From 67c4f4d86ef044c5d4492c4a491b0fa64a8c3af5 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 00:27:33 -0500 Subject: [PATCH 01/11] feat(usage): show an account's last known reading when it cannot be read A row that is expired, no_scope, no_login or error kept only a status and a hint. When the usage cache still holds an earlier reading of that account, at most seven days old, ak usage now lists its windows under the status line, dated, and --json carries it as the additive last_known block. A window whose reset time has passed is marked reset and carries no number. The row is still a problem row; ak pick and ak capacity never read a reading that old. Co-Authored-By: Claude Fable 5.2 --- CHANGELOG.md | 15 +++ docs/SECURITY.md | 6 ++ docs/schema/usage-v1.json | 92 +++++++++++++++++ docs/usage.md | 44 +++++++- lib/state.py | 34 +++++-- lib/usage.py | 53 ++++++++++ skills/agentkit/references/usage.md | 8 ++ tests/py/usage_checks.py | 151 ++++++++++++++++++++++++++++ 8 files changed, 396 insertions(+), 7 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c6d4b6..7c33230 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,21 @@ permission posture changes. ## [Unreleased] +### Added + +- **`ak usage` keeps showing an account it cannot read now.** A row that is + `expired`, `no_scope`, `no_login` or `error` used to be a status and a hint + with nothing else. When the kit's usage cache still holds an earlier + reading of that account, at most seven days old, the table now lists that + reading's windows under the status line, dimmed and dated (`last read 3h 0m + ago`), and `ak usage --json` carries it as the additive `last_known` block + (`read_at`, `age_s`, `plan`, `windows`, each window with `reset`). A window + whose reset time has passed is marked reset and carries no number. The row + is still a problem row: its status, its empty `windows` and the exit code + are unchanged, and `ak pick` and `ak capacity` never choose an account or + report room from it. Showing it makes no request and writes nothing. + Interface stays **1**; `usage-v1` gains one optional key. + ## [1.5.2] - 2026-11-19 A patch release with no runtime change: `ak` behaves exactly as in 1.5.1, and diff --git a/docs/SECURITY.md b/docs/SECURITY.md index f61c227..d75d2f0 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -147,6 +147,12 @@ profile and its headroom, nothing else. (no read-modify-write, safe under concurrent runs), pruned past the newest 5000 per account. Read only by `ak usage` for its `advisory` block, which never reaches the usage cache, `ak capacity` or `ak pick`. +- **Last known reading:** for a row it cannot read now (`expired`, + `no_scope`, `no_login`, `error`), `ak usage` shows the reading already in + the usage cache when it is at most seven days old (`last_known`). It is + read from the kit's own file: no request, no login touched, nothing + written, and it holds usage numbers only. `ak capacity` and `ak pick` + never read a reading that old, so no account is chosen on it. - **Accounts:** work moves only among the accounts you declared for the work, within each vendor's terms; no agent creates an account, renews a login or spends a Codex reset. diff --git a/docs/schema/usage-v1.json b/docs/schema/usage-v1.json index d264f1b..988b584 100644 --- a/docs/schema/usage-v1.json +++ b/docs/schema/usage-v1.json @@ -260,6 +260,98 @@ } } } + }, + "last_known": { + "description": "Optional (additive): the account's last stored reading, present only on a row whose status is expired, no_scope, no_login or error and only when the kit's usage cache holds an earlier reading with windows that is at most seven days old. For display: the row is still a problem row (status, the empty windows and the exit code are unchanged), and neither ak pick nor ak capacity reads it. Absence means no reading is on record, not zero usage.", + "type": "object", + "required": [ + "read_at", + "age_s", + "plan", + "windows" + ], + "additionalProperties": false, + "properties": { + "read_at": { + "type": "string", + "description": "When that reading was taken (ISO-8601 UTC)." + }, + "age_s": { + "type": "integer", + "minimum": 0, + "description": "Its age in seconds when ak usage ran." + }, + "plan": { + "type": [ + "string", + "null" + ], + "description": "The plan that reading reported." + }, + "windows": { + "type": "array", + "description": "The windows as read then, each with `reset`.", + "items": { + "type": "object", + "additionalProperties": false, + "required": [ + "id", + "label", + "used_pct", + "resets_at", + "window_seconds", + "reset" + ], + "properties": { + "id": { + "type": "string", + "description": "Stable machine id: 5h, 7d, 7d-opus, tokens, mcp, ..." + }, + "label": { + "type": "string" + }, + "used_pct": { + "type": [ + "number", + "null" + ], + "description": "0..100, null when unknown." + }, + "resets_at": { + "type": [ + "string", + "null" + ], + "description": "ISO-8601 UTC, null when unknown." + }, + "window_seconds": { + "type": [ + "integer", + "null" + ] + }, + "used": { + "type": "number", + "minimum": 0, + "description": "Optional (additive): the absolute amount used, when the source reports it (Z.AI credits)." + }, + "limit": { + "type": "number", + "minimum": 0, + "description": "Optional (additive): the window's absolute limit, in the same unit as used." + }, + "unit": { + "type": "string", + "description": "Optional (additive): what used and limit count (credits, tokens)." + }, + "reset": { + "type": "boolean", + "description": "true when this window's reset time had passed when ak usage ran: the window read back then is over, so used_pct is null and used is absent." + } + } + } + } + } } } } diff --git a/docs/usage.md b/docs/usage.md index a156409..4c87613 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -207,6 +207,28 @@ not delay or hide the others. | 3 | nothing to report for that filter | | ≥ 64 | kit internal error | +### The last known reading + +An account that cannot be read now does not go blank. When a row is +`expired`, `no_scope`, `no_login` or `error` and the [usage cache](#the-usage-cache) +still holds an earlier reading of that account, at most seven days old, the +table lists that reading's windows under the status line, dimmed and dated: + +```text +claude · Claude Code + @work - expired open ak claude @work once to renew + 5-hour reset since last read 3h 0m ago + 7-day all models █▍░░░░░░░░ 14% last read 3h 0m ago +``` + +A window whose reset time has passed prints `reset since` and no percentage: +what was read belongs to a window that is over. `--json` carries the same +thing as `last_known` on that row (below). It is for reading, not for +deciding: the row is still a problem row, the exit code is still 1, and +`ak pick` and `ak capacity` never choose an account or report room from it. +Showing it makes no request and writes nothing. After seven days, or when no +reading was ever stored, the row is the status line alone. + ## For programs `ak usage --json` is a versioned, **additive** surface: `"schema": "usage-v1"` @@ -229,6 +251,23 @@ other row), and the table shows it as `@work3 (ak claude)`. For `AGENTKIT_DEFAULT_PROFILE_=pick` it is the portable-login account `ak pick` ranks first. See [Profiles](profiles.md#a-default-profile-per-cli). +A row whose status is `expired`, `no_scope`, `no_login` or `error` may carry +`last_known` (additive; absent when no reading of the last seven days is +stored — absence is unknown, not zero): + +```json +{"cli": "claude", "profile": "@work", "status": "expired", "windows": [], "plan": null, + "error": "the login has expired; open this profile once to renew it", + "last_known": {"read_at": "2026-10-10T09:00:00Z", "age_s": 10800, "plan": "max", "windows": [ + {"id": "5h", "label": "5-hour", "used_pct": null, "resets_at": "2026-10-10T11:14:00Z", "window_seconds": 18000, "reset": true}, + {"id": "7d", "label": "7-day all models", "used_pct": 13.5, "resets_at": "2026-10-11T10:00:00Z", "window_seconds": 604800, "reset": false}]}} +``` + +`read_at` and `age_s` date the reading; each window has the usual keys plus +`reset`, which is `true` when its reset time had passed (then `used_pct` is +`null` and `used` is absent). Never read `last_known` as the account's +current room. + ## Choosing an account ``` @@ -494,7 +533,10 @@ and resets, the plan name and the row status; never a token, key or path — in `0600` files, written atomically. `ak capacity` and `ak pick` reuse a reading younger than `--max-age` (300 s by default; `0` reads live) and write back what they read live. Only vendor readings (`ok`, `rate_limited`) are -kept; a login problem shows again at once. **`ak usage` is the only command +kept; a login problem shows again at once, and the reading stored before it +stays on disk — it is what `ak usage` shows as that row's +[last known reading](#the-last-known-reading) for up to seven days, and +nothing else reads a reading that old. **`ak usage` is the only command that always reads live**, so checking `ak capacity --self` at every task boundary costs at most one vendor request per account every five minutes. diff --git a/lib/state.py b/lib/state.py index fad8fd1..b269297 100644 --- a/lib/state.py +++ b/lib/state.py @@ -24,6 +24,7 @@ CACHE_SCHEMA = "usage-cache-v1" DEFAULT_MAX_AGE = 300 MAX_MAX_AGE = 86400 +LAST_KNOWN_MAX_AGE = 7 * 86400 # the longest window the kit reads; older says nothing current CACHE_NOTE = "the usage cache holds usage numbers only; ak usage is the only command that always reads live" # The usage-v1 row keys the cache keeps (window keys below). Anything else @@ -128,11 +129,9 @@ def cache_put(env, row, now): return True -def cache_get(env, cli, profile, now, max_age): - """(row, age_seconds) when a fresh entry exists for this account, else - (None, None). A corrupt, foreign or future-dated entry is a miss.""" - if max_age <= 0: - return None, None +def _cache_entry(env, cli, profile, now): + """(row, age_seconds) of the stored reading of this account, whatever its + age, else (None, None). A corrupt, foreign or future-dated entry is a miss.""" doc = read_json(_cache_path(env, cli, profile)) if not doc or doc.get("schema") != CACHE_SCHEMA: return None, None @@ -142,11 +141,34 @@ def cache_get(env, cli, profile, now, max_age): if row.get("cli") != cli or row.get("profile") != profile or not isinstance(row.get("windows"), list): return None, None age = int(now) - stamp - if age < 0 or age > max_age: + if age < 0: return None, None return _clean_row(row), age +def cache_get(env, cli, profile, now, max_age): + """(row, age_seconds) when a fresh entry exists for this account, else + (None, None). A corrupt, foreign or future-dated entry is a miss.""" + if max_age <= 0: + return None, None + row, age = _cache_entry(env, cli, profile, now) + if row is None or age > max_age: + return None, None + return row, age + + +def cache_last(env, cli, profile, now): + """(row, age_seconds) of this account's last stored reading when it is at + most LAST_KNOWN_MAX_AGE old, else (None, None). For display only + (`ak usage`'s `last_known`): a reading this old is never fresh, so + nothing that chooses an account or reports room reads it; cache_get is + the only reader those use.""" + row, age = _cache_entry(env, cli, profile, now) + if row is None or age > LAST_KNOWN_MAX_AGE: + return None, None + return row, age + + # ------------------------------------------------------- advisory tokens # One immutable sample file per observed run, written once under a unique # name and never rewritten: concurrent runs cannot lose each other's diff --git a/lib/usage.py b/lib/usage.py index 7775846..f2e8cc4 100644 --- a/lib/usage.py +++ b/lib/usage.py @@ -56,6 +56,8 @@ refreshed or written). The sources are vendor-internal and unofficial. The table fits the terminal: accounts without a readable quota are folded into one n/d line and long notes are shortened; -v lists every row with its full note. +An account that cannot be read now (expired, rejected, no login, error) keeps +showing its last stored reading, dated ("last read 3h ago"), for up to 7 days. """ @@ -1184,6 +1186,44 @@ def _bar(pct, utf8): return bar + "░" * (BAR_CELLS - len(bar)) +# A problem row keeps showing what was last read. Display only: the block is +# attached by `ak usage` after the live read, never cached, and neither +# ak pick nor ak capacity sees it (they read rows through fetch_cached). +LAST_KNOWN_STATUSES = ("expired", "no_scope", "no_login", "error") + + +def last_known(env, result, now): + """The account's last stored reading for a row that could not be read + now: {read_at, age_s, plan, windows} or None. A window whose reset time + has passed is marked `reset` and its numbers are dropped (they describe + a window that is over). No request, nothing written.""" + if result["status"] not in LAST_KNOWN_STATUSES: + return None + row, age = state.cache_last(env, result["cli"], result["profile"], now) + if row is None or not row["windows"]: + return None + windows = [] + for win in row["windows"]: + win = dict(win) + over = bool(win.get("resets_at")) and epoch_of(win["resets_at"]) <= now + win["reset"] = over + if over: + win["used_pct"] = None + win.pop("used", None) + windows.append(win) + return {"read_at": iso_utc(int(now) - age), "age_s": age, "plan": row.get("plan"), "windows": windows} + + +def _ago(seconds): + days, rem = divmod(int(seconds), 86400) + hours, rem = divmod(rem, 3600) + if days: + return "%dd %dh ago" % (days, hours) + if hours: + return "%dh %dm ago" % (hours, rem // 60) + return "%dm ago" % max(rem // 60, 1) + + STATUS_LABELS = {"expired": "expired", "no_login": "no login", "no_scope": "no access", "rate_limited": "rate limited", "error": "error"} NOTE_MIN = 16 # a note is never squeezed below this many characters @@ -1258,6 +1298,15 @@ def render_table(results, platform, color, now, verbose=False, names=None): else: label = STATUS_LABELS.get(r["status"], r["status"]) lines.append((base + [_paint(label, "31" if r["status"] == "error" else "33", color)], _note(r, verbose))) + known = r.get("last_known") + for w in (known["windows"] if known else ()): + # The last reading, dimmed and dated: never mistaken for now. + pct = w["used_pct"] + if w["reset"]: + used = "reset since" + else: + used = "-" if pct is None else "%s %3d%%" % (_bar(pct, utf8), round(pct)) + lines.append((["", "", w["label"], _paint(used, "2", color)], "last read " + _ago(known["age_s"]))) # Blocks whose quota can be read come first, the rest (every account # n/d or not logged in) after; each part keeps the kit order. Table only. groups.sort(key=lambda g: g[0] not in measurable) @@ -1401,6 +1450,10 @@ def main(model, args, env, now=None, stdout=None, platform=None): for result in results: # always live; refreshes what ak capacity / ak pick read state.cache_put(env, result, now) results = mark_defaults(model, results, env) + for result in results: # a row that could not be read keeps showing its last reading (display only) + known = last_known(env, result, now) + if known: + result["last_known"] = known for result in results: # advisory: sums of this account's observed run samples (absent when none) advisory = state.tokens_get(env, result["cli"], result["profile"]) if advisory: diff --git a/skills/agentkit/references/usage.md b/skills/agentkit/references/usage.md index a56bb9b..f9e03ac 100644 --- a/skills/agentkit/references/usage.md +++ b/skills/agentkit/references/usage.md @@ -118,6 +118,14 @@ secret. Exit: 0 every row `ok` or `unsupported`; 1 a row needs attention; 2 usage error; 3 nothing matches the filter. +A row that is `expired`, `no_scope`, `no_login` or `error` may carry +`last_known`: the account's last stored reading (`read_at`, `age_s`, `plan`, +`windows`, each window with `reset`), at most seven days old; the table +prints it under the status line as `last read 3h 0m ago`. Report it to the +user as what the account looked like then, with its age. Never treat it as +the account's room now: the row is still a problem row, and `ak pick` and +`ak capacity` ignore it. The action for the status above does not change. + ## Plan-specific windows - **Team without a global weekly cap** (Claude Code): only `5h` and diff --git a/tests/py/usage_checks.py b/tests/py/usage_checks.py index ffa0df4..2eec3d5 100644 --- a/tests/py/usage_checks.py +++ b/tests/py/usage_checks.py @@ -680,6 +680,157 @@ def write(self, text): shutil.rmtree(os.path.join(PROFILES, "antigravity")) server.set_routes({"/claude": {"json": WINDOWS_OK}, "/codex": {"json": WINDOWS_OK}, "/zai": {"json": ZAI_OK}}) + +# ------------------------------------------------------ last known reading +# A row that cannot be read now keeps showing what was last read (display +# only): never on an ok row, never older than seven days, never a number for +# a window that is over, and never visible to ak pick or ak capacity. + +import capacity # noqa: E402 +import pick # noqa: E402 + +LATER = NOW + 3 * 3600 # the 5-hour window (reset at NOW + 8040) is over, the 7-day one is not +WORK_LOGIN = os.path.join(PROFILES, "claude", "work", ".credentials.json") +WORK_CACHE = os.path.join(CACHE_DIR, "claude@work.json") +SCHEMA_FILE = os.path.join(ROOT, "docs", "schema", "usage-v1.json") + + +def rows_at(args, now, env=None): + code, out, _ = run(["--json"] + args, env or ENV, now=now) + return code, json.loads(out)["rows"], out + + +def schema_valid(text): + path = os.path.join(TMP, "last-known.json") + write(path, text) + proc = subprocess.run([sys.executable, os.path.join(HERE, "schema_check.py"), SCHEMA_FILE, path], + stdout=subprocess.PIPE, stderr=subprocess.STDOUT) + return proc.stdout.decode().strip() + + +server.set_routes({"/claude": {"json": WINDOWS_OK}, "/codex": {"json": WINDOWS_OK}, "/zai": {"json": ZAI_OK}}) +login(WORK_LOGIN) +code, fresh, fresh_out = rows_at(["claude"], NOW) +check("usage last known: an ok row never carries last_known", + [r["profile"] for r in fresh if r["status"] == "ok"] == ["@default", "@work"] + and not any("last_known" in r for r in fresh if r["status"] == "ok"), str(fresh)) +cache_before = open(WORK_CACHE).read() + +login(WORK_LOGIN, exp=LATER - 10) +before = len(server.requests) +files_before = tree_state(TMP) +code, rows, out = rows_at(["claude", "@work"], LATER) +row = rows[0] +known = row.get("last_known") or {} +check("usage last known: an expired row carries its last reading, with when it was read and its age", + known.get("read_at") == usage.iso_utc(NOW) and known.get("age_s") == 3 * 3600 and known.get("plan") == "max" + and [w["id"] for w in known.get("windows", [])] == ["5h", "7d"], str(row)) +check("usage last known: the row is still a problem row (status, empty windows, error, exit 1)", + row["status"] == "expired" and row["windows"] == [] and row["error"] and code == 1, "%s %s" % (code, row)) +wins = known.get("windows") or [{}, {}] +check("usage last known: a window whose reset time has passed is reset, with no number", + wins[0].get("reset") is True and wins[0].get("used_pct") is None and "used" not in wins[0], str(wins[0])) +check("usage last known: a window still running keeps what was read", + wins[1].get("reset") is False and wins[1].get("used_pct") == 13.5 + and wins[1].get("resets_at") == usage.iso_utc(NOW + 90000), str(wins[1])) +check("usage last known: producing it makes no request", len(server.requests) == before, str(len(server.requests) - before)) +check("usage last known: ... and writes nothing, the usage cache included", + [s for s in tree_state(TMP) if s[0] != os.path.join(TMP, "last-known.json")] + == [s for s in files_before if s[0] != os.path.join(TMP, "last-known.json")]) +check("usage last known: the stored reading is untouched and never holds the block", + open(WORK_CACHE).read() == cache_before and "last_known" not in cache_before) +check("usage last known: the output validates against docs/schema/usage-v1.json", schema_valid(out) == "valid", + schema_valid(out)[:300]) +check("usage last known: no token or key value in the block", PLANTED_LOGIN not in out and PLANTED_PROVIDER not in out) + +os.rename(WORK_CACHE, WORK_CACHE + ".aside") +_c, bare, _o = rows_at(["claude", "@work"], LATER) +os.rename(WORK_CACHE + ".aside", WORK_CACHE) +check("usage last known: without a stored reading the row has no such key", + "last_known" not in bare[0] and bare[0]["status"] == "expired", str(bare[0])) +check("usage last known: the rest of the row is what it is without a stored reading", + {k: v for k, v in row.items() if k != "last_known"} == bare[0], "%s != %s" % (row, bare[0])) + +WEEK = usage.state.LAST_KNOWN_MAX_AGE +login(WORK_LOGIN, exp=NOW + 1) +_c, edge, _o = rows_at(["claude", "@work"], NOW + WEEK) +_c, past, _o = rows_at(["claude", "@work"], NOW + WEEK + 1) +check("usage last known: a reading exactly seven days old is still shown, one second older is not", + edge[0]["status"] == "expired" and "last_known" in edge[0] and "last_known" not in past[0], + "%s / %s" % (edge[0], past[0])) +check("usage last known: after seven days every window of it is over", all(w["reset"] for w in edge[0]["last_known"]["windows"])) + +login(WORK_LOGIN, exp=LATER - 10) +text = run(["claude", "@work"], ENV, now=LATER)[1] +lines = text.splitlines() +status_line = next((line for line in lines if "@work" in line), "") +check("usage last known: the table keeps the status and its hint on the account's line", + "expired" in status_line and "open ak claude @work once to renew" in status_line, text) +check("usage last known: ... and lists the last windows under it, dated", + any("7-day" in line and "14%" in line and "last read 3h 0m ago" in line for line in lines), text) +check("usage last known: a window that is over prints as reset, never as a percentage", + any("5-hour" in line and "reset since" in line and "%" not in line for line in lines), text) +check("usage last known: a problem row without a stored reading prints as before", + "last read" not in run(["claude", "@work"], ENV, now=NOW + WEEK + 1)[1]) +narrow = run(["claude", "@work"], ENV, now=LATER, platform=usage.Platform("linux", True, "utf-8", {"TERM": "xterm"}, 60))[1] +check("usage last known: the dated lines also fit a narrow terminal", + all(len(usage._visible(line)) <= 60 for line in narrow.splitlines()), narrow) + +# the other statuses that keep a last reading +login(WORK_LOGIN) +server.set_routes({"/claude": {"status": 500, "body": "boom"}}) +_c, errored, _o = rows_at(["claude", "@work"], LATER) +check("usage last known: an error row carries it", errored[0]["status"] == "error" and "last_known" in errored[0], str(errored[0])) +server.set_routes({"/claude": {"status": 401, "body": "no"}}) +_c, rejected, _o = rows_at(["claude", "@work"], LATER) +check("usage last known: a rejected login (no_scope) carries it", + rejected[0]["status"] == "no_scope" and "last_known" in rejected[0], str(rejected[0])) +os.remove(WORK_LOGIN) +_c, gone, _o = rows_at(["claude", "@work"], LATER) +check("usage last known: a profile whose login is gone (no_login) carries it", + gone[0]["status"] == "no_login" and "last_known" in gone[0], str(gone[0])) +login(WORK_LOGIN) + +# nobody decides on an old reading +login(WORK_LOGIN, exp=LATER - 10) + + +def quiet(fn): + out, saved = io.StringIO(), sys.stderr + sys.stderr = io.StringIO() + try: + try: + code = fn(out) + except AkError as exc: + code = exc.code + finally: + sys.stderr = saved + return code, out.getvalue() + + +code, out = quiet(lambda o: pick.main(MODEL, ["claude", "@work", "--json"], dict(ENV), now=LATER, stdout=o)) +picked = json.loads(out) if out.strip() else {} +check("usage last known: ak pick refuses an expired account whatever its last reading said", + code == pick.EXIT_NONE and picked.get("chosen") == [] and "last_known" not in out, "%s %s" % (code, out[:300])) +code, out = quiet(lambda o: capacity.main(MODEL, ["claude", "@work", "--json"], dict(ENV), now=LATER, stdout=o)) +cap = json.loads(out) if out.strip() else {} +check("usage last known: ak capacity reports no room from it (verdict unknown, no headroom)", + cap.get("status") == "expired" and cap.get("verdict") == "unknown" and cap.get("headroom_pct") is None + and "last_known" not in out, out[:300]) +check("usage last known: neither wrote the block into the usage cache", "last_known" not in open(WORK_CACHE).read()) + +# a stored reading without windows (a 429 replaced it) is nothing to show +login(WORK_LOGIN) +server.set_routes({"/claude": {"status": 429, "body": "slow down"}}) +rows_at(["claude", "@work"], LATER) +login(WORK_LOGIN, exp=LATER - 10) +_c, limited, _o = rows_at(["claude", "@work"], LATER + 60) +check("usage last known: a stored reading with no windows adds nothing", "last_known" not in limited[0], str(limited[0])) + +login(WORK_LOGIN) +server.set_routes({"/claude": {"json": WINDOWS_OK}, "/codex": {"json": WINDOWS_OK}, "/zai": {"json": ZAI_OK}}) +rows_at(["claude", "@work"], NOW) + server.stop() if FAILS: sys.exit(1) From e9beafddc637b1e2cd60cb43d2f6be20dfa6db43 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 00:34:23 -0500 Subject: [PATCH 02/11] fix(usage): never show a damaged stored reading The last known reading comes from a file on disk. A window with a reset time that is not a time, a percentage that is not a number or a missing key made ak usage fail instead of reporting the row. Such a reading is now not shown. Co-Authored-By: Claude Fable 5.2 --- lib/usage.py | 46 ++++++++++++++++++++++++++++++++++------ tests/py/usage_checks.py | 26 +++++++++++++++++++++++ 2 files changed, 65 insertions(+), 7 deletions(-) diff --git a/lib/usage.py b/lib/usage.py index f2e8cc4..c8d88c7 100644 --- a/lib/usage.py +++ b/lib/usage.py @@ -1204,14 +1204,46 @@ def last_known(env, result, now): return None windows = [] for win in row["windows"]: - win = dict(win) - over = bool(win.get("resets_at")) and epoch_of(win["resets_at"]) <= now - win["reset"] = over - if over: - win["used_pct"] = None - win.pop("used", None) + win = _stored_window(win, now) + if win is None: # a file on disk: one malformed window and nothing of it is shown + return None windows.append(win) - return {"read_at": iso_utc(int(now) - age), "age_s": age, "plan": row.get("plan"), "windows": windows} + plan = row.get("plan") + return {"read_at": iso_utc(int(now) - age), "age_s": age, "plan": plan if isinstance(plan, str) else None, + "windows": windows} + + +def _stored_window(win, now): + """A window read back from the cache file, checked before it is shown + (the file may be damaged or hand-edited), with `reset`; None when it is + not a usage-v1 window.""" + def number(value, optional=True): + return (value is None and optional) or (isinstance(value, (int, float)) and not isinstance(value, bool)) + + if not isinstance(win.get("id"), str) or not isinstance(win.get("label"), str): + return None + if set(("used_pct", "resets_at", "window_seconds")) - set(win) or not number(win["used_pct"]): + return None + seconds = win["window_seconds"] + if seconds is not None and (not isinstance(seconds, int) or isinstance(seconds, bool)): + return None + if any(key in win and not number(win[key], optional=False) for key in ("used", "limit")): + return None + if "unit" in win and not isinstance(win["unit"], str): + return None + over = False + if win["resets_at"] is not None: + try: + over = isinstance(win["resets_at"], str) and epoch_of(win["resets_at"]) <= now + except (ValueError, OverflowError): + return None + if not isinstance(win["resets_at"], str): + return None + win = dict(win, reset=over) + if over: + win["used_pct"] = None + win.pop("used", None) + return win def _ago(seconds): diff --git a/tests/py/usage_checks.py b/tests/py/usage_checks.py index 2eec3d5..56d8b25 100644 --- a/tests/py/usage_checks.py +++ b/tests/py/usage_checks.py @@ -827,9 +827,35 @@ def quiet(fn): _c, limited, _o = rows_at(["claude", "@work"], LATER + 60) check("usage last known: a stored reading with no windows adds nothing", "last_known" not in limited[0], str(limited[0])) +# the stored reading is a file on disk: a damaged one is never shown and never crashes the table login(WORK_LOGIN) server.set_routes({"/claude": {"json": WINDOWS_OK}, "/codex": {"json": WINDOWS_OK}, "/zai": {"json": ZAI_OK}}) rows_at(["claude", "@work"], NOW) +login(WORK_LOGIN, exp=LATER - 10) +good = json.loads(open(WORK_CACHE).read()) +for what, damage in (("a reset time that is not a time", {"resets_at": "soon"}), + ("a percentage that is not a number", {"used_pct": "many"}), + ("a label that is not text", {"label": 7}), + ("a window length that is not a whole number", {"window_seconds": "long"}), + ("a missing key", None)): + bad = copy.deepcopy(good) + if damage is None: + del bad["row"]["windows"][0]["label"] + else: + bad["row"]["windows"][0].update(damage) + write(WORK_CACHE, json.dumps(bad)) + code, damaged, out = rows_at(["claude", "@work"], LATER) + table = run(["claude", "@work"], ENV, now=LATER) + check("usage last known: a stored reading with %s is not shown, and nothing crashes" % what, + code == 1 and damaged[0]["status"] == "expired" and "last_known" not in damaged[0] + and table[0] == 1 and "last read" not in table[1] and schema_valid(out) == "valid", "%s %s" % (code, damaged)) +write(WORK_CACHE, json.dumps(dict(good, row=dict(good["row"], plan=7)))) +_c, odd, out = rows_at(["claude", "@work"], LATER) +check("usage last known: a stored plan that is not text is dropped, the windows are kept", + odd[0].get("last_known", {}).get("plan", 0) is None and schema_valid(out) == "valid", str(odd[0])) + +login(WORK_LOGIN) +rows_at(["claude", "@work"], NOW) server.stop() if FAILS: From 5f8b1efcfe8d83f0977eee19dc52982a1ee3f402 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 00:50:40 -0500 Subject: [PATCH 03/11] feat(sessions): record each interactive launch as a running session Every interactive ak [@profile] now leaves one record in the kit's state directory (sessions/, one 0600 file per launch): the process id and its start time, kind, CLI, provider, profile, working directory, launch time, posture and the Herdr pane id. Best effort: a failed write never changes a launch. A record is live only while its process id is alive with the recorded start time. Nothing reads the records yet; ak ps follows. Co-Authored-By: Claude Fable 5.2 --- docs/TESTING_GUIDE.md | 1 + lib/launch.py | 4 + lib/sessions.py | 179 ++++++++++++++++++++++++++++++++++++ tests/py/sessions_checks.py | 171 ++++++++++++++++++++++++++++++++++ tests/run.sh | 2 +- tests/scopes/security.sh | 17 +++- tests/scopes/sessions.sh | 99 ++++++++++++++++++++ 7 files changed, 467 insertions(+), 6 deletions(-) create mode 100644 lib/sessions.py create mode 100644 tests/py/sessions_checks.py create mode 100644 tests/scopes/sessions.sh diff --git a/docs/TESTING_GUIDE.md b/docs/TESTING_GUIDE.md index ef18c0f..306a2b2 100644 --- a/docs/TESTING_GUIDE.md +++ b/docs/TESTING_GUIDE.md @@ -49,6 +49,7 @@ when nothing failed. | `skills/agentkit/` | `skill` | | `ak profiles hooks` (`lib/hooks.py`) | `hooks` | | Herdr resume and `ak last` (`lib/restore.py`, `lib/last.py`, the launch hook in `lib/launch.py`, checks in `tests/py/restore_checks.py`, the fake `tests/fakes-host/herdr/herdr`) | `restore` (+ `dispatch`, `security`) | +| Session records (`lib/sessions.py`, the record call in `lib/launch.py`; checks in `tests/py/sessions_checks.py`) | `sessions` (what a record holds, one file per launch, modes, what does not record, the unchanged launch, the rule that ends a record), `dispatch`, `permissions`, `profiles` (the launch path), `security` (private files, no key) | | anything that prints, logs or writes | `security` | | the frozen interface (grammar, env prefix, outputs) | `contract` | | `scripts/check-public-hygiene.sh`, `.public-hygiene-allow`, any tracked file | `hygiene` (and the CI job `public hygiene`: `bash scripts/check-public-hygiene.sh`) | diff --git a/lib/launch.py b/lib/launch.py index bb3ca16..9d683c5 100644 --- a/lib/launch.py +++ b/lib/launch.py @@ -37,6 +37,7 @@ import last import profiles import restore +import sessions import trust import writers from common import AkError, EXIT_NOT_READY, EXIT_USAGE @@ -523,4 +524,7 @@ def launch(model, kind_name, args, base_env): # Herdr's resume command on ak (lib/restore.py). last.record(prep.env, prep.kind.name, prep.profile, prep.auto) restore.start(prep, prep.env) + # Last, so the record carries this process's id as the CLI inherits + # it: which sessions are running, for `ak ps` (lib/sessions.py). + sessions.record(prep.env, prep.kind, prep.profile, prep.auto) return profiles.exec_command([prep.exe] + argv, prep.env) diff --git a/lib/sessions.py b/lib/sessions.py new file mode 100644 index 0000000..bc7ae0d --- /dev/null +++ b/lib/sessions.py @@ -0,0 +1,179 @@ +"""Session records: which agent sessions `ak` launched are still running. + +Every interactive `ak [@profile]` leaves one small record just before +it becomes the CLI: the process id and that process's start time, the kind, +CLI, provider and profile, the working directory, the launch time, the +posture and, inside Herdr, the pane id. A reader can then join a running +agent to its account. + +One file per session in the kit's state directory (`sessions/`, 0600 files +in a 0700 directory, written atomically, lib/state.py): there is no shared +file and no read-modify-write, so launches at the same moment cannot lose +each other's records. A record never holds a key, a token, a session id, an +account identity or anything the CLI wrote. + +Recording is best effort: whatever goes wrong, the launch goes on unchanged. + +A record ends when its process does. The process id is ak's own: on POSIX ak +replaces itself with the CLI (same id, same start time), on Windows ak stays +the parent for as long as the CLI runs. A record is live only while that id +is alive *with the recorded start time*, so an id the system gave to another +process ends the record instead of reviving it. Where the start time cannot +be read the record lives on the id alone and says so (`verified` False). +""" + +import os +import re +import subprocess +import time + +import profiles +import state + +RECORD_SCHEMA = "session-record-v1" +DIRECTORY = "sessions" +PANE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$") +POSTURES = ("ask", "auto") +PS_TIMEOUT = 2.0 + + +def directory(env): + return os.path.join(state.root(env), DIRECTORY) + + +# ----------------------------------------------------- process start time + +def _start_linux(pid): + try: + with open("/proc/%d/stat" % pid) as handle: + text = handle.read() + except OSError: + return None + # The command name (field 2) is in parentheses and may hold anything; + # the fields after its closing parenthesis start at field 3. + fields = text[text.rfind(")") + 1:].split() + return "ticks:%s" % fields[19] if len(fields) > 19 and fields[19].isdigit() else None + + +def _start_windows(pid): + try: + import ctypes + from ctypes import wintypes + kernel = ctypes.windll.kernel32 + handle = kernel.OpenProcess(0x1000, False, pid) # PROCESS_QUERY_LIMITED_INFORMATION + if not handle: + return None + try: + times = [wintypes.FILETIME() for _ in range(4)] + if not kernel.GetProcessTimes(handle, *[ctypes.byref(t) for t in times]): + return None + return "filetime:%d" % ((times[0].dwHighDateTime << 32) | times[0].dwLowDateTime) + finally: + kernel.CloseHandle(handle) + except Exception: # no ctypes, no such API: the record lives on the id alone + return None + + +def _start_ps(pid): + exe = "/bin/ps" if os.path.exists("/bin/ps") else "ps" + try: + proc = subprocess.run([exe, "-o", "lstart=", "-p", str(pid)], stdin=subprocess.DEVNULL, + stdout=subprocess.PIPE, stderr=subprocess.DEVNULL, timeout=PS_TIMEOUT, + env={"PATH": "/bin:/usr/bin", "LC_ALL": "C", "TZ": "UTC"}) + except (OSError, subprocess.SubprocessError): + return None + text = " ".join(proc.stdout.decode("ascii", "replace").split()) + return "lstart:%s" % text if proc.returncode == 0 and text else None + + +def proc_start(pid): + """An opaque token for when process `pid` started, or None when this host + cannot say. Equal tokens mean the same process; it is never parsed.""" + if os.name == "nt": + return _start_windows(pid) + if os.path.isdir("/proc/%d" % os.getpid()): + return _start_linux(pid) + return _start_ps(pid) + + +# ------------------------------------------------------------------ write + +def pane_of(env): + """The Herdr pane this launch runs in, or None.""" + pane = env.get("HERDR_PANE_ID") or "" + return pane if env.get("HERDR_ENV") == "1" and PANE.match(pane) else None + + +def record(env, kind, profile_name, auto, now=None, pid=None, start=proc_start): + """Leave this launch's record. Returns its path, or None when it could + not be written. Never raises: a launch does not depend on it.""" + try: + pid = os.getpid() if pid is None else pid + now = time.time() if now is None else now + doc = {"schema": RECORD_SCHEMA, "pid": pid, "proc_start": start(pid), "kind": kind.name, + "cli": kind.cli_name, "provider": kind.provider_name or None, "profile": profiles.label(profile_name), + "cwd": os.path.realpath(os.getcwd()), "started_at": int(now), "posture": "auto" if auto else "ask", + "herdr_pane": pane_of(env)} + path = os.path.join(directory(env), "%d-%d.json" % (pid, int(now * 1000))) + state.write_json(path, doc) + return path + except Exception: # best effort by contract: nothing here may stop or change a launch + return None + + +# ------------------------------------------------------------------- read + +def _text(value, limit=4096): + return isinstance(value, str) and 0 < len(value) <= limit + + +def valid(doc): + """True when `doc` is a session record this version wrote.""" + if not isinstance(doc, dict) or doc.get("schema") != RECORD_SCHEMA: + return False + for key in ("pid", "started_at"): + if not isinstance(doc.get(key), int) or isinstance(doc.get(key), bool) or doc[key] < 0: + return False + if doc["pid"] == 0 or not all(_text(doc.get(key), 128) for key in ("kind", "cli", "profile")): + return False + if not doc["profile"].startswith("@") or not _text(doc.get("cwd")) or doc.get("posture") not in POSTURES: + return False + if doc.get("proc_start") is not None and not _text(doc["proc_start"], 128): + return False + if doc.get("provider") is not None and not _text(doc["provider"], 128): + return False + return doc.get("herdr_pane") is None or (isinstance(doc["herdr_pane"], str) and bool(PANE.match(doc["herdr_pane"]))) + + +def read_all(env): + """[(path, record-or-None)] for every record file, in name order. None + marks a file that is not a record (damaged, foreign, half-written).""" + base = directory(env) + try: + names = sorted(n for n in os.listdir(base) if n.endswith(".json") and not n.startswith(".")) + except OSError: + return [] + out = [] + for name in names: + path = os.path.join(base, name) + doc = state.read_json(path) + out.append((path, doc if valid(doc) else None)) + return out + + +def _alive(pid): + import restore + return restore.alive(pid) + + +def liveness(doc, alive=_alive, start=proc_start): + """(live, verified) for a record. `verified` is True when the process's + start time was compared with the recorded one.""" + if not alive(doc["pid"]): + return False, False + if doc.get("proc_start") is None: + return True, False + current = start(doc["pid"]) + if current is None: + return True, False + return current == doc["proc_start"], True diff --git a/tests/py/sessions_checks.py b/tests/py/sessions_checks.py new file mode 100644 index 0000000..a47e710 --- /dev/null +++ b/tests/py/sessions_checks.py @@ -0,0 +1,171 @@ +"""Bash-free checks for session records (lib/sessions.py): what a record +holds, where and how it is written, that a failed write never raises, and +the rule that ends a record (process id plus process start time). + + python3 tests/py/sessions_checks.py (any OS; no bash, no network) + +Prints one `ok ` / `FAIL : ` line per check and exits 1 when +any check failed, so the `sessions` scope folds the lines in. +""" + +import json +import os +import subprocess +import sys +import tempfile +import threading + +HERE = os.path.dirname(os.path.abspath(__file__)) +ROOT = os.path.dirname(os.path.dirname(HERE)) +sys.path.insert(0, os.path.join(ROOT, "lib")) + +import kinds # noqa: E402 +import sessions # noqa: E402 + +FAILS = [] +PLANTED = "PLANTED-KEY-5c1e77aa01" +NOW = 1790000000.0 + + +def check(name, cond, why=""): + if cond: + print("ok %s" % name) + else: + FAILS.append(name) + print("FAIL %s: %s" % (name, why or "condition false")) + + +TMP = tempfile.mkdtemp(prefix="agentkit-sessions-") +STATE = os.path.join(TMP, "state") +MODEL = kinds.load() + + +def env_for(extra=None): + env = {"HOME": TMP, "USERPROFILE": TMP, "AGENTKIT_STATE_DIR": STATE, "ZAI_CODING_API_KEY": PLANTED, + "ANTHROPIC_API_KEY": PLANTED, "PATH": os.environ.get("PATH", "")} + env.update(extra or {}) + return env + + +def files(): + base = sessions.directory(env_for()) + return sorted(os.listdir(base)) if os.path.isdir(base) else [] + + +def doc_of(path): + with open(path) as handle: + return json.load(handle) + + +# ------------------------------------------------------------- the record + +path = sessions.record(env_for(), MODEL.kind("claude"), "work", True, now=NOW) +doc = doc_of(path) if path else {} +KEYS = ["cli", "cwd", "herdr_pane", "kind", "pid", "posture", "proc_start", "profile", "provider", "schema", "started_at"] +check("sessions record: one file under the state directory's sessions/", + path is not None and os.path.dirname(path) == os.path.join(STATE, "sessions") and len(files()) == 1, str(files())) +check("sessions record: it holds exactly the documented keys", sorted(doc) == KEYS, str(sorted(doc))) +check("sessions record: kind, CLI, profile, posture, launch time and directory", + (doc.get("kind"), doc.get("cli"), doc.get("profile"), doc.get("posture"), doc.get("started_at")) + == ("claude", "claude", "@work", "auto", int(NOW)) and doc.get("cwd") == os.path.realpath(os.getcwd()), str(doc)) +check("sessions record: the process id is this process's, with its start time", + doc.get("pid") == os.getpid() and doc.get("proc_start") == sessions.proc_start(os.getpid()), str(doc)) +check("sessions record: a CLI's own login has no provider; outside Herdr no pane", + doc.get("provider") is None and doc.get("herdr_pane") is None, str(doc)) +if os.name == "posix": + check("sessions record: the file is 0600 and its directory 0700", + os.stat(path).st_mode & 0o777 == 0o600 and os.stat(os.path.dirname(path)).st_mode & 0o777 == 0o700) +check("sessions record: no temporary file is left beside it", not [n for n in os.listdir(os.path.dirname(path)) if n.startswith(".")]) + +glm = doc_of(sessions.record(env_for({"HERDR_ENV": "1", "HERDR_PANE_ID": "w1:p2"}), MODEL.kind("claude-glm"), None, False, + now=NOW + 1)) +check("sessions record: a provider kind names its provider; the default profile is @default; the opt-out is ask", + (glm["kind"], glm["cli"], glm["provider"], glm["profile"], glm["posture"]) + == ("claude-glm", "claude", "zai", "@default", "ask"), str(glm)) +check("sessions record: inside Herdr the pane id is kept", glm["herdr_pane"] == "w1:p2", str(glm)) +for label, extra in (("without HERDR_ENV=1", {"HERDR_PANE_ID": "w1:p2"}), + ("with a pane id that is not one", {"HERDR_ENV": "1", "HERDR_PANE_ID": "w1:p2; rm -rf /"}), + ("with an over-long pane id", {"HERDR_ENV": "1", "HERDR_PANE_ID": "w" * 80})): + got = doc_of(sessions.record(env_for(extra), MODEL.kind("codex"), "work", True, now=NOW + 2, pid=4242000 + len(label))) + check("sessions record: %s no pane is recorded" % label, got["herdr_pane"] is None, str(got)) +blob = "".join(open(os.path.join(STATE, "sessions", n)).read() for n in files()) +check("sessions record: no key value reaches a record", PLANTED not in blob) +check("sessions record: every record is one this version reads back", all(doc for _p, doc in sessions.read_all(env_for()))) + +# concurrency: no shared file, so launches at the same moment keep every record +before = len(files()) +threads = [threading.Thread(target=sessions.record, args=(env_for(), MODEL.kind("codex"), "w%d" % i, True), + kwargs={"now": NOW + 5, "pid": 5000000 + i}) for i in range(12)] +for t in threads: + t.start() +for t in threads: + t.join() +check("sessions record: twelve launches at the same moment leave twelve records", len(files()) - before == 12, + str(len(files()) - before)) + +# best effort: a state directory that cannot be written never raises +blocked = os.path.join(TMP, "blocked") +with open(blocked, "w") as handle: + handle.write("a file where the state directory should be") +try: + result = sessions.record(env_for({"AGENTKIT_STATE_DIR": blocked}), MODEL.kind("claude"), "work", True, now=NOW) + raised = None +except Exception as exc: # noqa: BLE001 - the point of the check + result, raised = "raised", exc +check("sessions record: an unwritable state directory is ignored (no record, no exception)", result is None, str(raised)) + + +def boom(_pid): + raise RuntimeError("no start time on this host") + + +try: + result = sessions.record(env_for(), MODEL.kind("claude"), "work", True, now=NOW + 9, pid=6000001, start=boom) +except Exception as exc: # noqa: BLE001 + result = exc +check("sessions record: a failure while reading the start time is ignored too", result is None, str(result)) + +# ---------------------------------------------------------------- liveness + +me = doc_of(path) +check("sessions liveness: this process's own record is live and verified", sessions.liveness(me) == (True, True), + str(sessions.liveness(me))) +check("sessions liveness: the start time of a process is stable", + sessions.proc_start(os.getpid()) is not None and sessions.proc_start(os.getpid()) == sessions.proc_start(os.getpid())) +child = subprocess.Popen([sys.executable, "-c", "import sys; sys.stdin.read()"], stdin=subprocess.PIPE) +theirs = dict(me, pid=child.pid, proc_start=sessions.proc_start(child.pid)) +check("sessions liveness: a running child is live and verified", sessions.liveness(theirs) == (True, True), + str(sessions.liveness(theirs))) +reused = dict(theirs, proc_start=(theirs["proc_start"] or "x") + "-earlier") +check("sessions liveness: a live process id with another start time is a reused id: the record is ended", + sessions.liveness(reused)[0] is False, str(sessions.liveness(reused))) +unknown = dict(theirs, proc_start=None) +check("sessions liveness: without a recorded start time the record lives on the id alone, unverified", + sessions.liveness(unknown) == (True, False), str(sessions.liveness(unknown))) +check("sessions liveness: ... and the same when this host cannot read one now", + sessions.liveness(theirs, start=lambda pid: None) == (True, False)) +child.stdin.close() +child.wait() +check("sessions liveness: once the process is gone the record is ended", sessions.liveness(theirs)[0] is False, + str(sessions.liveness(theirs))) + +# ------------------------------------------------------------ reading back + +base = os.path.join(STATE, "sessions") +with open(os.path.join(base, "0-damaged.json"), "w") as handle: + handle.write("{ not json") +with open(os.path.join(base, "0-foreign.json"), "w") as handle: + json.dump({"schema": "something-else", "pid": 1}, handle) +for name, change in (("0-bad-pid", {"pid": "12"}), ("0-bad-posture", {"posture": "yolo"}), ("0-bad-profile", {"profile": "work"}), + ("0-bad-pane", {"herdr_pane": "w1:p2 && x"}), ("0-zero-pid", {"pid": 0}), ("0-bool-pid", {"pid": True})): + with open(os.path.join(base, name + ".json"), "w") as handle: + json.dump(dict(me, **change), handle) +bad = [os.path.basename(p) for p, doc in sessions.read_all(env_for()) if doc is None] +check("sessions read: damaged, foreign and malformed files are marked, never returned as records", + bad == ["0-bad-pane.json", "0-bad-pid.json", "0-bad-posture.json", "0-bad-profile.json", "0-bool-pid.json", + "0-damaged.json", "0-foreign.json", "0-zero-pid.json"], str(bad)) +check("sessions read: a missing directory is no record, not an error", + sessions.read_all(env_for({"AGENTKIT_STATE_DIR": os.path.join(TMP, "nowhere")})) == []) + +if FAILS: + sys.exit(1) diff --git a/tests/run.sh b/tests/run.sh index 8cddeb5..c8edbdc 100644 --- a/tests/run.sh +++ b/tests/run.sh @@ -18,7 +18,7 @@ FAKES="${TESTS}/fakes" export FAKES # read by the scopes in tests/scopes/ # Order matters only for readability of the report. -ALL_SCOPES="harness lint kinds dispatch profiles permissions doctor usage usage-providers pick pick-kinds capacity lease setup setup-skill orchestrate-skill run install update aliases skill hooks restore security contract hygiene oss" +ALL_SCOPES="harness lint kinds dispatch profiles permissions doctor usage usage-providers pick pick-kinds capacity lease setup setup-skill orchestrate-skill run install update aliases skill hooks restore sessions security contract hygiene oss" KNOWN_SCOPES="${ALL_SCOPES} live setup-docker-live harness-selftest" PASSES=0 diff --git a/tests/scopes/security.sh b/tests/scopes/security.sh index b6a9145..340e3b7 100644 --- a/tests/scopes/security.sh +++ b/tests/scopes/security.sh @@ -417,18 +417,25 @@ security_trust_cwd() { sec_env_file root="${BOX}/home/.local/share/agentkit/profiles" mkdir -p "${root}/claude/work" "${root}/codex/work" - # The launch record of `ak last` (the kit's state, not a CLI config) is - # the one file every interactive launch writes; it is checked below. - before="$(cd "${BOX}" && find . -type f -not -path './out' -not -path './err' -not -name launches.json | sort | xargs cksum)" + # The launch record of `ak last` and the session record of `ak ps` (the + # kit's state, not a CLI config) are the only files every interactive + # launch writes; both are checked below. + before="$(cd "${BOX}" && find . -type f -not -path './out' -not -path './err' -not -name launches.json -not -path '*/agentkit/sessions/*' | sort | xargs cksum)" ak -- claude @work >/dev/null; ak -- codex @work >/dev/null; ak -- claude >/dev/null ak_split FAKE_MODE=headless -- run claude @work --output-format json -- "hello" - after="$(cd "${BOX}" && find . -type f -not -path './out' -not -path './err' -not -name launches.json | sort | xargs cksum)" + after="$(cd "${BOX}" && find . -type f -not -path './out' -not -path './err' -not -name launches.json -not -path '*/agentkit/sessions/*' | sort | xargs cksum)" expect_eq "security trust-cwd: without the opt-in no launch writes a trust entry" "${before}" "${after}" expect_eq "security launches: the ak last record is private and holds no key" \ "$(file_mode "${BOX}/home/.local/state/agentkit/launches.json") $(leaked "${BOX}/home/.local/state/agentkit/launches.json")" "600 " + cat "${BOX}/home/.local/state/agentkit/sessions/"*.json > "${BOX}/session-records" + expect_eq "security sessions: every session record is private, in a private directory, and holds no key" \ + "$(for f in "${BOX}/home/.local/state/agentkit/sessions/"*.json; do file_mode "${f}"; done | sort -u) $(file_mode "${BOX}/home/.local/state/agentkit/sessions") $(leaked "${BOX}/session-records")" "600 700 " + rm -f "${BOX}/session-records" + expect_eq "security sessions: three interactive launches left three records, the headless run none" \ + "$(find "${BOX}/home/.local/state/agentkit/sessions" -name '*.json' | wc -l | tr -d ' ')" "3" out="$(ak -- claude @work --trust-cwd; ak -- codex @work --trust-cwd)" expect_eq "security trust-cwd: with it, exactly the two profile files change" \ - "$(cd "${BOX}" && find . -newer "${BOX}/home/.config/agentkit/env" -type f -not -path './out' -not -path './err' -not -name launches.json | sort | tr '\n' ' ')" \ + "$(cd "${BOX}" && find . -newer "${BOX}/home/.config/agentkit/env" -type f -not -path './out' -not -path './err' -not -name launches.json -not -path '*/agentkit/sessions/*' | sort | tr '\n' ' ')" \ "./home/.local/share/agentkit/profiles/claude/work/.claude.json ./home/.local/share/agentkit/profiles/codex/work/config.toml " expect_eq "security trust-cwd: no key in any output" "$(printf '%s' "${out}" > "${BOX}/trust-out"; leaked "${BOX}/trust-out")" "" expect_eq "security trust-cwd: the files it creates are mode 600" \ diff --git a/tests/scopes/sessions.sh b/tests/scopes/sessions.sh new file mode 100644 index 0000000..eca004d --- /dev/null +++ b/tests/scopes/sessions.sh @@ -0,0 +1,99 @@ +# shellcheck shell=bash +# Session records (lib/sessions.py): every interactive launch leaves one +# record of the running session — and nothing else changes about a launch. +# The record's contents and the rule that ends it are covered bash free by +# tests/py/sessions_checks.py; here the real launcher writes them. + +sessions_dir() { + printf '%s' "${BOX}/home/.local/state/agentkit/sessions" +} + +sessions_count() { + find "$(sessions_dir)" -name '*.json' 2>/dev/null | wc -l | tr -d ' ' +} + +# sessions_newest — the path of the record written last. +sessions_newest() { + # shellcheck disable=SC2012 # names are -.json: no odd characters + ls -t "$(sessions_dir)"/*.json 2>/dev/null | head -1 +} + +scope_sessions() { + local out plain blocked rec pid cmd + box_new sessions claude codex agent + box_env_file ZAI_CODING_API_KEY=fake-zai-key-sessions + mkdir -p "${BOX}/home/.local/share/agentkit/profiles/claude/work" + + py_checks sessions_checks.py + + out="$(ak -- claude @work)" + expect_has "sessions: the CLI still starts" "${out}" "CLI=claude" + expect_eq "sessions: an interactive launch leaves one record" "$(sessions_count)" 1 + rec="$(sessions_newest)" + expect_eq "sessions: with its kind, CLI, profile and posture" \ + "$(json_get "${rec}" '[d["kind"], d["cli"], d["profile"], d["posture"], d["provider"], d["herdr_pane"]]')" \ + '["claude", "claude", "@work", "auto", null, null]' + expect_eq "sessions: and the directory it was launched in" "$(json_get "${rec}" 'd["cwd"]')" \ + "$(cd "${BOX}/work" && pwd -P)" + expect_eq "sessions: the record is 0600 in a 0700 directory" "$(file_mode "${rec}") $(file_mode "$(sessions_dir)")" "600 700" + + ak -- claude --ask >/dev/null + expect_eq "sessions: the opt-out is recorded as ask, the default profile as @default" \ + "$(json_get "$(sessions_newest)" '[d["profile"], d["posture"]]')" '["@default", "ask"]' + ak AGENTKIT_PERMISSIONS=ask -- claude @work >/dev/null + expect_eq "sessions: AGENTKIT_PERMISSIONS=ask is recorded as ask too" "$(json_get "$(sessions_newest)" 'd["posture"]')" "ask" + ak -- claude-glm >/dev/null + expect_eq "sessions: a provider kind names its provider" \ + "$(json_get "$(sessions_newest)" '[d["kind"], d["cli"], d["provider"]]')" '["claude-glm", "claude", "zai"]' + expect_lacks "sessions: no key value reaches any record" "$(cat "$(sessions_dir)"/*.json)" "fake-zai-key-sessions" + ak HERDR_ENV=1 HERDR_PANE_ID=w1:p7 AGENTKIT_HERDR_RESUME=0 -- claude @work >/dev/null + expect_eq "sessions: inside Herdr the pane id is recorded" "$(json_get "$(sessions_newest)" 'd["herdr_pane"]')" "w1:p7" + expect_eq "sessions: five launches, five records (one file each)" "$(sessions_count)" 5 + + # What does not record. + ak FAKE_MODE=headless -- run claude @work -- "hi" >/dev/null + expect_eq "sessions: a headless ak run leaves no record" "$(sessions_count)" 5 + ak -- cursor -l >/dev/null + expect_eq "sessions: a standalone subcommand (the session list) leaves no record" "$(sessions_count)" 5 + ak -- usage >/dev/null; ak -- doctor >/dev/null; ak -- last ls >/dev/null + expect_eq "sessions: other verbs leave no record" "$(sessions_count)" 5 + + # The launch itself is unchanged, with or without a writable state directory. + plain="$(ak FAKE_ENV_NAMES=1 -- claude @work -c)" + : > "${BOX}/not-a-directory" + blocked="$(ak FAKE_ENV_NAMES=1 AGENTKIT_STATE_DIR="${BOX}/not-a-directory" -- claude @work -c)" + expect_has "sessions: a state directory that cannot be written does not stop the launch" "${blocked}" "CLI=claude" + expect_eq "sessions: ... and the argv the CLI receives is the same" "$(argv_of "${blocked}")" "$(argv_of "${plain}")" + expect_eq "sessions: ... and so are the variables it receives (the moved state directory aside)" \ + "$(printf '%s\n' "${blocked}" | grep '^ENVNAME=' | grep -v '^ENVNAME=AGENTKIT_STATE_DIR$' | sort)" \ + "$(printf '%s\n' "${plain}" | grep '^ENVNAME=' | sort)" + expect_eq "sessions: ... and the kit says nothing about the record it could not write" \ + "$(printf '%s\n' "${blocked}" | grep -c '^ak: ')" "$(printf '%s\n' "${plain}" | grep -c '^ak: ')" + + # The recorded process id is the CLI's own: ak became the CLI. + ak FAKE_SLEEP=3 -- claude @work >/dev/null & + local waiter=$! tries=0 + rec="" + while [[ ${tries} -lt 40 ]]; do + rec="$(sessions_newest)" + pid="$(json_get "${rec}" 'd["pid"]' 2>/dev/null)" + cmd="$(ps -o command= -p "${pid:-0}" 2>/dev/null)" + [[ "${cmd}" == *"${BOX}/bin/claude"* ]] && break + tries=$((tries + 1)) + "${AK_PY}" -c 'import time; time.sleep(0.1)' + done + expect_has "sessions: while the CLI runs, the recorded process id is the CLI's" "${cmd}" "${BOX}/bin/claude" + check "sessions: ... and that record is live" "${AK_PY}" -c ' +import json, sys +sys.path.insert(0, sys.argv[2]) +import sessions +doc = json.load(open(sys.argv[1])) +sys.exit(0 if sessions.liveness(doc) == (True, True) else 1)' "${rec}" "${ROOT}/lib" + wait "${waiter}" 2>/dev/null + check "sessions: once the CLI exits, the record is ended" "${AK_PY}" -c ' +import json, sys +sys.path.insert(0, sys.argv[2]) +import sessions +doc = json.load(open(sys.argv[1])) +sys.exit(0 if sessions.liveness(doc)[0] is False else 1)' "${rec}" "${ROOT}/lib" +} From 50914a2a3abb9f5d2ad9a7a78775c8056746ea60 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 01:00:45 -0500 Subject: [PATCH 04/11] feat(ps): ak ps lists the running sessions with their account ak ps [--json] lists the interactive sessions ak launched that are still running, oldest first: kind, CLI, provider, profile, directory, launch time, posture, Herdr pane and the account's capacity. Capacity comes from the usage cache alone, with the reading's age: no vendor is queried and no login is touched. Ended records are removed as it reads; of several live sessions naming one Herdr pane only the newest is listed. --json is the new sessions-v1 schema. Interface stays 1. Co-Authored-By: Claude Fable 5.2 --- AGENTS.md | 6 +- CHANGELOG.md | 17 ++++ README.md | 2 + docs/SECURITY.md | 11 ++- docs/TESTING_GUIDE.md | 2 +- docs/ps.md | 103 +++++++++++++++++++ docs/schema/sessions-v1.json | 47 +++++++++ lib/ak.py | 5 + lib/sessions.py | 164 +++++++++++++++++++++++++++++++ skills/agentkit/SKILL.md | 1 + tests/py/sessions_checks.py | 185 +++++++++++++++++++++++++++++++++++ tests/scopes/sessions.sh | 44 +++++++++ 12 files changed, 582 insertions(+), 5 deletions(-) create mode 100644 docs/ps.md create mode 100644 docs/schema/sessions-v1.json diff --git a/AGENTS.md b/AGENTS.md index 4325e59..a7bb78e 100644 --- a/AGENTS.md +++ b/AGENTS.md @@ -15,7 +15,7 @@ agentkit (alias ak); skills agentkit, agentkit-setup, agentkit-orchestrate | Path | What | | --- | --- | | `bin/ak`, `bin/agentkit` | one byte-identical bash launcher: sources the env file, exec's the python core | -| `lib/ak.py` + `lib/*.py` | the python3 stdlib core: `launch` (dispatcher), `kinds` (+ `tomlmini`, `writers`), `profiles`, `run`, `envcmd`, `doctor`, `usage`, `pick` (`ak pick`, the account-selection policy over the usage rows), `capacity` (`ak capacity`, one account's room and verdict, pick's arithmetic), `state` (the machine state dir: usage cache, atomic 0600 writes), `lease` (`ak lease`, advisory account leases), `setup`, `aliases`, `installer`, `update` (`ak update`, the verified vendor update: discover, install, resolve, re-pin; `docs/update.md`), `hooks`, `common` | +| `lib/ak.py` + `lib/*.py` | the python3 stdlib core: `launch` (dispatcher), `kinds` (+ `tomlmini`, `writers`), `profiles`, `run`, `envcmd`, `doctor`, `usage`, `pick` (`ak pick`, the account-selection policy over the usage rows), `capacity` (`ak capacity`, one account's room and verdict, pick's arithmetic), `state` (the machine state dir: usage cache, atomic 0600 writes), `lease` (`ak lease`, advisory account leases), `setup`, `aliases`, `installer`, `update` (`ak update`, the verified vendor update: discover, install, resolve, re-pin; `docs/update.md`), `sessions` (the record every interactive launch leaves and `ak ps`, the running sessions joined to their account; `docs/ps.md`), `hooks`, `common` | | `lib/common.sh`, `lib/env.template` | the launcher's shell half; the env file template | | `providers.toml` | the kinds model as data (CLIs, providers, kinds) — see `docs/kinds.md` | | `skills/agentkit/` | the bundled skill (`ak --skill`): `SKILL.md` + `references/` (`accounts.md`, `usage.md`) | @@ -23,11 +23,11 @@ agentkit (alias ak); skills agentkit, agentkit-setup, agentkit-orchestrate | `skills/agentkit-orchestrate/` | the orchestration skill (`ak --skill orchestrate`): several agents over several accounts; see `docs/orchestration.md` | | `install.sh`, `install.ps1`, `win/*.cmd` | installers (POSIX, Windows) and Windows shims | | `tests/run.sh`, `tests/scopes/`, `tests/fakes/`, `tests/py/` | the suite: sandbox HOME, fake CLIs, one scope per surface | -| `docs/` | user docs, `SECURITY.md`, `TESTING_GUIDE.md`, `schema/doctor-v1.json`, `schema/usage-v1.json`, `schema/pick-v1.json`, `schema/capacity-v1.json`, `schema/leases-v1.json`, `schema/profiles-v1.json`, `schema/setup-probe-v1.json`, `schema/setup-verify-v1.json`, `accounts.md`, `orchestration.md`, `setup.md`, `usage.md` | +| `docs/` | user docs, `SECURITY.md`, `TESTING_GUIDE.md`, `schema/doctor-v1.json`, `schema/usage-v1.json`, `schema/pick-v1.json`, `schema/capacity-v1.json`, `schema/leases-v1.json`, `schema/profiles-v1.json`, `schema/setup-probe-v1.json`, `schema/setup-verify-v1.json`, `schema/sessions-v1.json`, `ps.md`, `accounts.md`, `orchestration.md`, `setup.md`, `usage.md` | | `scripts/` | maintainer tooling: `check-public-hygiene.sh`, `release.sh`, `update-pins.sh` | | `.agents/` (+ `.claude`, `.cursor` symlinks) | the agent kit for working on this repo: personas, `dwp-*` delegators, vendored skills, catalog in `.agents/docs/` | -Interface 1 (`ak doctor --json`, `ak env`, `ak run`) is consumed by other tools: a change to it is a breaking change (see `docs/doctor.md`, `docs/run.md`). `ak usage --json` (schema `usage-v1`, `docs/usage.md`), `ak pick --json` (schema `pick-v1`, `docs/usage.md#choosing-an-account`), `ak capacity --json` (schema `capacity-v1`), `ak lease ls --json` (schema `leases-v1`), `ak profiles --json` (schema `profiles-v1`, `docs/profiles.md`) and `ak setup probe|verify --json` (schemas `setup-probe-v1`, `setup-verify-v1`, `docs/setup.md`) are additive, separately versioned surfaces; `ak usage`, `ak pick` and `ak capacity` read logins and query vendors (and keep a cache of usage numbers), `ak lease` keeps a lease store, and `ak setup` guides machine changes, so their rules are in `docs/SECURITY.md`. +Interface 1 (`ak doctor --json`, `ak env`, `ak run`) is consumed by other tools: a change to it is a breaking change (see `docs/doctor.md`, `docs/run.md`). `ak usage --json` (schema `usage-v1`, `docs/usage.md`), `ak pick --json` (schema `pick-v1`, `docs/usage.md#choosing-an-account`), `ak capacity --json` (schema `capacity-v1`), `ak lease ls --json` (schema `leases-v1`), `ak profiles --json` (schema `profiles-v1`, `docs/profiles.md`), `ak ps --json` (schema `sessions-v1`, `docs/ps.md`) and `ak setup probe|verify --json` (schemas `setup-probe-v1`, `setup-verify-v1`, `docs/setup.md`) are additive, separately versioned surfaces; `ak usage`, `ak pick` and `ak capacity` read logins and query vendors (and keep a cache of usage numbers), `ak lease` keeps a lease store, and `ak setup` guides machine changes, so their rules are in `docs/SECURITY.md`. ## Quick commands diff --git a/CHANGELOG.md b/CHANGELOG.md index 4c6d4b6..6982116 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,23 @@ permission posture changes. ## [Unreleased] +### Added + +- **`ak ps [--json]`: the sessions that are running, joined to their + account.** Every interactive `ak [@profile]` now leaves one record + in the kit's state directory (`sessions/`, one `0600` file per session, + best effort — a failed write never changes a launch): the process id and + its start time, kind, CLI, provider, profile, directory, launch time, + posture and, inside Herdr, the pane id. `ak ps` lists the ones still + running, oldest first, and removes the records of those that ended; a + session counts as running only while its process id is alive with the + recorded start time. Each is joined to its account's capacity from the + usage cache alone (verdict, free share, reset, and the reading's age): no + vendor is queried and no login is touched. `--json` is the new, separately + versioned `sessions-v1` schema. An agent started without `ak`, and a + headless `ak run`, have no entry. Interface stays **1**; a launch's argv + and environment are unchanged. See [`docs/ps.md`](docs/ps.md). + ## [1.5.2] - 2026-11-19 A patch release with no runtime change: `ak` behaves exactly as in 1.5.1, and diff --git a/README.md b/README.md index ed81635..4ca9263 100644 --- a/README.md +++ b/README.md @@ -138,6 +138,7 @@ ak claude-glm # Claude Code routed to Z.AI GLM (key from ~/.config/ ak claude --ask # opt out for this launch: the CLI asks before acting ak claude -- @src/app.ts # `--` sends everything after it to the CLI untouched ak usage # quota and usage of every account, one row each +ak ps # the sessions ak launched that are still running, with their account ak run codex --cwd ~/src/api --timeout 900 --output-format json -- "fix the failing test" ``` @@ -266,6 +267,7 @@ the threat model is [docs/SECURITY.md](docs/SECURITY.md). - [Set up on any machine or container](docs/setup.md) — `ak setup`, the `agentkit-setup` skill, container recipes - [`ak usage`, `ak pick`, `ak capacity` and `ak lease`](docs/usage.md) — quota per account, reading the table, choosing an account, one account's room, the usage cache, leases ([usage-v1](docs/schema/usage-v1.json), [pick-v1](docs/schema/pick-v1.json), [capacity-v1](docs/schema/capacity-v1.json), [leases-v1](docs/schema/leases-v1.json)) - [Orchestration](docs/orchestration.md) — several agents over several accounts: worktrees, failover, Herdr, Deep Work Plans +- [`ak ps`](docs/ps.md) — the sessions that are running: account, posture, Herdr pane and capacity of each ([schema](docs/schema/sessions-v1.json)) - [`ak doctor` and `ak env`](docs/doctor.md) — interface 1 outputs ([schema](docs/schema/doctor-v1.json)) - [Install, `ak install`, aliases](docs/install.md) - [Threat model](docs/SECURITY.md) · [Testing](docs/TESTING_GUIDE.md) · [Changelog](CHANGELOG.md) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index f61c227..c357e0c 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -147,6 +147,14 @@ profile and its headroom, nothing else. (no read-modify-write, safe under concurrent runs), pruned past the newest 5000 per account. Read only by `ak usage` for its `advisory` block, which never reaches the usage cache, `ak capacity` or `ak pick`. +- **Session records** (`/sessions/`, `0600` files in a `0700` + directory): written by an interactive launch, read and pruned by `ak ps`. + They hold names, a directory, times and a process id — never a key, a + token, a session id, an account identity or the CLI's environment. `ak ps` + joins them to the usage cache only: it makes no request, refreshes no + login and writes nothing but the removal of ended records. The pane id is + taken from `HERDR_PANE_ID` only when `HERDR_ENV=1` and only when it has + the form of one. - **Accounts:** work moves only among the accounts you declared for the work, within each vendor's terms; no agent creates an account, renews a login or spends a Codex reset. @@ -231,10 +239,11 @@ paths. | `~/.config/agentkit/env` (`AGENTKIT_ENV`) | your keys and settings (created once, never overwritten) | 600 | | `~/.config/agentkit/aliases.json` | alias definitions | 600 | | your shell rc | one guarded block (PATH + aliases) | unchanged | -| `~/.local/state/agentkit/` (`AGENTKIT_STATE_DIR`) | `usage-cache/@.json` (usage numbers only), `leases/leases.json`, `launches.json` (per working directory: the kind, profile and posture of the last interactive launch, for `ak last`) | dirs 700, files 600 | +| `~/.local/state/agentkit/` (`AGENTKIT_STATE_DIR`) | `usage-cache/@.json` (usage numbers only), `leases/leases.json`, `launches.json` (per working directory: the kind, profile and posture of the last interactive launch, for `ak last`), `sessions/-