diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.yml index 0da6ec2..13a5639 100644 --- a/.github/workflows/ci.yml +++ b/.github/workflows/ci.yml @@ -44,7 +44,7 @@ jobs: - run: tail -n 1 coverage.txt >> "$GITHUB_STEP_SUMMARY" build: - needs: test + needs: [test, version] strategy: fail-fast: false matrix: @@ -64,6 +64,14 @@ jobs: with: targets: ${{ matrix.target }} - uses: Swatinem/rust-cache@v2 + - shell: bash + env: + TAG: ${{ needs.version.outputs.tag }} + run: | + export VERSION="${TAG#v}" + perl -pi -e '$done ||= s/^version = "[^"]*"/version = "$ENV{VERSION}"/' Cargo.toml + perl -0pi -e 's/(name = "status_cli"\r?\nversion = )"[^"]*"/$1"$ENV{VERSION}"/' Cargo.lock + grep -m1 '^version' Cargo.toml - run: cargo build --release --locked --target ${{ matrix.target }} - if: runner.os == 'macOS' run: | @@ -202,16 +210,30 @@ jobs: fetch-depth: 0 - id: version run: | - tag="v$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n 1)" + base=$(sed -n 's/^version = "\(.*\)"/\1/p' Cargo.toml | head -n 1) + last=$(git tag --list 'v[0-9]*.[0-9]*.[0-9]*' --sort=-v:refname | head -n 1) publish=false - if [ "$GITHUB_REF" = "refs/heads/main" ] && ! git rev-parse -q --verify "refs/tags/$tag" >/dev/null; then - publish=true - elif [ "$GITHUB_REF" = "refs/tags/$tag" ]; then + if [ "$GITHUB_REF_TYPE" = "tag" ]; then + tag="$GITHUB_REF_NAME" publish=true + elif [ -z "$last" ]; then + tag="v$base" + else + current=${last#v} + major=${current%%.*} + rest=${current#*.} + next="$major.$((${rest%%.*} + 1)).0" + highest=$(printf '%s\n' "$next" "$base" | sort -V | tail -n 1) + tag="v$highest" + fi + if [ "$GITHUB_EVENT_NAME" = "push" ] && [ "$GITHUB_REF" = "refs/heads/main" ]; then + if [ -z "$last" ] || ! git diff --quiet "$last" HEAD -- src Cargo.toml Cargo.lock; then + publish=true + fi fi echo "tag=$tag" >> "$GITHUB_OUTPUT" echo "publish=$publish" >> "$GITHUB_OUTPUT" - echo "$tag publish=$publish" + echo "last=${last:-none} next=$tag publish=$publish" release: if: needs.version.outputs.publish == 'true' diff --git a/.gitignore b/.gitignore index a7288ed..26a8173 100644 --- a/.gitignore +++ b/.gitignore @@ -11,6 +11,7 @@ GEMINI.md .gemini/ .agy/ .agents/ +.serena/ .cursor/ .cursorrules .windsurf/ diff --git a/Cargo.lock b/Cargo.lock index 1d0052b..c062ace 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -26,6 +26,15 @@ version = "2.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ded4057c258ba199e2d26386d3af3780957ecaee6c4ef4041c6b4b8b97c0b06" +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "cfg-if" version = "1.0.5" @@ -38,6 +47,12 @@ version = "0.1.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fd16c4719339c4530435d38e511904438d07cce7950afa3718a84ac36c10e89e" +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "convert_case" version = "0.10.0" @@ -47,6 +62,15 @@ dependencies = [ "unicode-segmentation", ] +[[package]] +name = "cpufeatures" +version = "0.3.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5ca28b0ae3115b884660db4118d803791fd6756b6e88f39c0f3f7859060d7566" +dependencies = [ + "libc", +] + [[package]] name = "crossterm" version = "0.29.0" @@ -74,6 +98,15 @@ dependencies = [ "winapi", ] +[[package]] +name = "crypto-common" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + [[package]] name = "derive_more" version = "2.1.1" @@ -96,6 +129,17 @@ dependencies = [ "syn 2.0.119", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer", + "const-oid", + "crypto-common", +] + [[package]] name = "document-features" version = "0.2.12" @@ -144,6 +188,15 @@ version = "0.17.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ed5909b6e89a2db4456e54cd5f673791d7eca6732202bbf2a9cc504fe2f9b84a" +[[package]] +name = "hybrid-array" +version = "0.4.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "27f864f10dfb56725ce5ce5472bc52252c8f93a4ab86327122cebf62c5f59a17" +dependencies = [ + "typenum", +] + [[package]] name = "indexmap" version = "2.14.2" @@ -388,6 +441,17 @@ dependencies = [ "windows-sys", ] +[[package]] +name = "sha2" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" +dependencies = [ + "cfg-if", + "cpufeatures", + "digest", +] + [[package]] name = "shared_library" version = "0.1.9" @@ -449,6 +513,7 @@ dependencies = [ "portable-pty", "serde", "serde_json", + "sha2", "terminal_size", "toml_edit", "vt100", @@ -544,6 +609,12 @@ version = "1.1.3+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06bdbd8cfc056b8d2e2e85f29b56a3bdbecb527cef81eb39e3e7b98af4652770" +[[package]] +name = "typenum" +version = "1.20.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6f5e870be6c3b371b77fe0ee0bafb859fa4964b4404c27de1d380043c4dda20" + [[package]] name = "unicode-ident" version = "1.0.26" diff --git a/Cargo.toml b/Cargo.toml index 75b8999..80c20c0 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -12,6 +12,7 @@ crossterm = "0.29.0" portable-pty = "0.9.0" serde = { version = "1", features = ["derive"] } serde_json = "1" +sha2 = "0.11.0" terminal_size = "0.4.4" toml_edit = "0.25.16" vt100 = "0.16.2" diff --git a/README.md b/README.md index fc4fb4a..f9db580 100644 --- a/README.md +++ b/README.md @@ -38,8 +38,17 @@ in `~/.local/bin` and runs `status_cli setup`, which configures every host it fi copy of each file it changes. On Windows the folder is added to `PATH`; on Linux and macOS the host settings point at the binary's full path, so `PATH` does not matter. Open a new session afterwards. -`status_cli doctor` checks the result: version, `PATH`, each host's settings, the `codex-stt` shortcut and the -detected terminal and language. It exits with 1 when something is missing. +`status_cli doctor` checks the result: version, `PATH`, each host's settings and usage hooks, the `codex-stt` +shortcut and the detected terminal and language. It exits with 1 when something is missing. + +`status_cli update` moves to the latest GitHub release. It compares the release tag with the running version and stops +if there is nothing newer. Otherwise it downloads that release's binary for your system with `curl`, which ships with +Windows 10 and later, macOS and most Linux distributions. It checks the SHA-256 against the release's `SHA256SUMS`, +makes sure the new binary runs, and only then swaps it in place of the running one. Open sessions pick it up on their +next refresh. On Windows the running binary can't be overwritten, so it is renamed to `status_cli.old`, which the next +update deletes. Errors exit with 1 and leave the installed binary untouched. `STATUS_CLI_RELEASE_URL` (release JSON) +and `STATUS_CLI_BASE_URL` (asset folder) point it at another source, which is how the tests run it against a local +release. ### Install with an AI assistant @@ -117,21 +126,61 @@ describes it: the auto-compact window minus 33k tokens (about 967k on a 1M windo context unless `CLAUDE_CODE_AUTO_COMPACT_WINDOW` sets a smaller one, and `CLAUDE_AUTOCOMPACT_PCT_OVERRIDE` can only bring the threshold down. Values set through `autoCompactWindow` in settings are not read. -## Languages +## Usage limits for agents + +`status_cli setup` also hooks `status_cli guard` into every host, so the agent knows how much of the 5-hour and +weekly limits is used and when each one resets, without being asked: + +| Host | Where | When | +| --- | --- | --- | +| Claude Code | `hooks` in `settings.json` | every prompt (`UserPromptSubmit`), and before `Agent`, `Task` or `Workflow` | +| Codex CLI | `~/.codex/hooks.json` | session start and every prompt | +| agy | plugin in `~/.gemini/config/plugins/status_cli/` | session start, and before each model call near the limit | + +The agent reads a line such as `status_cli: session 57% (resets in 58m), week 21% (resets in 5d0h).` From 85% of +the session or 90% of the week it is also told to keep its task notes current and to ask before starting subagents +or workflows. From 95% of the session or 97% of the week it is told not to start new tasks: record what is done +and what comes next, tell the user, and stop. In Claude Code, subagents then need confirmation, and are blocked once +the limit is nearly exhausted. Codex has no confirmation step, so it only blocks. -Labels follow the system language: English, Spanish, Portuguese, French and Chinese, with English for anything -else. `STATUS_CLI_LANG` overrides it (`en`, `es`, `pt`, `fr`, `zh`); otherwise `LC_ALL`, `LC_MESSAGES` and `LANG` -are used, and the Windows display language when those are empty. +Claude Code and agy are read from the state the status line saves for that session; Codex is read from the session +file Codex itself writes, so it works with or without `codex-stt`. A window that already reset is not reported. +Codex runs only hooks you trust: after `status_cli setup`, approve the new ones once with `/hooks` in Codex. +Running setup again replaces the previous guard entries and leaves every other hook alone. -| | en | es | pt | fr | zh | -| --- | --- | --- | --- | --- | --- | -| 5-hour window | session | sesión | sessão | session | 会话 | -| Weekly window | week | semana | semana | semaine | 本周 | -| Auto-compact | compact | compactar | compactar | compacter | 压缩 | -| Context | context | contexto | contexto | contexte | 上下文 | -| Duration | time | tiempo | tempo | temps | 时长 | +## Languages -Chinese characters count as two columns, so the line keeps its width. +Labels follow the system language, with English for anything else. `STATUS_CLI_LANG` overrides it; otherwise +`LC_ALL`, `LC_MESSAGES` and `LANG` are used, and the Windows display language when those are empty. The first two +letters pick the language, so `pt`, `pt_BR` and `pt-PT` all give Brazilian Portuguese and `zh_TW` gives simplified +Chinese. + +| Code | Language | 5-hour window | Weekly window | Auto-compact | Context | Duration | +| --- | --- | --- | --- | --- | --- | --- | +| `en` | English | session | week | compact | context | time | +| `pt` | Portuguese (Brazil) | sessão | semana | compactar | contexto | tempo | +| `es` | Spanish | sesión | semana | compactar | contexto | tiempo | +| `zh` | Chinese (simplified) | 会话 | 本周 | 压缩 | 上下文 | 时长 | +| `hi` | Hindi | सत्र | सप्ताह | संक्षेपण | संदर्भ | समय | +| `ar` | Arabic | الجلسة | الأسبوع | الضغط | السياق | الوقت | +| `fr` | French | session | semaine | compacter | contexte | temps | +| `de` | German | Sitzung | Woche | verdichten | Kontext | Zeit | +| `ja` | Japanese | セッション | 今週 | 圧縮 | コンテキスト | 時間 | +| `ru` | Russian | сессия | неделя | сжатие | контекст | время | +| `ko` | Korean | 세션 | 주간 | 압축 | 컨텍스트 | 시간 | +| `it` | Italian | sessione | settimana | compattare | contesto | tempo | +| `id` | Indonesian | sesi | minggu | ringkas | konteks | waktu | +| `tr` | Turkish | oturum | hafta | sıkıştır | bağlam | süre | +| `vi` | Vietnamese | phiên | tuần | nén | ngữ cảnh | thời gian | +| `th` | Thai | เซสชัน | สัปดาห์ | บีบอัด | บริบท | เวลา | +| `bn` | Bengali | সেশন | সপ্তাহ | সংকোচন | প্রসঙ্গ | সময় | +| `ur` | Urdu | سیشن | ہفتہ | کمپیکٹ | سیاق | وقت | +| `pl` | Polish | sesja | tydzień | kompaktowanie | kontekst | czas | +| `nl` | Dutch | sessie | week | compacteren | context | tijd | + +Chinese, Japanese and Korean characters count as two columns and combining marks (Thai, Hindi, Bengali, Arabic +vowel signs) as none, so the line keeps its width. Arabic and Urdu are written in logical order; how they read +depends on the terminal's right-to-left support. The guard's messages to the agent use the same language. ## Configuration @@ -141,7 +190,7 @@ Everything works out of the box. These environment variables change the defaults | --- | --- | | `STATUS_CLI_COLOR` | `truecolor`, `256`, `16` or `none`, for terminals that do not advertise their depth (tmux, screen) | | `STATUS_CLI_ASCII` | ASCII instead of Unicode glyphs | -| `STATUS_CLI_LANG` | `en`, `es`, `pt`, `fr` or `zh` | +| `STATUS_CLI_LANG` | Language code from the table above, such as `en`, `pt`, `zh`, `ja` or `ar` | | `NO_COLOR` | No colors | | `STATUS_CLI_LOG` | JSON Lines log with per-phase timings, host, model, effort and the rendered line | | `STATUS_CLI_CODEX` | Program to run instead of `codex` in `codex-stt` | @@ -178,14 +227,18 @@ cargo llvm-cov --summary-only ``` The suite has unit tests beside each module and integration tests in `tests/`: `cli` (rendering), `matrix` (every -model, effort and mode), `i18n` (every language), `setup`, `codex`, `wrap` (Codex inside a real pseudo-terminal), +model, effort and mode), `i18n` (every language), `setup`, `guard` (usage hooks and their registration), `codex`, `wrap` (Codex inside a real pseudo-terminal), `regression` (one test per fixed bug) and `e2e` (install, configure, then run the configured command through the host's shell). CI runs them on every platform and reports coverage. Each feature in `src/features/` owns its parsing, rendering and tests; `payload`, `state`, `style`, `terminal` and -`layout` are shared. Releases are automatic: bump `version` in `Cargo.toml` and merge to `main`. Once every test, -shell and distro check passes, CI tags the commit, publishes the binaries with `SHA256SUMS` and installs them on -each platform. +`layout` are shared. Releases are automatic. Every push to `main` that changes `src/`, `Cargo.toml` or `Cargo.lock` +since the last `vX.Y.Z` tag ships the next minor version: `v1.1.0` becomes `v1.2.0`. CI writes that number into +`Cargo.toml` and `Cargo.lock` inside the runner before building, so nothing is committed back. The `version` in +`Cargo.toml` is a floor: raise it by hand for a major or a specific version, and CI uses it when it's higher. Pushes +that only touch docs or CI don't release. Once every test, shell and distro check passes, CI tags the commit, +publishes the binaries with `SHA256SUMS` and installs them on each platform. Local builds report the `Cargo.toml` +version, which can trail the latest release. ## License diff --git a/src/features.rs b/src/features.rs index 30c0fe3..1119676 100644 --- a/src/features.rs +++ b/src/features.rs @@ -1,8 +1,11 @@ pub mod clock; pub mod codex; pub mod context; +pub mod guard; +pub mod hooks; pub mod model; pub mod quota; pub mod setup; pub mod telemetry; +pub mod update; pub mod wrap; diff --git a/src/features/codex.rs b/src/features/codex.rs index e983671..4c337b7 100644 --- a/src/features/codex.rs +++ b/src/features/codex.rs @@ -82,7 +82,7 @@ impl Reader { } } -fn parse_session(file: &Path) -> Result> { +pub fn parse_session(file: &Path) -> Result> { let mut payload = Payload { product: Some("codex".to_owned()), ..Payload::default() }; for record in tail_records(file)?.iter().rev() { let body = &record["payload"]; diff --git a/src/features/guard.rs b/src/features/guard.rs new file mode 100644 index 0000000..e381439 --- /dev/null +++ b/src/features/guard.rs @@ -0,0 +1,259 @@ +use std::io::{self, Read}; +use std::path::Path; + +use serde::Deserialize; +use serde_json::{Value, json}; + +use crate::features::codex; +use crate::i18n::{ALL, labels}; +use crate::payload::{Host, Payload, Window}; +use crate::state::{self, Reading}; +use crate::style::duration; + +const MAX_INPUT_BYTES: u64 = 1 << 20; +const SESSION: Limits = Limits { near: 85.0, reached: 95.0 }; +const WEEK: Limits = Limits { near: 90.0, reached: 97.0 }; + +struct Limits { + near: f64, + reached: f64, +} + +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +enum Level { + Fine, + Near, + Reached, +} + +#[derive(Default, Deserialize)] +struct Input { + session_id: Option, + hook_event_name: Option, + transcript_path: Option, + #[serde(rename = "conversationId")] + conversation_id: Option, + #[serde(rename = "toolCall")] + tool_call: Option, + #[serde(rename = "invocationNum")] + invocation_num: Option, +} + +struct Usage { + session: Option, + week: Option, +} + +pub fn host(name: &str) -> Option { + match name { + "claude" => Some(Host::Claude), + "codex" => Some(Host::Codex), + "agy" => Some(Host::Agy), + _ => None, + } +} + +pub fn run(host: Host, dir: &Path, now: u64) -> Option { + let mut bytes = Vec::new(); + let reply = io::stdin() + .lock() + .take(MAX_INPUT_BYTES) + .read_to_end(&mut bytes) + .ok() + .and_then(|_| serde_json::from_slice::(bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(&bytes)).ok()) + .and_then(|input| respond(host, &input, &usage(host, &input, dir, now)?, now)); + reply.or_else(|| (host == Host::Agy).then(|| "{}".to_owned())) +} + +fn usage(host: Host, input: &Input, dir: &Path, now: u64) -> Option { + let usage = if host == Host::Codex { + let payload = input + .transcript_path + .as_deref() + .and_then(|path| codex::parse_session(Path::new(path)).ok()) + .filter(|payload| payload.rate_limits.is_some()) + .or_else(|| codex::Reader::latest().read(now).ok())? + .validated(); + let limits = payload.rate_limits?; + let reading = |window: Option| { + let window = window?; + Some(Reading { pct: window.used_percentage?, resets_at: window.resets_at.map(|s| (s * 1000.0) as u64) }) + }; + Usage { session: reading(limits.five_hour), week: reading(limits.seven_day) } + } else { + let key = Payload { + session_id: input.session_id.clone(), + conversation_id: input.conversation_id.clone(), + product: (host == Host::Agy).then(|| "antigravity".to_owned()), + ..Payload::default() + } + .session_key()?; + let session: Vec<&str> = ALL.iter().flat_map(|l| [l.session, l.quota]).collect(); + let week: Vec<&str> = ALL.iter().map(|l| l.week).collect(); + Usage { session: state::read(dir, &key, &session), week: state::read(dir, &key, &week) } + }; + let current = |reading: Option| reading.filter(|r| r.resets_at.is_none_or(|at| at > now)); + let usage = Usage { session: current(usage.session), week: current(usage.week) }; + (usage.session.is_some() || usage.week.is_some()).then_some(usage) +} + +impl Usage { + fn level(&self) -> Level { + let level = |reading: &Option, limits: &Limits| match reading.as_ref().map(|r| r.pct.round()) { + Some(pct) if pct >= limits.reached => Level::Reached, + Some(pct) if pct >= limits.near => Level::Near, + _ => Level::Fine, + }; + level(&self.session, &SESSION).max(level(&self.week, &WEEK)) + } + + fn summary(&self, level: Level, now: u64) -> String { + let l = labels(); + let part = |label: &str, reading: &Option| match reading { + None => format!("{label} ?"), + Some(Reading { pct, resets_at: Some(at) }) => { + format!("{label} {pct:.0}% ({} {})", l.resets_in, duration(at.saturating_sub(now))) + } + Some(Reading { pct, resets_at: None }) => format!("{label} {pct:.0}%"), + }; + let usage = format!("status_cli: {}, {}.", part(l.session, &self.session), part(l.week, &self.week)); + match level { + Level::Fine => usage, + Level::Near => format!("{usage} {}", l.limit_near), + Level::Reached => format!("{usage} {}", l.limit_reached), + } + } +} + +fn respond(host: Host, input: &Input, usage: &Usage, now: u64) -> Option { + let level = usage.level(); + let text = usage.summary(level, now); + let reply = match host { + Host::Agy => match (&input.tool_call, input.invocation_num) { + (Some(_), _) => return None, + (None, Some(_)) if level == Level::Fine => json!({}), + _ => json!({ "injectSteps": [{ "ephemeralMessage": text }] }), + }, + Host::Claude | Host::Codex => match input.hook_event_name.as_deref()? { + "PreToolUse" => { + let decision = match level { + Level::Reached => "deny", + Level::Near if host == Host::Claude => "ask", + _ => return None, + }; + json!({ "hookSpecificOutput": { + "hookEventName": "PreToolUse", + "permissionDecision": decision, + "permissionDecisionReason": text, + } }) + } + event @ ("UserPromptSubmit" | "SessionStart") => { + json!({ "hookSpecificOutput": { "hookEventName": event, "additionalContext": text } }) + } + _ => return None, + }, + }; + Some(reply.to_string()) +} + +#[cfg(test)] +mod tests { + use std::fs; + + use super::*; + + const NOW: u64 = 1_000_000_000; + + fn usage(session: f64, week: f64) -> Usage { + Usage { + session: Some(Reading { pct: session, resets_at: Some(NOW + 70 * 60_000) }), + week: Some(Reading { pct: week, resets_at: Some(NOW + 5 * 86_400_000) }), + } + } + + fn event(name: &str) -> Input { + Input { hook_event_name: Some(name.to_owned()), ..Input::default() } + } + + fn reply(host: Host, input: &Input, usage: &Usage) -> Option { + respond(host, input, usage, NOW).map(|text| serde_json::from_str(&text).unwrap()) + } + + #[test] + fn levels_follow_the_session_and_week_limits() { + assert_eq!(usage(50.0, 20.0).level(), Level::Fine); + assert_eq!(usage(85.0, 20.0).level(), Level::Near); + assert_eq!(usage(94.6, 20.0).level(), Level::Reached); + assert_eq!(usage(10.0, 90.0).level(), Level::Near); + assert_eq!(usage(10.0, 97.0).level(), Level::Reached); + } + + #[test] + fn summary_shows_usage_and_time_to_reset() { + let fine = usage(53.0, 20.0); + assert_eq!( + fine.summary(Level::Fine, NOW), + "status_cli: sessão 53% (reinicia em 1h10m), semana 20% (reinicia em 5d0h)." + ); + let full = usage(96.0, 20.0); + assert!(full.summary(full.level(), NOW).ends_with(labels().limit_reached)); + } + + #[test] + fn prompt_events_always_get_context() { + let out = reply(Host::Codex, &event("UserPromptSubmit"), &usage(10.0, 10.0)).unwrap(); + assert_eq!(out["hookSpecificOutput"]["hookEventName"], "UserPromptSubmit"); + assert!(out["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("10%")); + assert!(reply(Host::Claude, &event("Stop"), &usage(99.0, 10.0)).is_none()); + } + + #[test] + fn tools_are_gated_only_near_the_limit() { + let tool = event("PreToolUse"); + assert!(reply(Host::Claude, &tool, &usage(50.0, 10.0)).is_none()); + let decision = |host, u| reply(host, &tool, &u).map(|v| v["hookSpecificOutput"]["permissionDecision"].clone()); + assert_eq!(decision(Host::Claude, usage(88.0, 10.0)), Some(json!("ask"))); + assert_eq!(decision(Host::Codex, usage(88.0, 10.0)), None); + assert_eq!(decision(Host::Codex, usage(96.0, 10.0)), Some(json!("deny"))); + } + + #[test] + fn agy_injects_at_start_and_on_invocations_near_the_limit() { + let start = reply(Host::Agy, &Input::default(), &usage(10.0, 10.0)).unwrap(); + assert!(start["injectSteps"][0]["ephemeralMessage"].as_str().unwrap().contains("10%")); + let invocation = Input { invocation_num: Some(3), ..Input::default() }; + assert_eq!(reply(Host::Agy, &invocation, &usage(10.0, 10.0)), Some(json!({}))); + assert!(reply(Host::Agy, &invocation, &usage(90.0, 10.0)).unwrap()["injectSteps"].is_array()); + } + + #[test] + fn reads_the_saved_state_and_drops_windows_that_already_reset() { + let dir = std::env::temp_dir().join(format!("status_cli-guard-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let state = format!( + r#"{{"gauges":{{"session":{{"from":1,"to":91,"changed_at":0,"resets_at":{}}},"week":{{"from":1,"to":40,"changed_at":0,"resets_at":{}}}}}}}"#, + NOW + 60_000, + NOW - 1 + ); + fs::write(dir.join("status_cli-abc"), state).unwrap(); + let input = Input { session_id: Some("abc".to_owned()), ..Input::default() }; + let read = super::usage(Host::Claude, &input, &dir, NOW).unwrap(); + assert_eq!(read.session.map(|r| r.pct), Some(91.0)); + assert!(read.week.is_none()); + assert!(super::usage(Host::Agy, &input, &dir, NOW).is_none()); + fs::remove_dir_all(&dir).unwrap(); + } + + #[test] + fn codex_reads_limits_from_the_transcript() { + let dir = std::env::temp_dir().join(format!("status_cli-guard-codex-{}", std::process::id())); + fs::create_dir_all(&dir).unwrap(); + let file = dir.join("rollout-1.jsonl"); + let record = r#"{"type":"event_msg","payload":{"type":"token_count","info":null,"rate_limits":{"primary":{"used_percent":96.0,"window_minutes":300,"resets_at":2000000}}}}"#; + fs::write(&file, format!("{record}\n")).unwrap(); + let input = Input { transcript_path: Some(file.to_string_lossy().into_owned()), ..Input::default() }; + let read = super::usage(Host::Codex, &input, &dir, NOW).unwrap(); + assert_eq!(read.level(), Level::Reached); + fs::remove_dir_all(&dir).unwrap(); + } +} diff --git a/src/features/hooks.rs b/src/features/hooks.rs new file mode 100644 index 0000000..21aa74c --- /dev/null +++ b/src/features/hooks.rs @@ -0,0 +1,107 @@ +use serde_json::{Map, Value, json}; + +const TIMEOUT_SECS: u64 = 10; +pub const AGY_PLUGIN: &str = "status_cli"; +const AGY_HOOK: &str = "status_cli-guard"; + +pub struct Event { + pub name: &'static str, + pub matcher: Option<&'static str>, +} + +pub const CLAUDE_EVENTS: &[Event] = &[ + Event { name: "UserPromptSubmit", matcher: None }, + Event { name: "PreToolUse", matcher: Some("Agent|Task|Workflow") }, +]; +pub const CODEX_EVENTS: &[Event] = + &[Event { name: "SessionStart", matcher: None }, Event { name: "UserPromptSubmit", matcher: None }]; + +pub fn command(binary: &str, host: &str) -> String { + format!("{binary} guard {host}") +} + +pub fn is_guard(text: &str) -> bool { + text.contains("status_cli") && text.contains(" guard ") +} + +pub fn merge(hooks: &mut Map, events: &[Event], command: &str) { + for groups in hooks.values_mut() { + if let Value::Array(groups) = groups { + groups.retain(|group| !mentions_guard(group)); + } + } + hooks.retain(|_, groups| groups.as_array().is_none_or(|groups| !groups.is_empty())); + for event in events { + let mut group = Map::new(); + if let Some(matcher) = event.matcher { + group.insert("matcher".to_owned(), json!(matcher)); + } + group.insert("hooks".to_owned(), json!([{ "type": "command", "command": command, "timeout": TIMEOUT_SECS }])); + let groups = hooks.entry(event.name).or_insert_with(|| json!([])); + if let Value::Array(groups) = groups { + groups.push(Value::Object(group)); + } else { + *groups = json!([group]); + } + } +} + +fn mentions_guard(group: &Value) -> bool { + group["hooks"].as_array().is_some_and(|hooks| hooks.iter().any(|h| h["command"].as_str().is_some_and(is_guard))) +} + +pub fn agy_plugin(command: &str) -> (String, String) { + let handler = json!([{ "type": "command", "command": command, "timeout": TIMEOUT_SECS }]); + let manifest = json!({ + "name": AGY_PLUGIN, + "version": env!("CARGO_PKG_VERSION"), + "description": "Tells the agent how much of the session and weekly usage is left", + }); + let hooks = json!({ AGY_HOOK: { "enabled": true, "SessionStart": handler, "PreInvocation": handler } }); + (pretty(&manifest), pretty(&hooks)) +} + +fn pretty(value: &Value) -> String { + serde_json::to_string_pretty(value).unwrap_or_default() + "\n" +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn merge_replaces_old_guard_entries_and_keeps_other_hooks() { + let mut hooks = json!({ + "PreToolUse": [ + { "matcher": "Bash", "hooks": [{ "type": "command", "command": "rtk hook" }] }, + { "matcher": "Agent", "hooks": [{ "type": "command", "command": "status_cli guard claude" }] } + ], + "UserPromptSubmit": [{ "hooks": [{ "type": "command", "command": "'/opt/status_cli' guard claude" }] }] + }); + let map = hooks.as_object_mut().unwrap(); + merge(map, CLAUDE_EVENTS, "status_cli guard claude"); + merge(map, CLAUDE_EVENTS, "status_cli guard claude"); + assert_eq!(hooks["PreToolUse"].as_array().unwrap().len(), 2); + assert_eq!(hooks["PreToolUse"][0]["hooks"][0]["command"], "rtk hook"); + assert_eq!(hooks["PreToolUse"][1]["matcher"], "Agent|Task|Workflow"); + assert_eq!(hooks["UserPromptSubmit"].as_array().unwrap().len(), 1); + assert!(hooks["UserPromptSubmit"][0].get("matcher").is_none()); + } + + #[test] + fn merge_drops_events_left_empty() { + let mut hooks = json!({ "Stop": [{ "hooks": [{ "command": "status_cli guard codex" }] }] }); + merge(hooks.as_object_mut().unwrap(), CODEX_EVENTS, "status_cli guard codex"); + assert!(hooks.get("Stop").is_none()); + assert!(hooks["SessionStart"].is_array()); + } + + #[test] + fn agy_plugin_hooks_start_and_every_invocation() { + let (manifest, hooks) = agy_plugin("status_cli guard agy"); + assert!(manifest.contains(r#""name": "status_cli""#)); + let hooks: Value = serde_json::from_str(&hooks).unwrap(); + assert_eq!(hooks[AGY_HOOK]["PreInvocation"][0]["command"], "status_cli guard agy"); + assert!(is_guard(hooks[AGY_HOOK]["SessionStart"][0]["command"].as_str().unwrap())); + } +} diff --git a/src/features/quota.rs b/src/features/quota.rs index 4800d12..0a4172e 100644 --- a/src/features/quota.rs +++ b/src/features/quota.rs @@ -23,12 +23,10 @@ pub struct Quota { } pub fn read(payload: &Payload, now: u64, session: &mut Session) -> Vec { - let mut quota = |label, pct, resets_at, window, show_reset| Quota { - label, - motion: session.track(label, pct), - resets_at, - window, - show_reset, + let mut quota = |label, pct, resets_at, window, show_reset| { + let motion = session.track(label, pct); + session.resets(label, resets_at); + Quota { label, motion, resets_at, window, show_reset } }; match payload.host() { Host::Claude | Host::Codex => { @@ -214,6 +212,13 @@ mod tests { assert_eq!(lines(json, false), ["cota 25% ↻ 2m"]); } + #[test] + fn agy_reads_reset_time_when_seconds_are_missing() { + let json = r#"{"product":"antigravity","model":{"id":"gemini-3-pro"}, + "quota":{"gemini-3-pro":{"remaining_fraction":0.5,"reset_time":"1969-12-31T21:20:00-03:00"}}}"#; + assert_eq!(lines(json, false), ["cota 50% ↻ 3m"]); + } + const AGY_QUOTA: &str = r#""quota":{"3p-5h":{"remaining_fraction":1,"reset_in_seconds":18001}, "3p-weekly":{"remaining_fraction":0.0004,"reset_in_seconds":204931}, "gemini-5h":{"remaining_fraction":0.9989992,"reset_in_seconds":17279}, diff --git a/src/features/setup.rs b/src/features/setup.rs index 26e1b9f..5f37de7 100644 --- a/src/features/setup.rs +++ b/src/features/setup.rs @@ -6,18 +6,23 @@ use std::path::{Path, PathBuf}; use serde_json::{Map, Value, json}; use toml_edit::{Array, DocumentMut, Item, Table, value}; +use crate::features::hooks::{self, Event}; + pub const CODEX_ALIAS: &str = "codex-stt"; const CODEX_STATUS_ITEMS: [&str; 4] = ["model-with-reasoning", "five-hour-limit", "weekly-limit", "context-used"]; enum Config { - Json(Value), + Json { status_line: Option, guard: Option<(&'static [Event], &'static str)> }, CodexToml, + AgyPlugin, } struct Host { name: &'static str, settings: PathBuf, + installed: PathBuf, config: Config, + note: Option<&'static str>, } pub fn run() -> Vec> { @@ -27,12 +32,16 @@ pub fn run() -> Vec> { let mut outcomes: Vec> = hosts(&home) .into_iter() .map(|host| { - let outcome = match host.settings.parent() { - Some(dir) if dir.is_dir() => configure(&host).map(|backup| match backup { - Some(backup) => format!("configured (backup: {})", backup.display()), - None => "configured".to_owned(), - }), - _ => Ok("not installed, skipped".to_owned()), + let outcome = if host.installed.is_dir() { + configure(&host).map(|backup| { + let note = host.note.map(|note| format!("; {note}")).unwrap_or_default(); + match backup { + Some(backup) => format!("configured (backup: {}){note}", backup.display()), + None => format!("configured{note}"), + } + }) + } else { + Ok("not installed, skipped".to_owned()) }; match outcome { Ok(message) => Ok(format!("{}: {message} -> {}", host.name, host.settings.display())), @@ -99,12 +108,14 @@ pub fn doctor() -> (Vec, bool) { }; let mut configured = 0; for host in hosts(&home) { - let marker = match host.config { - Config::Json(_) => "status_cli", - Config::CodexToml => "status_line", - }; - let installed = host.settings.parent().is_some_and(Path::is_dir); - let ready = fs::read_to_string(&host.settings).is_ok_and(|text| text.contains(marker)); + let installed = host.installed.is_dir(); + let ready = fs::read_to_string(&host.settings).is_ok_and(|text| match &host.config { + Config::Json { status_line, guard } => { + (status_line.is_none() || text.contains("status_cli")) && (guard.is_none() || hooks::is_guard(&text)) + } + Config::CodexToml => text.contains("status_line"), + Config::AgyPlugin => hooks::is_guard(&text), + }); lines.push(match (installed, ready) { (false, _) => format!("skip {} is not installed", host.name), (true, true) => { @@ -139,24 +150,53 @@ pub fn doctor() -> (Vec, bool) { (lines, healthy) } -fn hosts(home: &Path) -> [Host; 3] { +fn hosts(home: &Path) -> [Host; 5] { let command = command(); let config_dir = |var: &str, default: PathBuf| env::var_os(var).map_or(default, PathBuf::from); + let claude = config_dir("CLAUDE_CONFIG_DIR", home.join(".claude")); + let agy = home.join(".gemini").join("antigravity-cli"); + let codex = config_dir("CODEX_HOME", home.join(".codex")); [ Host { name: "Claude Code", - settings: config_dir("CLAUDE_CONFIG_DIR", home.join(".claude")).join("settings.json"), - config: Config::Json(json!({ "type": "command", "command": command, "refreshInterval": 1 })), + settings: claude.join("settings.json"), + installed: claude, + config: Config::Json { + status_line: Some(json!({ "type": "command", "command": command, "refreshInterval": 1 })), + guard: Some((hooks::CLAUDE_EVENTS, "claude")), + }, + note: None, }, Host { name: "Antigravity CLI", - settings: home.join(".gemini").join("antigravity-cli").join("settings.json"), - config: Config::Json(json!({ "type": "command", "command": command, "enabled": true })), + settings: agy.join("settings.json"), + installed: agy.clone(), + config: Config::Json { + status_line: Some(json!({ "type": "command", "command": command, "enabled": true })), + guard: None, + }, + note: None, + }, + Host { + name: "Antigravity CLI usage guard", + settings: home.join(".gemini").join("config").join("plugins").join(hooks::AGY_PLUGIN).join("hooks.json"), + installed: agy, + config: Config::AgyPlugin, + note: None, }, Host { name: "Codex CLI", - settings: config_dir("CODEX_HOME", home.join(".codex")).join("config.toml"), + settings: codex.join("config.toml"), + installed: codex.clone(), config: Config::CodexToml, + note: None, + }, + Host { + name: "Codex CLI usage guard", + settings: codex.join("hooks.json"), + installed: codex, + config: Config::Json { status_line: None, guard: Some((hooks::CODEX_EVENTS, "codex")) }, + note: Some("trust the new hooks once with /hooks in Codex"), }, ] } @@ -184,8 +224,15 @@ fn configure(host: &Host) -> Result, Box> { }; let text = existing.as_deref().map(|bytes| bytes.strip_prefix(b"\xEF\xBB\xBF").unwrap_or(bytes)); let updated = match &host.config { - Config::Json(status_line) => merge_json(text, status_line)?, + Config::Json { status_line, guard } => merge_json(text, status_line.as_ref(), *guard)?, Config::CodexToml => merge_codex(text.map(std::str::from_utf8).transpose()?.unwrap_or_default())?, + Config::AgyPlugin => { + let (manifest, hooks) = hooks::agy_plugin(&hooks::command(&command(), "agy")); + let dir = host.settings.parent().ok_or("plugin directory not found")?; + fs::create_dir_all(dir)?; + fs::write(dir.join("plugin.json"), manifest)?; + hooks + } }; let backup = match existing { Some(bytes) => { @@ -201,20 +248,30 @@ fn configure(host: &Host) -> Result, Box> { Ok(backup) } -fn merge_json(existing: Option<&[u8]>, wanted: &Value) -> Result> { +fn merge_json( + existing: Option<&[u8]>, + wanted: Option<&Value>, + guard: Option<(&[Event], &str)>, +) -> Result> { let mut settings = match existing.map(serde_json::from_slice).transpose()? { Some(Value::Object(map)) => map, Some(_) => return Err("settings file is not a JSON object".into()), None => Map::new(), }; - let mut status_line = match settings.remove("statusLine") { - Some(Value::Object(map)) => map, - _ => Map::new(), - }; - if let Value::Object(wanted) = wanted { + if let Some(Value::Object(wanted)) = wanted { + let mut status_line = match settings.remove("statusLine") { + Some(Value::Object(map)) => map, + _ => Map::new(), + }; status_line.extend(wanted.clone()); + settings.insert("statusLine".to_owned(), Value::Object(status_line)); + } + if let Some((events, host)) = guard { + let Value::Object(map) = settings.entry("hooks").or_insert_with(|| json!({})) else { + return Err("\"hooks\" in the settings file is not a JSON object".into()); + }; + hooks::merge(map, events, &hooks::command(&command(), host)); } - settings.insert("statusLine".to_owned(), Value::Object(status_line)); Ok(serde_json::to_string_pretty(&Value::Object(settings))? + "\n") } diff --git a/src/features/update.rs b/src/features/update.rs new file mode 100644 index 0000000..43b69cb --- /dev/null +++ b/src/features/update.rs @@ -0,0 +1,136 @@ +use std::env; +use std::fs; +use std::path::Path; +use std::process::Command; + +use serde::Deserialize; +use sha2::{Digest, Sha256}; + +const REPO: &str = "Isllanrx/status_cli"; +const MAX_SECONDS: &str = "120"; + +#[derive(Deserialize)] +struct Release { + tag_name: String, +} + +pub fn run() -> Result { + let current = env!("CARGO_PKG_VERSION"); + let release_url = env::var("STATUS_CLI_RELEASE_URL") + .unwrap_or_else(|_| format!("https://api.github.com/repos/{REPO}/releases/latest")); + let release: Release = serde_json::from_slice(&fetch(&release_url)?) + .map_err(|err| format!("unreadable release from {release_url}: {err}"))?; + let latest = release.tag_name.trim_start_matches('v'); + let latest_version = version(latest).ok_or_else(|| format!("unreadable release tag {}", release.tag_name))?; + if version(current).is_some_and(|current| latest_version <= current) { + return Ok(format!("status_cli {current} is up to date (latest release {latest})")); + } + let asset = asset(env::consts::OS, env::consts::ARCH) + .ok_or_else(|| format!("no release asset for {} {}", env::consts::OS, env::consts::ARCH))?; + let base = env::var("STATUS_CLI_BASE_URL") + .unwrap_or_else(|_| format!("https://github.com/{REPO}/releases/download/{}", release.tag_name)); + let sums = String::from_utf8_lossy(&fetch(&format!("{base}/SHA256SUMS"))?).into_owned(); + let expected = checksum(&sums, asset).ok_or_else(|| format!("no checksum published for {asset}"))?; + let binary = fetch(&format!("{base}/{asset}"))?; + if hex(&Sha256::digest(&binary)) != expected.to_ascii_lowercase() { + return Err(format!("checksum mismatch for {asset}")); + } + let target = env::current_exe().map_err(|err| format!("cannot locate the running binary: {err}"))?; + replace(&target, &binary)?; + Ok(format!("Updated status_cli {current} -> {latest} at {}", target.display())) +} + +fn fetch(url: &str) -> Result, String> { + let out = Command::new("curl") + .args(["-fsSL", "--retry", "3", "--max-time", MAX_SECONDS, url]) + .output() + .map_err(|err| format!("curl is required to update: {err}"))?; + if !out.status.success() { + return Err(format!("download failed: {url}: {}", String::from_utf8_lossy(&out.stderr).trim())); + } + Ok(out.stdout) +} + +fn version(text: &str) -> Option> { + text.split(['-', '+']).next()?.split('.').map(|part| part.parse().ok()).collect() +} + +fn asset(os: &str, arch: &str) -> Option<&'static str> { + Some(match (os, arch) { + ("windows", "x86_64") => "status_cli-x86_64-pc-windows-msvc.exe", + ("windows", "aarch64") => "status_cli-aarch64-pc-windows-msvc.exe", + ("linux", "x86_64") => "status_cli-x86_64-unknown-linux-musl", + ("linux", "aarch64") => "status_cli-aarch64-unknown-linux-musl", + ("macos", _) => "status_cli-universal-apple-darwin", + _ => return None, + }) +} + +fn checksum<'a>(sums: &'a str, asset: &str) -> Option<&'a str> { + sums.lines().find_map(|line| { + let mut fields = line.split_whitespace(); + let digest = fields.next()?; + (fields.next()?.trim_start_matches('*') == asset).then_some(digest) + }) +} + +fn hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() +} + +fn replace(target: &Path, binary: &[u8]) -> Result<(), String> { + let staged = target.with_extension("new"); + let old = target.with_extension("old"); + let _ = fs::remove_file(&old); + fs::write(&staged, binary).map_err(|err| format!("cannot write {}: {err}", staged.display()))?; + #[cfg(unix)] + { + use std::os::unix::fs::PermissionsExt; + fs::set_permissions(&staged, fs::Permissions::from_mode(0o755)) + .map_err(|err| format!("cannot mark {} executable: {err}", staged.display()))?; + } + let runs = Command::new(&staged).arg("--version").output().is_ok_and(|out| out.status.success()); + if !runs { + let _ = fs::remove_file(&staged); + return Err(format!("downloaded binary does not run on this system: {}", staged.display())); + } + if cfg!(windows) { + fs::rename(target, &old).map_err(|err| format!("cannot move {} aside: {err}", target.display()))?; + } + if let Err(err) = fs::rename(&staged, target) { + if cfg!(windows) { + let _ = fs::rename(&old, target); + } + let _ = fs::remove_file(&staged); + return Err(format!("cannot install {}: {err}", target.display())); + } + let _ = fs::remove_file(&old); + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn compares_versions_numerically() { + assert!(version("1.10.0") > version("1.9.3")); + assert_eq!(version("1.2.0-rc.1"), Some(vec![1, 2, 0])); + assert_eq!(version("latest"), None); + } + + #[test] + fn picks_the_published_asset_per_platform() { + assert_eq!(asset("windows", "x86_64"), Some("status_cli-x86_64-pc-windows-msvc.exe")); + assert_eq!(asset("linux", "aarch64"), Some("status_cli-aarch64-unknown-linux-musl")); + assert_eq!(asset("macos", "aarch64"), Some("status_cli-universal-apple-darwin")); + assert_eq!(asset("freebsd", "x86_64"), None); + } + + #[test] + fn finds_the_checksum_of_the_asset() { + let sums = "aa status_cli-x86_64-unknown-linux-musl\nBB *status_cli-x86_64-pc-windows-msvc.exe\n"; + assert_eq!(checksum(sums, "status_cli-x86_64-pc-windows-msvc.exe"), Some("BB")); + assert_eq!(checksum(sums, "status_cli-universal-apple-darwin"), None); + } +} diff --git a/src/i18n.rs b/src/i18n.rs deleted file mode 100644 index 7562b23..0000000 --- a/src/i18n.rs +++ /dev/null @@ -1,112 +0,0 @@ -use std::env; -use std::sync::OnceLock; - -pub struct Labels { - pub code: &'static str, - pub session: &'static str, - pub week: &'static str, - pub compact: &'static str, - pub context: &'static str, - pub quota: &'static str, - pub time: &'static str, -} - -const ENGLISH: Labels = Labels { - code: "en", - session: "session", - week: "week", - compact: "compact", - context: "context", - quota: "quota", - time: "time", -}; -const SPANISH: Labels = Labels { - code: "es", - session: "sesión", - week: "semana", - compact: "compactar", - context: "contexto", - quota: "cuota", - time: "tiempo", -}; -const PORTUGUESE: Labels = Labels { - code: "pt", - session: "sessão", - week: "semana", - compact: "compactar", - context: "contexto", - quota: "cota", - time: "tempo", -}; -const FRENCH: Labels = Labels { - code: "fr", - session: "session", - week: "semaine", - compact: "compacter", - context: "contexte", - quota: "quota", - time: "temps", -}; -const CHINESE: Labels = Labels { - code: "zh", - session: "会话", - week: "本周", - compact: "压缩", - context: "上下文", - quota: "配额", - time: "时长", -}; - -pub fn labels() -> &'static Labels { - if cfg!(test) { - return &PORTUGUESE; - } - static LABELS: OnceLock<&'static Labels> = OnceLock::new(); - LABELS.get_or_init(|| { - let requested = ["STATUS_CLI_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] - .into_iter() - .filter_map(|name| env::var(name).ok()) - .find(|value| !value.is_empty() && value != "C" && value != "POSIX"); - for_locale(&requested.or_else(system_locale).unwrap_or_default()) - }) -} - -fn for_locale(locale: &str) -> &'static Labels { - match locale.get(..2).map(str::to_ascii_lowercase).as_deref() { - Some("es") => &SPANISH, - Some("pt") => &PORTUGUESE, - Some("fr") => &FRENCH, - Some("zh") => &CHINESE, - _ => &ENGLISH, - } -} - -#[cfg(windows)] -fn system_locale() -> Option { - use windows_sys::Win32::Globalization::GetUserDefaultLocaleName; - - let mut buffer = [0u16; 85]; - let len = unsafe { GetUserDefaultLocaleName(buffer.as_mut_ptr(), buffer.len() as i32) }; - (len > 1).then(|| String::from_utf16_lossy(&buffer[..len as usize - 1])) -} - -#[cfg(not(windows))] -fn system_locale() -> Option { - None -} - -#[cfg(test)] -mod tests { - use super::*; - - #[test] - fn locales_map_to_the_five_languages() { - assert_eq!(for_locale("pt_BR.UTF-8").session, "sessão"); - assert_eq!(for_locale("es-ES").session, "sesión"); - assert_eq!(for_locale("fr_FR").week, "semaine"); - assert_eq!(for_locale("zh_CN.UTF-8").session, "会话"); - assert_eq!(for_locale("en_US").session, "session"); - assert_eq!(for_locale("de_DE").session, "session"); - assert_eq!(for_locale("").session, "session"); - } -} diff --git a/src/i18n/latin.rs b/src/i18n/latin.rs new file mode 100644 index 0000000..9c91520 --- /dev/null +++ b/src/i18n/latin.rs @@ -0,0 +1,184 @@ +use super::Labels; + +pub const ENGLISH: Labels = Labels { + code: "en", + session: "session", + week: "week", + compact: "compact", + context: "context", + quota: "quota", + time: "time", + resets_in: "resets in", + limit_near: "Usage limit close: before starting long work, tell the user these percentages, keep the task notes \ + current (done and next steps) and ask before starting subagents or workflows.", + limit_reached: "Usage limit nearly exhausted: do not start new tasks. Record what is done and the next steps in \ + the task notes, tell the user these percentages and when the limit resets, and stop.", +}; + +pub const PORTUGUESE: Labels = Labels { + code: "pt-BR", + session: "sessão", + week: "semana", + compact: "compactar", + context: "contexto", + quota: "cota", + time: "tempo", + resets_in: "reinicia em", + limit_near: "Limite de uso próximo: antes de trabalho longo, avise o usuário com estes percentuais, mantenha as \ + notas da tarefa atualizadas (feito e próximos passos) e confirme antes de abrir subagentes ou \ + workflows.", + limit_reached: "Limite de uso quase esgotado: não comece tarefas novas. Registre o que foi feito e os próximos \ + passos nas notas da tarefa, avise o usuário com estes percentuais e quando o limite reinicia, e \ + pare.", +}; + +pub const SPANISH: Labels = Labels { + code: "es", + session: "sesión", + week: "semana", + compact: "compactar", + context: "contexto", + quota: "cuota", + time: "tiempo", + resets_in: "se reinicia en", + limit_near: "Límite de uso cercano: antes de un trabajo largo, informa al usuario de estos porcentajes, mantén al \ + día las notas de la tarea (hecho y próximos pasos) y pide confirmación antes de iniciar subagentes o \ + workflows.", + limit_reached: "Límite de uso casi agotado: no empieces tareas nuevas. Registra lo hecho y los próximos pasos en \ + las notas de la tarea, informa al usuario de estos porcentajes y de cuándo se reinicia el límite, \ + y detente.", +}; + +pub const FRENCH: Labels = Labels { + code: "fr", + session: "session", + week: "semaine", + compact: "compacter", + context: "contexte", + quota: "quota", + time: "temps", + resets_in: "réinitialisé dans", + limit_near: "Limite d'utilisation proche : avant un travail long, indique ces pourcentages à l'utilisateur, tiens \ + à jour les notes de la tâche (fait et prochaines étapes) et demande confirmation avant de lancer des \ + sous-agents ou des workflows.", + limit_reached: "Limite d'utilisation presque atteinte : ne commence pas de nouvelle tâche. Note ce qui est fait \ + et les prochaines étapes dans les notes de la tâche, indique ces pourcentages à l'utilisateur et \ + quand la limite se réinitialise, puis arrête-toi.", +}; + +pub const GERMAN: Labels = Labels { + code: "de", + session: "Sitzung", + week: "Woche", + compact: "verdichten", + context: "Kontext", + quota: "Kontingent", + time: "Zeit", + resets_in: "zurückgesetzt in", + limit_near: "Nutzungslimit nahe: Vor längerer Arbeit dem Nutzer diese Prozentwerte nennen, die Aufgabennotizen \ + aktuell halten (erledigt und nächste Schritte) und vor dem Start von Subagenten oder Workflows \ + nachfragen.", + limit_reached: "Nutzungslimit fast erschöpft: Keine neuen Aufgaben beginnen. Erledigtes und nächste Schritte in \ + den Aufgabennotizen festhalten, dem Nutzer diese Prozentwerte und den Zeitpunkt des \ + Zurücksetzens nennen und aufhören.", +}; + +pub const ITALIAN: Labels = Labels { + code: "it", + session: "sessione", + week: "settimana", + compact: "compattare", + context: "contesto", + quota: "quota", + time: "tempo", + resets_in: "si azzera tra", + limit_near: "Limite di utilizzo vicino: prima di un lavoro lungo, comunica all'utente queste percentuali, tieni \ + aggiornate le note dell'attività (fatto e prossimi passi) e chiedi conferma prima di avviare \ + subagenti o workflow.", + limit_reached: "Limite di utilizzo quasi esaurito: non iniziare nuove attività. Registra ciò che è stato fatto e \ + i prossimi passi nelle note dell'attività, comunica all'utente queste percentuali e quando il \ + limite si azzera, poi fermati.", +}; + +pub const DUTCH: Labels = Labels { + code: "nl", + session: "sessie", + week: "week", + compact: "compacteren", + context: "context", + quota: "quotum", + time: "tijd", + resets_in: "reset over", + limit_near: "Gebruikslimiet bijna bereikt: meld de gebruiker vóór langer werk deze percentages, houd de \ + taaknotities bij (gedaan en volgende stappen) en vraag bevestiging voordat je subagents of \ + workflows start.", + limit_reached: "Gebruikslimiet bijna op: begin geen nieuwe taken. Leg vast wat gedaan is en de volgende stappen \ + in de taaknotities, meld de gebruiker deze percentages en wanneer de limiet reset, en stop.", +}; + +pub const POLISH: Labels = Labels { + code: "pl", + session: "sesja", + week: "tydzień", + compact: "kompaktowanie", + context: "kontekst", + quota: "limit", + time: "czas", + resets_in: "reset za", + limit_near: "Limit użycia blisko: przed dłuższą pracą podaj użytkownikowi te wartości procentowe, aktualizuj \ + notatki zadania (zrobione i kolejne kroki) i pytaj o zgodę przed uruchomieniem subagentów lub \ + workflowów.", + limit_reached: "Limit użycia prawie wyczerpany: nie zaczynaj nowych zadań. Zapisz, co zrobiono, i kolejne kroki \ + w notatkach zadania, podaj użytkownikowi te wartości procentowe i kiedy limit się odnowi, i \ + zakończ.", +}; + +pub const INDONESIAN: Labels = Labels { + code: "id", + session: "sesi", + week: "minggu", + compact: "ringkas", + context: "konteks", + quota: "kuota", + time: "waktu", + resets_in: "reset dalam", + limit_near: "Batas pemakaian hampir tercapai: sebelum pekerjaan panjang, beri tahu pengguna persentase ini, \ + perbarui catatan tugas (selesai dan langkah berikutnya), dan minta konfirmasi sebelum menjalankan \ + subagen atau workflow.", + limit_reached: "Batas pemakaian hampir habis: jangan mulai tugas baru. Catat yang sudah selesai dan langkah \ + berikutnya di catatan tugas, beri tahu pengguna persentase ini dan kapan batas direset, lalu \ + berhenti.", +}; + +pub const TURKISH: Labels = Labels { + code: "tr", + session: "oturum", + week: "hafta", + compact: "sıkıştır", + context: "bağlam", + quota: "kota", + time: "süre", + resets_in: "sıfırlanmaya", + limit_near: "Kullanım sınırı yakın: uzun bir işe başlamadan önce kullanıcıya bu yüzdeleri bildir, görev \ + notlarını güncel tut (yapılanlar ve sonraki adımlar) ve alt ajan veya iş akışı başlatmadan önce \ + onay iste.", + limit_reached: "Kullanım sınırı neredeyse doldu: yeni görev başlatma. Yapılanları ve sonraki adımları görev \ + notlarına yaz, kullanıcıya bu yüzdeleri ve sınırın ne zaman sıfırlanacağını bildir ve dur.", +}; + +pub const VIETNAMESE: Labels = Labels { + code: "vi", + session: "phiên", + week: "tuần", + compact: "nén", + context: "ngữ cảnh", + quota: "hạn mức", + time: "thời gian", + resets_in: "đặt lại sau", + limit_near: "Sắp chạm giới hạn sử dụng: trước khi làm việc dài, hãy báo cho người dùng các phần trăm này, cập \ + nhật ghi chú công việc (đã xong và bước tiếp theo) và hỏi xác nhận trước khi chạy subagent hoặc \ + workflow.", + limit_reached: "Giới hạn sử dụng gần cạn: không bắt đầu công việc mới. Ghi lại phần đã xong và các bước tiếp \ + theo vào ghi chú công việc, báo cho người dùng các phần trăm này và thời điểm giới hạn được đặt \ + lại, rồi dừng.", +}; diff --git a/src/i18n/mod.rs b/src/i18n/mod.rs new file mode 100644 index 0000000..69b3175 --- /dev/null +++ b/src/i18n/mod.rs @@ -0,0 +1,122 @@ +mod latin; +mod scripts; + +use std::env; +use std::sync::OnceLock; + +use latin::*; +use scripts::*; + +pub struct Labels { + pub code: &'static str, + pub session: &'static str, + pub week: &'static str, + pub compact: &'static str, + pub context: &'static str, + pub quota: &'static str, + pub time: &'static str, + pub resets_in: &'static str, + pub limit_near: &'static str, + pub limit_reached: &'static str, +} + +pub const ALL: [&Labels; 20] = [ + &ENGLISH, + &PORTUGUESE, + &SPANISH, + &CHINESE, + &HINDI, + &ARABIC, + &FRENCH, + &GERMAN, + &JAPANESE, + &RUSSIAN, + &KOREAN, + &ITALIAN, + &INDONESIAN, + &TURKISH, + &VIETNAMESE, + &THAI, + &BENGALI, + &URDU, + &POLISH, + &DUTCH, +]; + +pub fn labels() -> &'static Labels { + if cfg!(test) { + return &PORTUGUESE; + } + static LABELS: OnceLock<&'static Labels> = OnceLock::new(); + LABELS.get_or_init(|| { + let requested = ["STATUS_CLI_LANG", "LC_ALL", "LC_MESSAGES", "LANG"] + .into_iter() + .filter_map(|name| env::var(name).ok()) + .find(|value| !value.is_empty() && value != "C" && value != "POSIX"); + for_locale(&requested.or_else(system_locale).unwrap_or_default()) + }) +} + +fn for_locale(locale: &str) -> &'static Labels { + let language = match locale.get(..2).map(str::to_ascii_lowercase).as_deref() { + Some("in") => "id".to_owned(), + Some(other) => other.to_owned(), + None => return &ENGLISH, + }; + ALL.into_iter().find(|labels| labels.code.get(..2) == Some(language.as_str())).unwrap_or(&ENGLISH) +} + +#[cfg(windows)] +fn system_locale() -> Option { + use windows_sys::Win32::Globalization::GetUserDefaultLocaleName; + + let mut buffer = [0u16; 85]; + let len = unsafe { GetUserDefaultLocaleName(buffer.as_mut_ptr(), buffer.len() as i32) }; + (len > 1).then(|| String::from_utf16_lossy(&buffer[..len as usize - 1])) +} + +#[cfg(not(windows))] +fn system_locale() -> Option { + None +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn locales_map_to_their_language() { + assert_eq!(for_locale("pt_BR.UTF-8").session, "sessão"); + assert_eq!(for_locale("es-ES").session, "sesión"); + assert_eq!(for_locale("fr_FR").week, "semaine"); + assert_eq!(for_locale("zh_CN.UTF-8").session, "会话"); + assert_eq!(for_locale("de-DE").session, "Sitzung"); + assert_eq!(for_locale("ja_JP.UTF-8").code, "ja"); + assert_eq!(for_locale("hi-IN").code, "hi"); + assert_eq!(for_locale("ar_SA").code, "ar"); + assert_eq!(for_locale("in_ID").code, "id"); + assert_eq!(for_locale("nl-BE").code, "nl"); + assert_eq!(for_locale("en_US").session, "session"); + assert_eq!(for_locale("sv_SE").session, "session"); + assert_eq!(for_locale("").session, "session"); + } + + #[test] + fn codes_are_unique_and_every_text_is_filled() { + for (i, labels) in ALL.iter().enumerate() { + assert!(ALL[..i].iter().all(|other| other.code.get(..2) != labels.code.get(..2)), "{}", labels.code); + let texts = [ + labels.session, + labels.week, + labels.compact, + labels.context, + labels.quota, + labels.time, + labels.resets_in, + labels.limit_near, + labels.limit_reached, + ]; + assert!(texts.iter().all(|text| !text.trim().is_empty() && !text.contains(" ")), "{}", labels.code); + } + } +} diff --git a/src/i18n/scripts.rs b/src/i18n/scripts.rs new file mode 100644 index 0000000..8574a76 --- /dev/null +++ b/src/i18n/scripts.rs @@ -0,0 +1,137 @@ +use super::Labels; + +pub const CHINESE: Labels = Labels { + code: "zh-CN", + session: "会话", + week: "本周", + compact: "压缩", + context: "上下文", + quota: "配额", + time: "时长", + resets_in: "距重置", + limit_near: "用量接近上限:开始耗时工作前,先告知用户这些百分比,保持任务记录最新(已完成和后续步骤),\ + 启动子代理或工作流前先确认。", + limit_reached: "用量即将耗尽:不要开始新任务。在任务记录中写下已完成内容和后续步骤,\ + 告知用户这些百分比及额度重置时间,然后停止。", +}; + +pub const JAPANESE: Labels = Labels { + code: "ja", + session: "セッション", + week: "今週", + compact: "圧縮", + context: "コンテキスト", + quota: "割り当て", + time: "時間", + resets_in: "リセットまで", + limit_near: "使用量の上限が近い:長い作業を始める前にユーザーにこの割合を伝え、\ + タスクのメモ(完了内容と次の手順)を最新に保ち、サブエージェントやワークフローを始める前に確認すること。", + limit_reached: "使用量の上限にほぼ達した:新しいタスクを始めないこと。完了内容と次の手順をタスクのメモに記録し、\ + ユーザーにこの割合と上限のリセット時刻を伝えて、停止すること。", +}; + +pub const KOREAN: Labels = Labels { + code: "ko", + session: "세션", + week: "주간", + compact: "압축", + context: "컨텍스트", + quota: "할당량", + time: "시간", + resets_in: "초기화까지", + limit_near: "사용 한도에 가까움: 긴 작업을 시작하기 전에 사용자에게 이 비율을 알리고, 작업 메모(완료 내용과 다음 \ + 단계)를 최신으로 유지하며, 하위 에이전트나 워크플로를 시작하기 전에 확인을 받으세요.", + limit_reached: "사용 한도가 거의 소진됨: 새 작업을 시작하지 마세요. 완료한 내용과 다음 단계를 작업 메모에 \ + 기록하고, 사용자에게 이 비율과 한도 초기화 시점을 알린 뒤 멈추세요.", +}; + +pub const RUSSIAN: Labels = Labels { + code: "ru", + session: "сессия", + week: "неделя", + compact: "сжатие", + context: "контекст", + quota: "квота", + time: "время", + resets_in: "сброс через", + limit_near: "Лимит использования близок: перед долгой работой сообщи пользователю эти проценты, держи заметки \ + задачи актуальными (сделано и следующие шаги) и спрашивай подтверждение перед запуском субагентов \ + или workflow.", + limit_reached: "Лимит использования почти исчерпан: не начинай новые задачи. Запиши сделанное и следующие шаги в \ + заметки задачи, сообщи пользователю эти проценты и когда лимит сбросится, и остановись.", +}; + +pub const HINDI: Labels = Labels { + code: "hi", + session: "सत्र", + week: "सप्ताह", + compact: "संक्षेपण", + context: "संदर्भ", + quota: "कोटा", + time: "समय", + resets_in: "रीसेट में", + limit_near: "उपयोग सीमा निकट है: लंबा काम शुरू करने से पहले उपयोगकर्ता को ये प्रतिशत बताएं, कार्य नोट्स \ + (पूरा हुआ काम और अगले कदम) अद्यतन रखें और सबएजेंट या वर्कफ़्लो शुरू करने से पहले पुष्टि लें।", + limit_reached: "उपयोग सीमा लगभग समाप्त: नया काम शुरू न करें। पूरा हुआ काम और अगले कदम कार्य नोट्स में दर्ज करें, \ + उपयोगकर्ता को ये प्रतिशत और सीमा रीसेट होने का समय बताएं, फिर रुकें।", +}; + +pub const BENGALI: Labels = Labels { + code: "bn", + session: "সেশন", + week: "সপ্তাহ", + compact: "সংকোচন", + context: "প্রসঙ্গ", + quota: "কোটা", + time: "সময়", + resets_in: "রিসেট বাকি", + limit_near: "ব্যবহারের সীমা কাছাকাছি: দীর্ঘ কাজ শুরু করার আগে ব্যবহারকারীকে এই শতাংশগুলো জানান, কাজের নোট \ + (সম্পন্ন কাজ ও পরবর্তী ধাপ) হালনাগাদ রাখুন এবং সাবএজেন্ট বা ওয়ার্কফ্লো শুরু করার আগে নিশ্চিত করুন।", + limit_reached: "ব্যবহারের সীমা প্রায় শেষ: নতুন কাজ শুরু করবেন না। সম্পন্ন কাজ ও পরবর্তী ধাপ কাজের নোটে লিখে রাখুন, \ + ব্যবহারকারীকে এই শতাংশগুলো ও সীমা রিসেটের সময় জানান, তারপর থামুন।", +}; + +pub const THAI: Labels = Labels { + code: "th", + session: "เซสชัน", + week: "สัปดาห์", + compact: "บีบอัด", + context: "บริบท", + quota: "โควตา", + time: "เวลา", + resets_in: "รีเซ็ตใน", + limit_near: "ใกล้ถึงขีดจำกัดการใช้งาน: ก่อนเริ่มงานที่ใช้เวลานาน ให้แจ้งเปอร์เซ็นต์เหล่านี้แก่ผู้ใช้ \ + อัปเดตบันทึกงาน (สิ่งที่ทำแล้วและขั้นตอนถัดไป) และขอยืนยันก่อนเริ่ม subagent หรือ workflow", + limit_reached: "ขีดจำกัดการใช้งานใกล้หมดแล้ว: อย่าเริ่มงานใหม่ บันทึกสิ่งที่ทำแล้วและขั้นตอนถัดไปในบันทึกงาน \ + แจ้งเปอร์เซ็นต์เหล่านี้และเวลาที่ขีดจำกัดจะรีเซ็ตแก่ผู้ใช้ แล้วหยุด", +}; + +pub const ARABIC: Labels = Labels { + code: "ar", + session: "الجلسة", + week: "الأسبوع", + compact: "الضغط", + context: "السياق", + quota: "الحصة", + time: "الوقت", + resets_in: "إعادة الضبط بعد", + limit_near: "حد الاستخدام قريب: قبل بدء عمل طويل، أخبر المستخدم بهذه النسب، وحدّث ملاحظات المهمة (ما أُنجز \ + والخطوات التالية)، واطلب التأكيد قبل تشغيل وكلاء فرعيين أو مسارات عمل.", + limit_reached: "حد الاستخدام يكاد ينفد: لا تبدأ مهام جديدة. سجّل ما أُنجز والخطوات التالية في ملاحظات المهمة، \ + وأخبر المستخدم بهذه النسب وبموعد إعادة ضبط الحد، ثم توقف.", +}; + +pub const URDU: Labels = Labels { + code: "ur", + session: "سیشن", + week: "ہفتہ", + compact: "کمپیکٹ", + context: "سیاق", + quota: "کوٹہ", + time: "وقت", + resets_in: "ری سیٹ میں", + limit_near: "استعمال کی حد قریب ہے: طویل کام شروع کرنے سے پہلے صارف کو یہ فیصد بتائیں، کام کے نوٹس (مکمل کام \ + اور اگلے مراحل) تازہ رکھیں، اور سب ایجنٹ یا ورک فلو شروع کرنے سے پہلے تصدیق لیں۔", + limit_reached: "استعمال کی حد تقریباً ختم: نیا کام شروع نہ کریں۔ مکمل کام اور اگلے مراحل کام کے نوٹس میں لکھیں، \ + صارف کو یہ فیصد اور حد کے ری سیٹ ہونے کا وقت بتائیں، پھر رک جائیں۔", +}; diff --git a/src/main.rs b/src/main.rs index 05a12b2..b5e04af 100644 --- a/src/main.rs +++ b/src/main.rs @@ -15,7 +15,7 @@ use std::thread; use std::time::{Duration, SystemTime, UNIX_EPOCH}; use features::telemetry::{self, Event, Timer}; -use features::{clock, codex, context, model, quota, setup, wrap}; +use features::{clock, codex, context, guard, model, quota, setup, wrap}; use layout::Line; use payload::Payload; use state::Session; @@ -37,7 +37,24 @@ fn main() { lines.iter().for_each(|line| println!("{line}")); std::process::exit(if healthy { 0 } else { 1 }); } + Some("update") => match features::update::run() { + Ok(message) => return println!("{message}"), + Err(err) => { + eprintln!("status_cli: {err}"); + std::process::exit(1); + } + }, Some("codex") => return run_codex(env::args().skip(2).collect()), + Some("guard") => { + let Some(host) = env::args().nth(2).as_deref().and_then(guard::host) else { + eprintln!("status_cli: usage: status_cli guard "); + std::process::exit(2); + }; + if let Some(reply) = guard::run(host, &cache_dir(), now_millis()) { + print!("{reply}"); + } + return; + } Some("--version" | "-V") => return println!("status_cli {}", env!("CARGO_PKG_VERSION")), _ => {} } diff --git a/src/state.rs b/src/state.rs index a485d1c..a1e477f 100644 --- a/src/state.rs +++ b/src/state.rs @@ -28,6 +28,8 @@ struct Trend { from: f64, to: f64, changed_at: u64, + #[serde(default, skip_serializing_if = "Option::is_none")] + resets_at: Option, } pub struct Motion { @@ -81,9 +83,14 @@ impl Session { pub fn track(&mut self, label: &str, pct: Option) -> Option { let pct = pct?; let now = self.now; - let trend = self.current.gauges.entry(label.to_owned()).or_insert(Trend { from: pct, to: pct, changed_at: 0 }); + let trend = self.current.gauges.entry(label.to_owned()).or_insert(Trend { + from: pct, + to: pct, + changed_at: 0, + resets_at: None, + }); if pct.round() != trend.to.round() { - *trend = Trend { from: trend.shown(now), to: pct, changed_at: now }; + *trend = Trend { from: trend.shown(now), to: pct, changed_at: now, ..*trend }; } else { let shift = pct - trend.to; trend.from += shift; @@ -93,6 +100,12 @@ impl Session { Some(Motion { shown, growing: trend.to > trend.from && shown < trend.to }) } + pub fn resets(&mut self, label: &str, at: Option) { + if let Some(trend) = self.current.gauges.get_mut(label) { + trend.resets_at = at; + } + } + pub fn advance(&mut self, now: u64) { self.now = now; } @@ -113,6 +126,17 @@ impl Session { } } +pub struct Reading { + pub pct: f64, + pub resets_at: Option, +} + +pub fn read(dir: &Path, key: &str, labels: &[&str]) -> Option { + let snapshot = load(&dir.join(format!("{FILE_PREFIX}{key}")))?; + let trend = labels.iter().find_map(|label| snapshot.gauges.get(*label))?; + Some(Reading { pct: trend.to, resets_at: trend.resets_at }) +} + fn write_atomic(file: &Path, bytes: &[u8]) -> io::Result<()> { let staging = file.with_extension(format!("tmp{}", std::process::id())); fs::write(&staging, bytes)?; @@ -196,4 +220,17 @@ mod tests { s.now = 10_000; assert_eq!(s.track("x", Some(79.4)).map(|m| m.shown), Some(79.4)); } + + #[test] + fn reset_survives_value_changes_and_is_saved() { + let mut s = Session::detached(0); + s.resets("x", Some(9_000)); + assert!(s.current.gauges.is_empty()); + s.track("x", Some(10.0)); + s.resets("x", Some(9_000)); + s.track("x", Some(40.0)); + assert_eq!(s.current.gauges["x"].resets_at, Some(9_000)); + let json = serde_json::to_string(&s.current).unwrap(); + assert!(json.contains(r#""resets_at":9000"#)); + } } diff --git a/src/style.rs b/src/style.rs index cb83fa7..25a34ca 100644 --- a/src/style.rs +++ b/src/style.rs @@ -205,6 +205,31 @@ pub fn strip(s: &str) -> String { pub fn char_width(c: char) -> usize { match c as u32 { + 0x0300..=0x036F + | 0x0610..=0x061A + | 0x064B..=0x065F + | 0x0670 + | 0x06D6..=0x06DC + | 0x06DF..=0x06E4 + | 0x06E7..=0x06E8 + | 0x06EA..=0x06ED + | 0x0900..=0x0902 + | 0x093A + | 0x093C + | 0x0941..=0x0948 + | 0x094D + | 0x0951..=0x0957 + | 0x0962..=0x0963 + | 0x0981 + | 0x09BC + | 0x09C1..=0x09C4 + | 0x09CD + | 0x09E2..=0x09E3 + | 0x0E31 + | 0x0E34..=0x0E3A + | 0x0E47..=0x0E4E + | 0x200B..=0x200F + | 0xFE00..=0xFE0F => 0, 0x1100..=0x115F | 0x2E80..=0x303E | 0x3041..=0x33FF diff --git a/src/time.rs b/src/time.rs index 248991d..cb08900 100644 --- a/src/time.rs +++ b/src/time.rs @@ -2,16 +2,35 @@ pub fn parse_utc_millis(timestamp: &str) -> Option { let field = |range: std::ops::Range| timestamp.get(range)?.parse::().ok(); let (year, month, day) = (field(0..4)?, field(5..7)?, field(8..10)?); let (hour, minute, second) = (field(11..13)?, field(14..16)?, field(17..19)?); + let offset = utc_offset_seconds(timestamp.get(19..)?)?; let year = if month <= 2 { year - 1 } else { year }; let era = year.div_euclid(400); let year_of_era = year - era * 400; let day_of_year = (153 * ((month + 9) % 12) + 2) / 5 + day - 1; let day_of_era = year_of_era * 365 + year_of_era / 4 - year_of_era / 100 + day_of_year; let days = era * 146_097 + day_of_era - 719_468; - let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second; + let seconds = days * 86_400 + hour * 3_600 + minute * 60 + second - offset; u64::try_from(seconds).ok().map(|s| s * 1000) } +fn utc_offset_seconds(suffix: &str) -> Option { + let zone = match suffix.strip_prefix('.') { + Some(fraction) => fraction.trim_start_matches(|c: char| c.is_ascii_digit()), + None => suffix, + }; + if matches!(zone, "" | "Z" | "z") { + return Some(0); + } + let sign = match zone.as_bytes().first()? { + b'+' => 1, + b'-' => -1, + _ => return None, + }; + let (hours, minutes) = zone.get(1..)?.split_once(':')?; + let (hours, minutes) = (hours.parse::().ok()?, minutes.parse::().ok()?); + (hours < 24 && minutes < 60).then_some(sign * (hours * 3_600 + minutes * 60)) +} + #[cfg(test)] mod tests { use super::*; @@ -23,4 +42,12 @@ mod tests { assert_eq!(parse_utc_millis("2026-10-08T05:52:12Z"), Some(1_791_438_732_000)); assert_eq!(parse_utc_millis("garbage"), None); } + + #[test] + fn applies_rfc3339_offsets() { + assert_eq!(parse_utc_millis("2026-10-08T02:52:12-03:00"), Some(1_791_438_732_000)); + assert_eq!(parse_utc_millis("2026-10-08T07:22:12.5+01:30"), Some(1_791_438_732_000)); + assert_eq!(parse_utc_millis("2026-10-08T05:52:12+00:00"), Some(1_791_438_732_000)); + assert_eq!(parse_utc_millis("2026-10-08T05:52:12 PST"), None); + } } diff --git a/tests/guard.rs b/tests/guard.rs new file mode 100644 index 0000000..cb4c9ba --- /dev/null +++ b/tests/guard.rs @@ -0,0 +1,114 @@ +mod common; + +use common::*; +use serde_json::Value; +use std::fs; +use std::io::Write; +use std::process::{Command, Stdio}; + +fn guard(temp: &TempDir, host: &str, input: &str) -> String { + let mut child = Command::new(env!("CARGO_BIN_EXE_status_cli")) + .args(["guard", host]) + .env("XDG_RUNTIME_DIR", &temp.0) + .env("STATUS_CLI_LANG", "en") + .env("HOME", &temp.0) + .env("USERPROFILE", &temp.0) + .env_remove("CODEX_HOME") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .unwrap(); + let _ = child.stdin.take().unwrap().write_all(input.as_bytes()); + let out = child.wait_with_output().unwrap(); + assert!(out.status.success()); + String::from_utf8(out.stdout).unwrap() +} + +fn render(temp: &TempDir, session: &str, session_pct: u32) { + let now = now_secs(); + run_raw( + temp, + &format!( + r#"{{"session_id":"{session}","rate_limits":{{"five_hour":{{"used_percentage":{session_pct},"resets_at":{}}}, + "seven_day":{{"used_percentage":31,"resets_at":{}}}}}}}"#, + now + 1800, + now + 300_000 + ), + &[], + ); +} + +#[test] +fn claude_prompt_gets_usage_and_time_to_reset_from_the_status_line_state() { + let temp = TempDir::new(); + render(&temp, "s1", 40); + let out: Value = + serde_json::from_str(&guard(&temp, "claude", r#"{"session_id":"s1","hook_event_name":"UserPromptSubmit"}"#)) + .unwrap(); + let context = out["hookSpecificOutput"]["additionalContext"].as_str().unwrap(); + assert!(context.starts_with("status_cli: session 40% (resets in 29m"), "{context}"); + assert!(context.contains("week 31% (resets in 3d"), "{context}"); +} + +#[test] +fn near_exhaustion_tells_the_agent_to_stop_and_blocks_subagents() { + let temp = TempDir::new(); + render(&temp, "s2", 96); + let prompt: Value = + serde_json::from_str(&guard(&temp, "claude", r#"{"session_id":"s2","hook_event_name":"UserPromptSubmit"}"#)) + .unwrap(); + assert!(prompt["hookSpecificOutput"]["additionalContext"].as_str().unwrap().contains("do not start new tasks")); + let tool: Value = serde_json::from_str(&guard( + &temp, + "claude", + r#"{"session_id":"s2","hook_event_name":"PreToolUse","tool_name":"Agent"}"#, + )) + .unwrap(); + assert_eq!(tool["hookSpecificOutput"]["permissionDecision"], "deny"); +} + +#[test] +fn unknown_sessions_and_bad_input_stay_silent() { + let temp = TempDir::new(); + assert_eq!(guard(&temp, "claude", r#"{"session_id":"none","hook_event_name":"UserPromptSubmit"}"#), ""); + assert_eq!(guard(&temp, "claude", "not json"), ""); + assert_eq!(guard(&temp, "agy", "not json"), "{}"); +} + +#[test] +fn setup_registers_the_guard_in_every_host_and_keeps_other_hooks() { + let temp = TempDir::new(); + let claude = temp.0.join(".claude"); + let codex = temp.0.join(".codex"); + fs::create_dir_all(&claude).unwrap(); + fs::create_dir_all(&codex).unwrap(); + fs::create_dir_all(temp.0.join(".gemini").join("antigravity-cli")).unwrap(); + fs::write( + codex.join("hooks.json"), + r#"{"hooks":{"PreToolUse":[{"matcher":"Bash","hooks":[{"type":"command","command":"rtk"}]}]}}"#, + ) + .unwrap(); + let out = Command::new(env!("CARGO_BIN_EXE_status_cli")) + .arg("setup") + .env("HOME", &temp.0) + .env("USERPROFILE", &temp.0) + .env_remove("CLAUDE_CONFIG_DIR") + .env_remove("CODEX_HOME") + .output() + .unwrap(); + let stdout = String::from_utf8(out.stdout).unwrap(); + assert!(out.status.success(), "{stdout}"); + assert!(stdout.contains("/hooks in Codex"), "{stdout}"); + let read = + |path: std::path::PathBuf| -> Value { serde_json::from_str(&fs::read_to_string(path).unwrap()).unwrap() }; + let settings = read(claude.join("settings.json")); + let command = settings["hooks"]["UserPromptSubmit"][0]["hooks"][0]["command"].as_str().unwrap(); + assert!(command.ends_with("guard claude"), "{command}"); + assert_eq!(settings["hooks"]["PreToolUse"][0]["matcher"], "Agent|Task|Workflow"); + let codex_hooks = read(codex.join("hooks.json")); + assert_eq!(codex_hooks["hooks"]["PreToolUse"][0]["hooks"][0]["command"], "rtk"); + assert!(codex_hooks["hooks"]["SessionStart"][0]["hooks"][0]["command"].as_str().unwrap().ends_with("guard codex")); + let plugin = temp.0.join(".gemini").join("config").join("plugins").join("status_cli"); + assert_eq!(read(plugin.join("plugin.json"))["name"], "status_cli"); + assert!(read(plugin.join("hooks.json"))["status_cli-guard"]["PreInvocation"].is_array()); +} diff --git a/tests/i18n.rs b/tests/i18n.rs index 562c487..1781c4f 100644 --- a/tests/i18n.rs +++ b/tests/i18n.rs @@ -2,25 +2,51 @@ mod common; use common::*; +const LANGUAGES: [(&str, &str, &str, &str); 20] = [ + ("en", "session", "compact", "time"), + ("pt_BR.UTF-8", "sessão", "compactar", "tempo"), + ("es", "sesión", "compactar", "tiempo"), + ("zh_CN", "会话", "压缩", "时长"), + ("hi_IN", "सत्र", "संक्षेपण", "समय"), + ("ar_SA", "الجلسة", "الضغط", "الوقت"), + ("fr", "session", "compacter", "temps"), + ("de_DE", "Sitzung", "verdichten", "Zeit"), + ("ja_JP", "セッション", "圧縮", "時間"), + ("ru_RU", "сессия", "сжатие", "время"), + ("ko_KR", "세션", "압축", "시간"), + ("it_IT", "sessione", "compattare", "tempo"), + ("id_ID", "sesi", "ringkas", "waktu"), + ("tr_TR", "oturum", "sıkıştır", "süre"), + ("vi_VN", "phiên", "nén", "thời gian"), + ("th_TH", "เซสชัน", "บีบอัด", "เวลา"), + ("bn_BD", "সেশন", "সংকোচন", "সময়"), + ("ur_PK", "سیشن", "کمپیکٹ", "وقت"), + ("pl_PL", "sesja", "kompaktowanie", "czas"), + ("nl_NL", "sessie", "compacteren", "tijd"), +]; + +fn columns(text: &str) -> usize { + text.chars() + .map(|c| match c as u32 { + 0x0900..=0x0902 | 0x093C | 0x0941..=0x0948 | 0x094D | 0x09BC | 0x09C1..=0x09C4 | 0x09CD => 0, + 0x0E31 | 0x0E34..=0x0E3A | 0x0E47..=0x0E4E => 0, + 0x1100..=0x115F | 0x3041..=0x33FF | 0x4E00..=0x9FFF | 0xAC00..=0xD7A3 | 0xFF00..=0xFF60 => 2, + _ => 1, + }) + .sum() +} + #[test] fn every_language_labels_the_line_and_keeps_the_width() { let temp = TempDir::new(); let payload = r#"{"session_id":"lang","model":{"display_name":"Opus 5.5"}, "rate_limits":{"five_hour":{"used_percentage":40}},"context_window":{"used_percentage":20,"context_window_size":200000}, "cost":{"total_duration_ms":60000}}"#; - for (lang, session, compact, time) in [ - ("en", "session", "compact", "time"), - ("es", "sesión", "compactar", "tiempo"), - ("pt_BR.UTF-8", "sessão", "compactar", "tempo"), - ("fr", "session", "compacter", "temps"), - ("zh_CN", "会话", "压缩", "时长"), - ] { + for (lang, session, compact, time) in LANGUAGES { let out = run_with(&temp, payload, Some(120), &[("STATUS_CLI_LANG", lang)]); for label in [session, compact, time] { assert!(out.text.contains(label), "{lang}: {:?}", out.text); } - let columns: usize = - out.visible.chars().map(|c| if ('\u{4e00}'..='\u{9fff}').contains(&c) { 2 } else { 1 }).sum(); - assert_eq!(columns, 112, "{lang}: {:?}", out.visible); + assert_eq!(columns(&out.visible), 112, "{lang}: {:?}", out.visible); } } diff --git a/tests/update.rs b/tests/update.rs new file mode 100644 index 0000000..4ef56a4 --- /dev/null +++ b/tests/update.rs @@ -0,0 +1,86 @@ +mod common; + +use common::*; +use sha2::{Digest, Sha256}; +use std::fs; +use std::path::{Path, PathBuf}; +use std::process::{Command, Output}; + +const MARKER: &[u8] = b"\0status_cli-update-test"; + +fn asset() -> &'static str { + match (std::env::consts::OS, std::env::consts::ARCH) { + ("windows", "aarch64") => "status_cli-aarch64-pc-windows-msvc.exe", + ("windows", _) => "status_cli-x86_64-pc-windows-msvc.exe", + ("linux", "aarch64") => "status_cli-aarch64-unknown-linux-musl", + ("linux", _) => "status_cli-x86_64-unknown-linux-musl", + _ => "status_cli-universal-apple-darwin", + } +} + +fn url(path: &Path) -> String { + let path = path.to_string_lossy().replace('\\', "/"); + if path.starts_with('/') { format!("file://{path}") } else { format!("file:///{path}") } +} + +fn publish(temp: &TempDir, tag: &str, corrupt: bool) -> PathBuf { + let release = temp.0.join("release"); + fs::create_dir_all(&release).unwrap(); + let mut binary = fs::read(env!("CARGO_BIN_EXE_status_cli")).unwrap(); + binary.extend_from_slice(MARKER); + let digest: String = Sha256::digest(&binary).iter().map(|b| format!("{b:02x}")).collect(); + let digest = if corrupt { "0".repeat(64) } else { digest }; + fs::write(release.join(asset()), &binary).unwrap(); + fs::write(release.join("SHA256SUMS"), format!("{digest} {}\n", asset())).unwrap(); + fs::write(release.join("latest.json"), format!(r#"{{"tag_name":"{tag}","name":"status_cli {tag}"}}"#)).unwrap(); + release +} + +fn installed(temp: &TempDir) -> PathBuf { + let bin = temp.0.join("bin"); + fs::create_dir_all(&bin).unwrap(); + let target = bin.join(if cfg!(windows) { "status_cli.exe" } else { "status_cli" }); + fs::copy(env!("CARGO_BIN_EXE_status_cli"), &target).unwrap(); + target +} + +fn update(target: &Path, release: &Path) -> Output { + Command::new(target) + .arg("update") + .env("STATUS_CLI_RELEASE_URL", url(&release.join("latest.json"))) + .env("STATUS_CLI_BASE_URL", url(release)) + .output() + .unwrap() +} + +#[test] +fn update_installs_a_newer_verified_release_in_place() { + let temp = TempDir::new(); + let (release, target) = (publish(&temp, "v99.0.0", false), installed(&temp)); + let out = update(&target, &release); + let stdout = String::from_utf8_lossy(&out.stdout); + assert!(out.status.success(), "{stdout}{}", String::from_utf8_lossy(&out.stderr)); + assert!(stdout.contains(&format!("{} -> 99.0.0", env!("CARGO_PKG_VERSION"))), "{stdout}"); + assert!(fs::read(&target).unwrap().ends_with(MARKER)); + assert!(!target.with_extension("new").exists()); +} + +#[test] +fn update_keeps_the_binary_when_already_current() { + let temp = TempDir::new(); + let (release, target) = (publish(&temp, "v0.0.1", false), installed(&temp)); + let out = update(&target, &release); + assert!(out.status.success()); + assert!(String::from_utf8_lossy(&out.stdout).contains("is up to date")); + assert!(!fs::read(&target).unwrap().ends_with(MARKER)); +} + +#[test] +fn update_refuses_a_checksum_mismatch() { + let temp = TempDir::new(); + let (release, target) = (publish(&temp, "v99.0.0", true), installed(&temp)); + let out = update(&target, &release); + assert_eq!(out.status.code(), Some(1)); + assert!(String::from_utf8_lossy(&out.stderr).contains("checksum mismatch")); + assert!(!fs::read(&target).unwrap().ends_with(MARKER)); +}