From 51e2103724f13e51cd761c097752d9f86998a712 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 08:06:58 -0500 Subject: [PATCH 01/11] feat(pick): a declared account pool (--only, AGENTKIT_POOL) --only @a,@b on ak pick (also with --kinds), ak run --pick and ak fanout run, or AGENTKIT_POOL when no flag is given, keeps every choice, failover included, inside those profiles. A profile outside the pool is listed as 'outside the pool' and never chosen; --allow-unknown does not admit it. Additive: without either, nothing changes. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 +++ docs/fanout.md | 3 +- docs/run.md | 5 +-- docs/usage.md | 13 ++++++++ lib/fanout.py | 15 +++++++-- lib/pick.py | 62 +++++++++++++++++++++++++++++++++----- lib/run.py | 23 +++++++++++--- tests/py/pick_checks.py | 42 ++++++++++++++++++++++++++ tests/scopes/fanout.sh | 11 +++++++ tests/scopes/pick-kinds.sh | 15 +++++++++ tests/scopes/run.sh | 16 +++++++++- 11 files changed, 191 insertions(+), 18 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea369f1..e47ef21 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,10 @@ permission posture changes. ### Added +- **A declared account pool.** `--only @a,@b` on `ak pick` (also with `--kinds`), `ak run --pick` and `ak fanout run`, or `AGENTKIT_POOL=@a,@b` when no flag is given, keeps every choice — failover included — inside those profiles. A profile outside the pool is listed as `outside the pool` and never chosen. Additive; without either nothing changes. + +### 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 diff --git a/docs/fanout.md b/docs/fanout.md index 1860e94..955c380 100644 --- a/docs/fanout.md +++ b/docs/fanout.md @@ -3,7 +3,7 @@ ``` ak fanout run --tasks FILE|- [--kind KIND] [--fallback KIND,KIND] [--base REF] [--max-parallel N] [--failover N] [--timeout SECONDS] [--owner ADDR] - [--worktrees DIR] [--ask] [--trust-cwd] [--json] + [--worktrees DIR] [--only @a,@b] [--ask] [--trust-cwd] [--json] ak fanout ls ak fanout clean [--discard] ``` @@ -74,6 +74,7 @@ opt-out always wins. A new worktree is a folder the CLI has not seen: pass | `--fallback KIND,KIND` | further kinds a lane may fall back to, in priority order | | `--timeout SECONDS` | per attempt | | `--base REF` | the commit every lane starts from | +| `--only @a,@b` | lanes use only these profiles ([the declared pool](usage.md#the-declared-pool---only-agentkit_pool)); default `AGENTKIT_POOL` | ## When an account runs dry diff --git a/docs/run.md b/docs/run.md index 2c2ccaf..f34e0df 100644 --- a/docs/run.md +++ b/docs/run.md @@ -2,7 +2,7 @@ ``` ak run [@profile] [--cwd DIR] [--timeout SECONDS] [--output-format text|json] [--ask | --auto] [--trust-cwd] -- "" -ak run --pick [--failover N] [--fallback KIND,KIND] [--owner ADDR] [--exclude @profile]... [the same options] -- "" +ak run --pick [--failover N] [--fallback KIND,KIND] [--owner ADDR] [--exclude @profile]... [--only @a,@b] [the same options] -- "" ``` Runs one prompt non-interactively in `--cwd` (default: the current @@ -49,8 +49,9 @@ run does not start: exit 3, and the error names the soonest reset. | `--fallback KIND,KIND` | further kinds, in priority order, tried when the kinds before them have no account left | | `--owner ADDR` | hold an [`ak lease`](usage.md) on the account while an attempt runs, released when it ends — on success, failure, timeout and cancellation alike | | `--exclude @profile` | leave an account out of the choice, for every kind (repeatable) — one already found spent, or busy | +| `--only @a,@b` | choose only among these profiles, also when failing over ([the declared pool](usage.md#the-declared-pool---only-agentkit_pool)); default `AGENTKIT_POOL` | -All four need `--pick`. +All five need `--pick`. ### When a run moves to another account diff --git a/docs/usage.md b/docs/usage.md index 4c87613..6fb8ed4 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -452,6 +452,19 @@ knowledge. A CLI that declares a `models` list in providers.toml refuses a value it does not accept; without one the value passes through and the CLI validates it (Claude accepts its sonnet/opus/haiku aliases natively). + +### The declared pool: `--only`, `AGENTKIT_POOL` + +Work is often given a fixed set of accounts. `--only @a,@b` (repeatable; bare +names work too) keeps the choice inside that set, and so does the variable +`AGENTKIT_POOL=@a,@b` when no `--only` is given — `--only` wins over it. A +profile outside the pool is never chosen, however much room it has: it is +listed among the candidates as `outside the pool`, and `--allow-unknown` does +not admit it either. `--exclude` still applies inside the pool. A pool that +names no account with room is exit 1, and the message names the pool. The +same flag and variable apply to `ak run --pick` and to every lane of +`ak fanout`. + ## Windows, macOS and Linux One code path everywhere; only where a login lives differs. diff --git a/lib/fanout.py b/lib/fanout.py index 062f09a..5d75ed8 100644 --- a/lib/fanout.py +++ b/lib/fanout.py @@ -65,7 +65,7 @@ USAGE = """usage: ak fanout run --tasks FILE|- [--kind KIND] [--fallback KIND,KIND] [--base REF] [--max-parallel N] [--failover N] [--timeout SECONDS] [--owner ADDR] - [--worktrees DIR] [--ask] [--trust-cwd] [--json] + [--worktrees DIR] [--only @a,@b] [--ask] [--trust-cwd] [--json] ak fanout ls ak fanout clean [--discard] Runs each task of a list in its own git worktree, on its own new branch, on @@ -80,6 +80,7 @@ --timeout S per attempt, in seconds --owner ADDR the lease owner of every lane (default fanout:) --worktrees DIR where the lanes' worktrees go (default: the kit's state directory) + --only @a,@b lanes use only these profiles (default: AGENTKIT_POOL when set) --ask opt out of autonomy for every lane (also AGENTKIT_PERMISSIONS=ask) --json exactly one JSON object, schema fanout-v1 It never merges, pushes or rebases: run your gate in each worktree, merge what passes. @@ -141,11 +142,11 @@ def facts(env, worktree, base): def parse_run(args): opts = {"tasks": None, "kind": None, "fallback": [], "base": "HEAD", "max_parallel": None, - "failover": DEFAULT_FAILOVER, "timeout": None, "owner": None, "worktrees": None, "ask": False, + "failover": DEFAULT_FAILOVER, "timeout": None, "owner": None, "worktrees": None, "ask": False, "only": None, "trust_cwd": False, "json": False} valued = {"--tasks": "tasks", "--kind": "kind", "--fallback": "fallback", "--base": "base", "--max-parallel": "max_parallel", "--failover": "failover", "--timeout": "timeout", - "--owner": "owner", "--worktrees": "worktrees"} + "--owner": "owner", "--worktrees": "worktrees", "--only": "only"} i = 0 while i < len(args): arg = args[i] @@ -199,6 +200,12 @@ def _value(flag, text): return lease.check_owner(text) except AkError as exc: raise AkError(str(exc), EXIT_USAGE) + if flag == "--only": + import pick + try: + return pick.parse_pool(text, "--only") + except AkError as exc: + raise AkError(str(exc), EXIT_USAGE) if flag == "--base" and (not text or text.startswith("-")): raise AkError("--base takes a commit, branch or tag, got '%s'" % text, EXIT_USAGE) return text @@ -317,6 +324,8 @@ def run_argv(run, lane, moves_left=None): argv += ["--failover", str(moves_left)] for label in list(run.spent): argv += ["--exclude", label] + if opts.get("only"): + argv += ["--only", ",".join(opts["only"])] if opts["fallback"]: argv += ["--fallback", ",".join(opts["fallback"])] if opts["timeout"]: diff --git a/lib/pick.py b/lib/pick.py index b0b8851..75f1c6e 100644 --- a/lib/pick.py +++ b/lib/pick.py @@ -54,7 +54,7 @@ SCOPED = re.compile(r"^(5h|7d)-(.+)$") USAGE = """usage: ak pick [@profile] [--model NAME] [--need WIN:PCT]... [--reserve PCT] - [--count N] [--exclude @profile]... [--allow-unknown] [--owner ADDR [--reuse @profile]...] + [--count N] [--exclude @profile]... [--only @a,@b] [--allow-unknown] [--owner ADDR [--reuse @profile]...] [--max-age S] [--json] [--timeout SECONDS] ak pick --kinds KIND,KIND,... [--model-for KIND=NAME]... [the same flags] [--json] The account(s) with the most usable headroom for a kind, from the same rows as @@ -69,6 +69,8 @@ --reserve PCT keep PCT% of every window of 7 days or more unused (default 10, max 50) --count N up to N distinct accounts, best first (default 1, max 16) --exclude @name leave an account out (repeatable), e.g. one already busy + --only @a,@b choose only among these profiles: the pool the work was given + (default: AGENTKIT_POOL when set; every profile otherwise) --allow-unknown connected accounts with no readable quota may be chosen, last --owner ADDR choose for this lease owner: skip Codex accounts leased to anyone, rank by headroom / (1 + active leases) (see ak lease) @@ -173,6 +175,38 @@ def evaluate(row, model, reserve, needs, now): # ------------------------------------------------------------------ cap +POOL_VAR = "AGENTKIT_POOL" +OUTSIDE_POOL = "outside the pool" + + +def parse_pool(text, source): + """'@a,@b' (or 'a,b') -> ['@a', '@b']; a name that is not a profile name + is a usage error naming where it came from.""" + labels = [] + for word in (text or "").split(","): + word = word.strip() + if not word: + continue + try: + label = usage._profile_label(profiles.normalize(word[1:] if word.startswith("@") else word)) + except AkError as exc: + raise AkError("%s: %s" % (source, exc)) + if label not in labels: + labels.append(label) + if not labels: + raise AkError("%s names no profile; it takes @a,@b" % source) + return labels + + +def pool_of(opts, env): + """The declared pool: --only, else AGENTKIT_POOL, else None (every profile).""" + if opts.get("only") is not None: + return opts["only"] + if env.get(POOL_VAR, "").strip(): + return parse_pool(env[POOL_VAR], POOL_VAR) + return None + + CAP_VAR = "AGENTKIT_CAPACITY_CAP" CAP_ENTRY = re.compile(r"^([a-z0-9][a-z0-9-]{0,40})?(@[a-z0-9][a-z0-9._-]{0,31})=(\d{1,3})$") DEFAULT_LOW = 25 # ak capacity's thresholds; the low one also marks a capped unmeasured account poor @@ -280,23 +314,29 @@ def apply_cap(cand, caps, low=DEFAULT_LOW, needs=()): def choose(rows, model=None, reserve=DEFAULT_RESERVE, needs=(), count=1, exclude=(), allow_unknown=False, now=0, - caps=(), leases=None, owner=None, low=DEFAULT_LOW, reuse=(), critical=DEFAULT_CRITICAL): + caps=(), leases=None, owner=None, low=DEFAULT_LOW, reuse=(), critical=DEFAULT_CRITICAL, pool=None): """The decision over usage-v1 rows (already in providers.toml + profile order). Returns (chosen, candidates, soonest_reset). `leases` (active lease records) adds `leases` to each candidate; with `owner` it also excludes accounts leased exclusively to anyone (the owner included) and divides headroom by 1 + the active leases, except the owner's own lease on - a profile in `reuse`.""" + a profile in `reuse`. `pool` (a list of profiles, or None) leaves every + other profile ineligible, named `outside the pool`.""" cands = [] for index, row in enumerate(rows): if row["profile"] in exclude: continue cand = evaluate(row, model, reserve, needs, now) cand["_order"] = index + if pool is not None and row["profile"] not in pool: + cand["eligible"] = False + cand["excluded_reason"] = OUTSIDE_POOL + cand["_unknown"] = False # never admitted by --allow-unknown either + cand["_outside"] = True cap = apply_cap(cand, caps, low, needs) cand["verdict"] = verdict(row["status"], cand["headroom_pct"], low, critical, cap) if (allow_unknown and cand["_unknown"] and cand.get("_connected") and not needs - and not cand.get("_unknown_poor")): + and not cand.get("_unknown_poor") and not cand.get("_outside")): cand["eligible"] = True cand["excluded_reason"] = None cand["_others"] = 0 @@ -360,7 +400,7 @@ def _public(cand): def parse_args(args): opts = {"target": None, "profile": None, "model": None, "needs": [], "reserve": DEFAULT_RESERVE, - "count": 1, "exclude": [], "allow_unknown": False, "json": False, "timeout": None, + "count": 1, "exclude": [], "only": None, "allow_unknown": False, "json": False, "timeout": None, "owner": None, "reuse": [], "max_age": state.DEFAULT_MAX_AGE, "kinds": [], "model_for": {}} @@ -409,6 +449,10 @@ def value(i, flag): if not text.startswith("@"): raise AkError("--exclude takes a profile, e.g. @work") opts["exclude"].append(usage._profile_label(profiles.normalize(text[1:]))) + elif arg == "--only": + i += 1 + pool = parse_pool(value(i, arg), "--only") + opts["only"] = pool if opts["only"] is None else opts["only"] + [p for p in pool if p not in opts["only"]] elif arg == "--owner": i += 1 opts["owner"] = lease.check_owner(value(i, arg)) @@ -573,6 +617,7 @@ def _pick_kinds(model, opts, env, now, stdout): raise low, critical = DEFAULT_LOW, DEFAULT_CRITICAL leases = lease.active(env, now) + pool = pool_of(opts, env) soonest = None misses = [] rows_seen = False @@ -586,7 +631,7 @@ def _pick_kinds(model, opts, env, now, stdout): results = [{k: v for k, v in r.items() if not k.startswith("_")} for r in results] chosen, candidates, kind_soonest = choose( results, opts["model_for"].get(kind) or opts["model"], opts["reserve"], opts["needs"], - 1, opts["exclude"], opts["allow_unknown"], now, caps, leases, opts["owner"], low, (), critical) + 1, opts["exclude"], opts["allow_unknown"], now, caps, leases, opts["owner"], low, (), critical, pool) if kind_soonest and (soonest is None or kind_soonest < soonest): soonest = kind_soonest if chosen: @@ -628,7 +673,7 @@ def select(model, opts, env, now): results = [{k: v for k, v in r.items() if not k.startswith("_")} for r in results] return choose(results, opts["model"], opts["reserve"], opts["needs"], opts["count"], opts["exclude"], opts["allow_unknown"], now, caps, - lease.active(env, now), opts["owner"], low, opts["reuse"], critical) + lease.active(env, now), opts["owner"], low, opts["reuse"], critical, pool_of(opts, env)) def main(model, args, env, now=None, stdout=None): @@ -657,6 +702,9 @@ def main(model, args, env, now=None, stdout=None): if not opts["allow_unknown"] and any((c["excluded_reason"] or "").startswith("no readable quota") for c in candidates): hint += " With no readable quota, ak pick %s --allow-unknown chooses a connected account (verdict unknown)." \ % opts["target"] + pool = pool_of(opts, env) + if pool is not None: + hint += " The pool is %s." % ",".join(pool) common.warn("no %s account has room (%s).%s" % (opts["target"], reasons, hint)) return EXIT_NONE if len(chosen) < opts["count"]: diff --git a/lib/run.py b/lib/run.py index 58971ea..020e10f 100644 --- a/lib/run.py +++ b/lib/run.py @@ -54,7 +54,7 @@ USAGE = ('usage: ak run [@profile] [--cwd DIR] [--timeout SECONDS] ' '[--output-format text|json] [--ask | --auto] [--trust-cwd] -- ""\n' - ' ak run --pick [--failover N] [--fallback KIND,KIND] [--owner ADDR] [--exclude @profile]... ' + ' ak run --pick [--failover N] [--fallback KIND,KIND] [--owner ADDR] [--exclude @profile]... [--only @a,@b] ' '[the same options] -- ""') MAX_FAILOVER = 3 @@ -75,6 +75,7 @@ def __init__(self): self.fallback = [] # --fallback K,K: further kinds, in priority order self.owner = None # --owner ADDR: hold a lease on the account while an attempt runs self.exclude = [] # --exclude @profile: an account the choice leaves out (repeatable) + self.only = None # --only @a,@b: the pool the choice keeps to (else AGENTKIT_POOL) def parse(args, env): @@ -102,7 +103,7 @@ def parse(args, env): opts.trust_cwd = True elif tok == "--pick": opts.pick = True - elif tok in ("--cwd", "--timeout", "--output-format", "--failover", "--fallback", "--owner", "--exclude"): + elif tok in ("--cwd", "--timeout", "--output-format", "--failover", "--fallback", "--owner", "--exclude", "--only"): if i + 1 >= n: raise AkError("%s needs a value. %s" % (tok, USAGE), EXIT_USAGE) value = args[i + 1] @@ -120,6 +121,14 @@ def parse(args, env): if not opts.fallback: raise AkError("--fallback takes kinds separated by commas, e.g. --fallback codex,grok", EXIT_USAGE) given.append(tok) + elif tok == "--only": + import pick + try: + pool = pick.parse_pool(value, "--only") + except AkError as exc: + raise AkError(str(exc), EXIT_USAGE) + opts.only = pool if opts.only is None else opts.only + [p for p in pool if p not in opts.only] + given.append(tok) elif tok == "--exclude": if not value.startswith("@"): raise AkError("--exclude takes an @profile, got '%s'" % value, EXIT_USAGE) @@ -611,7 +620,7 @@ def _spent(model, env, kind_name, profile): return False -def _next_account(model, env, order, excluded, owner): +def _next_account(model, env, order, excluded, owner, only=None): """(kind, candidate, soonest reset) of the next account to try: ak pick's own choice for the first kind of `order` that still has one.""" import pick @@ -622,6 +631,8 @@ def _next_account(model, env, order, excluded, owner): args += ["--exclude", label] if owner: args += ["--owner", owner] + if only: + args += ["--only", ",".join(only)] selected = pick.select(model, pick.parse_args(args), env, time.time()) if selected is None: continue @@ -668,11 +679,15 @@ def _run_picked(model, opts, env, cwd): pass try: while True: - kind_name, cand, soonest = _next_account(model, env, order, excluded, opts.owner) + kind_name, cand, soonest = _next_account(model, env, order, excluded, opts.owner, opts.only) if cand is None: stopped = STOP_NONE_LEFT if final is None: hint = (" Soonest reset: %s." % usage._relative(soonest, time.time())) if soonest else "" + import pick + pool = pick.pool_of({"only": opts.only}, env) + if pool is not None: + hint += " The pool is %s." % ",".join(pool) final = {"kind": opts.kind, "profile": "@default", "code": EXIT_NOT_READY, "cli_exit": None, "result_text": "", "truncated": False, "tokens": None, "duration": 0.0, "error": "no %s account has room.%s" % (" or ".join(order), hint)} diff --git a/tests/py/pick_checks.py b/tests/py/pick_checks.py index 81f59ca..6c2c168 100644 --- a/tests/py/pick_checks.py +++ b/tests/py/pick_checks.py @@ -248,4 +248,46 @@ def fake_main(args, rows): check("read-only: lib/pick.py opens no file and starts no process", "open(" not in src and "subprocess" not in src and "os.remove" not in src, "") +# ---------------------------------------------------------------- the pool +# --only / AGENTKIT_POOL: a profile outside the declared pool is never chosen. + +rich, mid, poor = (row("claude", "@rich", [win("5h", 5, 3600)]), row("claude", "@mid", [win("5h", 40, 3600)]), + row("claude", "@poor", [win("5h", 80, 3600)])) +chosen, cands, _s = pick.choose([rich, mid, poor], now=NOW, pool=["@mid", "@poor"]) +check("pool: the roomiest account outside the pool is never chosen", [c["profile"] for c in chosen] == ["@mid"], + str([c["profile"] for c in chosen])) +check("pool: it is listed as a candidate, ineligible, with the reason 'outside the pool'", + [(c["profile"], c["eligible"], c["excluded_reason"]) for c in cands if c["profile"] == "@rich"] + == [("@rich", False, "outside the pool")], str(cands)) +chosen, _c, _s = pick.choose([rich, mid, poor], now=NOW, pool=["@mid", "@poor"], count=3) +check("pool: --count stays inside it", [c["profile"] for c in chosen] == ["@mid", "@poor"], str([c["profile"] for c in chosen])) +chosen, _c, _s = pick.choose([rich, mid, poor], now=NOW, pool=["@mid", "@poor"], exclude=["@mid"]) +check("pool: --exclude still applies inside it", [c["profile"] for c in chosen] == ["@poor"]) +chosen, _c, _s = pick.choose([rich, mid], now=NOW, pool=["@elsewhere"]) +check("pool: a pool that names no account here chooses nothing", chosen == []) +unknown = row("grok", "@grokker", [], status="unsupported", connected=True) +chosen, _c, _s = pick.choose([unknown], now=NOW, pool=["@other"], allow_unknown=True) +check("pool: --allow-unknown never admits an account outside it", chosen == []) +chosen, _c, _s = pick.choose([rich, mid, poor], now=NOW) +check("pool: without a pool nothing changes", [c["profile"] for c in chosen] == ["@rich"]) +check("pool: --only parses @a,@b, bare names and repeats into one list", + pick.parse_args(["claude", "--only", "@a,b", "--only", "@c,@a"])["only"] == ["@a", "@b", "@c"]) +check("pool: @default and @1 are the same profile in a pool", pick.parse_pool("@1,default", "--only") == ["@default"]) +for bad in ("@../x", "", ",", "@bad/name"): + try: + pick.parse_pool(bad, "--only") + ok = False + except Exception as exc: # AkError + ok = getattr(exc, "code", None) == 2 + check("pool: '%s' is a usage error" % bad, ok) +check("pool: AGENTKIT_POOL is the default; --only wins over it", + pick.pool_of({"only": None}, {"AGENTKIT_POOL": "@x,@y"}) == ["@x", "@y"] + and pick.pool_of({"only": ["@z"]}, {"AGENTKIT_POOL": "@x"}) == ["@z"] and pick.pool_of({"only": None}, {}) is None) +try: + pick.pool_of({"only": None}, {"AGENTKIT_POOL": "@bad/name"}) + named = False +except Exception as exc: + named = "AGENTKIT_POOL" in str(exc) and getattr(exc, "code", None) == 2 +check("pool: a bad AGENTKIT_POOL is a usage error that names the variable", named) + sys.exit(1 if FAILS else 0) diff --git a/tests/scopes/fanout.sh b/tests/scopes/fanout.sh index a12325d..037f07b 100644 --- a/tests/scopes/fanout.sh +++ b/tests/scopes/fanout.sh @@ -144,6 +144,17 @@ scope_fanout() { "$(json_get "${BOX}/fan2.json" 'd["lanes"][1]["worktree"]')" "${BOX}/trees/${run}/docs" check "fanout: ... starting from the base, not from the newer HEAD" bash -c '[[ ! -e "$1/second.txt" ]]' _ "${BOX}/trees/${run}/docs" + # --- the declared pool --------------------------------------------------------- + fanout_tasks "${tasks}" claude one two + fanout_run -- fanout run --tasks "${tasks}" --only @b --max-parallel 1 --json; status=$? + expect_eq "fanout pool: --only keeps every lane inside the pool" \ + "${status}:$(json_get "${BOX}/out" '[l["profile"] for l in d["lanes"]]')" '0:["@b", "@b"]' + fanout_run AGENTKIT_POOL=@b -- fanout run --tasks "${tasks}" --max-parallel 1 --json; status=$? + expect_eq "fanout pool: AGENTKIT_POOL reaches every lane" \ + "${status}:$(json_get "${BOX}/out" '[l["profile"] for l in d["lanes"]]')" '0:["@b", "@b"]' + fanout_run -- fanout run --tasks "${tasks}" --only @bad/name --json; status=$? + expect_eq "fanout pool: a bad --only is a usage error" "${status}" 2 + # --- lanes in parallel, an exclusive account one lane at a time ----------------- fanout_tasks "${tasks}" claude one two three start="$("${AK_PY}" -c 'import time; print(time.time())')" diff --git a/tests/scopes/pick-kinds.sh b/tests/scopes/pick-kinds.sh index 0d34016..b2be866 100644 --- a/tests/scopes/pick-kinds.sh +++ b/tests/scopes/pick-kinds.sh @@ -47,6 +47,21 @@ PY expect_eq "pick kinds: --model-for sets the model" "$(json_get "${doc}" 'd["model"]')" 'sonnet' expect_eq "pick kinds: the model rides the launch argv head-level" "$(json_get "${doc}" 'd["launch"]["argv"]')" '["ak", "claude", "@work", "--model", "sonnet"]' + # The declared pool: --only, or AGENTKIT_POOL, keeps every choice inside it. + ak_split "${url}" -- pick --kinds claude-glm,claude --only @2 --json; status=$? + expect_eq "pick pool: --kinds with --only picks inside the pool (@2), not the roomiest (@work)" \ + "${status}:$(json_get "${BOX}/out" 'd["profile"]')" "0:@2" + ak_split "${url}" AGENTKIT_POOL=@2,@default -- pick claude --count 3 --json; status=$? + expect_eq "pick pool: AGENTKIT_POOL does the same for the single-kind pick" \ + "${status}:$(json_get "${BOX}/out" '[c["profile"] for c in d["chosen"]]')" '0:["@2", "@default"]' + ak_split "${url}" AGENTKIT_POOL=@2 -- pick claude --only @work --json; status=$? + expect_eq "pick pool: --only wins over AGENTKIT_POOL" "${status}:$(json_get "${BOX}/out" '[c["profile"] for c in d["chosen"]]')" '0:["@work"]' + ak_split "${url}" -- pick claude --only @nobody; status=$? + expect_eq "pick pool: a pool with no account here is exit 1" "${status}" 1 + expect_has "pick pool: ... and the message names the pool" "$(cat "${BOX}/err")" "The pool is @nobody." + ak_split "${url}" AGENTKIT_POOL=@bad/name -- pick claude; status=$? + expect_eq "pick pool: a bad AGENTKIT_POOL is a usage error" "${status}" 2 + # permissions reflects the ask opt-out when the pick itself runs with it — # including the case-normalized form the launch itself accepts, and an # invalid value is a usage error, never a silently wrong mode. diff --git a/tests/scopes/run.sh b/tests/scopes/run.sh index cb92a42..2a968b5 100644 --- a/tests/scopes/run.sh +++ b/tests/scopes/run.sh @@ -217,8 +217,22 @@ run_failover() { ak_split "${base[@]}" -- run claude --pick --exclude @a --exclude @b --cwd "${repo}" --output-format json -- "do it"; status=$? expect_eq "run pick: with every account excluded nothing starts" "${status}:$(json_get "${BOX}/out" 'd["attempts"]')" "3:[]" + # The declared pool. + failover_prime 10 50 + ak_split "${base[@]}" -- run claude --pick --only @b --cwd "${repo}" --output-format json -- "do it"; status=$? + expect_eq "run pool: --only keeps the run inside the pool (@b, not the roomier @a)" "${status}:$(json_get "${BOX}/out" 'd["profile"]')" "0:@b" + ak_split "${base[@]}" AGENTKIT_POOL=@b -- run claude --pick --cwd "${repo}" --output-format json -- "do it"; status=$? + expect_eq "run pool: AGENTKIT_POOL does the same" "${status}:$(json_get "${BOX}/out" 'd["profile"]')" "0:@b" + failover_prime 10 50; failover_routes 10 100 + ak_split "${base[@]}" FAKE_FAIL_FOR=/claude/b -- run claude --pick --only @b --failover 2 --cwd "${repo}" --output-format json -- "do it"; status=$? + expect_eq "run pool: failover never leaves the pool, even for a roomier account" \ + "${status}:$(failover_attempts):$(json_get "${BOX}/out" '[d["failover"]]')" '1:[["@b", 1, "account spent"]]:["no account left"]' + ak_split "${base[@]}" -- run claude --pick --only @nobody --cwd "${repo}" --output-format json -- "do it"; status=$? + expect_eq "run pool: an empty pool is exit 3 before any attempt" "${status}:$(json_get "${BOX}/out" 'd["attempts"]')" "3:[]" + expect_has "run pool: ... naming the pool" "$(json_get "${BOX}/out" 'd["error"]')" "The pool is @nobody." + # Usage errors. - for out in "claude --exclude @a" "claude --pick --exclude a" "claude --pick --exclude @bad/name" "claude @a --pick" "claude --failover 1" "claude --fallback codex" "claude --owner test:lead" \ + for out in "claude --only @a" "claude --pick --only @bad/name" "claude --exclude @a" "claude --pick --exclude a" "claude --pick --exclude @bad/name" "claude @a --pick" "claude --failover 1" "claude --fallback codex" "claude --owner test:lead" \ "claude --pick --failover 4" "claude --pick --failover x" "claude --pick --fallback nope" "claude --pick --owner bad^owner"; do # shellcheck disable=SC2086 # the words of one command line ak_split "${base[@]}" -- run ${out} --cwd "${repo}" --output-format json -- "do it"; status=$? From 28d301e45e4f08031abf12d6514d76c7f720d6b5 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 08:18:13 -0500 Subject: [PATCH 02/11] feat(run,ps): leases are visible in attempts and in ak ps With ak run --pick --owner, each attempt carries lease {owner, released} (null when it could not be taken), and docs/run.md states its lifetime. Each ak ps --json session carries leases [{owner, purpose}] for its account, so a launched agent can be tied to the lead or daemon that leased it. Additive. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/ps.md | 1 + docs/run.md | 1 + docs/schema/fanout-v1.json | 7 ++++++- docs/schema/sessions-v1.json | 15 ++++++++++++++- lib/run.py | 7 ++++++- lib/sessions.py | 15 ++++++++++++++- tests/py/sessions_checks.py | 26 ++++++++++++++++++++++++-- tests/scopes/run.sh | 4 ++++ 9 files changed, 71 insertions(+), 6 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index e47ef21..3baa15d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ permission posture changes. ### Added +- **Leases are visible.** With `ak run --pick --owner`, each entry of `attempts` carries `lease: {owner, released}` (or `null` when the lease could not be taken), and `docs/run.md` states its lifetime. Each `ak ps --json` session carries `leases: [{owner, purpose}]` for its account. Additive. - **A declared account pool.** `--only @a,@b` on `ak pick` (also with `--kinds`), `ak run --pick` and `ak fanout run`, or `AGENTKIT_POOL=@a,@b` when no flag is given, keeps every choice — failover included — inside those profiles. A profile outside the pool is listed as `outside the pool` and never chosen. Additive; without either nothing changes. ### Added diff --git a/docs/ps.md b/docs/ps.md index 043c4d2..7fc01bc 100644 --- a/docs/ps.md +++ b/docs/ps.md @@ -99,6 +99,7 @@ core directly: `py -3 \lib\ak.py ps --json`. | `posture` | `ask` or `auto` | | `herdr_pane` | the Herdr pane id, or `null` | | `capacity` | `null`, or `verdict`, `headroom_pct`, `resets_at` (ISO-8601 UTC or `null`), `age_s` | +| `leases` | the active [`ak lease`](usage.md#leases-ak-lease) records on the session's account: `[{owner, purpose}]`, empty when none — it ties a launched agent to the lead or daemon that leased its account | No key, token or account identity (e-mail, organisation, id) is ever in it. diff --git a/docs/run.md b/docs/run.md index f34e0df..f0e858e 100644 --- a/docs/run.md +++ b/docs/run.md @@ -147,6 +147,7 @@ CLI's own output (its transcript, including its JSON stream) goes to stderr. | `tokens` | present on `--output-format json` runs that started (a run that never started carries `error` instead): the run's **reported** token counts `{input, output, cache_read, cache_write, total}` extracted from the CLI's own JSON per the providers.toml `run.tokens` table (Claude's `usage`, Codex's last `turn.completed`) — a field the CLI does not report stays `null`, never imputed and never summed by ak; a CLI with no `run.tokens` table reports all-null fields. Fields mean what each CLI reports: Codex's `input` **includes** its cached input (`cache_read` is a subset of it), Claude's `input` excludes cache reads and writes, and Claude reports no `total`. Only `--output-format json` envelopes carry `tokens`. Advisory per-account sums of these observed values surface in `ak usage --json` (`advisory`); runs whose counts the CLI did not report are never counted | | `error` | present only when the run never started: the one-line reason | | `attempts` | **only with `--pick`** (additive): one entry per attempt, in order — `kind`, `profile`, `exit`, `cli_exit`, `duration_s`, and `reason`: why the run moved on from it (`not ready`, `account spent`), `null` on the last one. Empty when no account had room. The fields above describe the last attempt | +| `attempts[].lease` | **only with `--pick --owner`**: the lease the attempt held, `{owner, released}` — taken before the CLI started, released when the attempt ended, on every way out (success, failure, timeout, cancellation). `null` when it could not be taken: an exclusive account (Codex) leased to another owner is "not ready" and the run moves on. Two lanes with the same owner never share an exclusive account: the lease store refuses the second | | `failover` | **only with `--pick`** (additive): `null`, or why the run stopped moving: `no account left`, `limit reached` (the `--failover` count is used up) or `cwd changed` (the workspace rule) | A run without `--pick` has neither key: its envelope is exactly what it was. diff --git a/docs/schema/fanout-v1.json b/docs/schema/fanout-v1.json index 944c9a2..9936632 100644 --- a/docs/schema/fanout-v1.json +++ b/docs/schema/fanout-v1.json @@ -55,7 +55,12 @@ "exit": { "type": "integer" }, "cli_exit": { "type": ["integer", "null"] }, "duration_s": { "type": "number" }, - "reason": { "type": ["string", "null"] } + "reason": { "type": ["string", "null"] }, + "lease": { + "type": ["object", "null"], + "description": "The lease the attempt held: its owner and whether it was released at the end; null when it could not be taken.", + "properties": { "owner": { "type": "string" }, "released": { "type": "boolean" } } + } } } }, diff --git a/docs/schema/sessions-v1.json b/docs/schema/sessions-v1.json index f9512a7..93fa25a 100644 --- a/docs/schema/sessions-v1.json +++ b/docs/schema/sessions-v1.json @@ -15,7 +15,7 @@ "items": { "type": "object", "additionalProperties": false, - "required": ["pid", "pid_verified", "mode", "kind", "cli", "provider", "profile", "cwd", "started_at", "posture", "herdr_pane", "capacity"], + "required": ["pid", "pid_verified", "mode", "kind", "cli", "provider", "profile", "cwd", "started_at", "posture", "herdr_pane", "capacity", "leases"], "properties": { "pid": { "type": "integer", "description": "The session's process id: the CLI's own on POSIX (ak replaces itself with it), ak's on Windows (it stays the CLI's parent)." }, "pid_verified": { "type": "boolean", "description": "true when the process's start time was compared with the one recorded at launch; false when this host could not read it, and the entry rests on the process id alone." }, @@ -39,6 +39,19 @@ "resets_at": { "type": ["string", "null"], "description": "When the binding window resets (ISO-8601 UTC)." }, "age_s": { "type": "integer", "minimum": 0, "description": "Age of the cached reading in seconds." } } + }, + "leases": { + "type": "array", + "description": "The active ak leases on this session's account (any owner): who holds it and why; empty when none. A lease ties a launched agent to the lead or daemon that leased its account.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["owner", "purpose"], + "properties": { + "owner": { "type": "string" }, + "purpose": { "type": ["string", "null"] } + } + } } } } diff --git a/lib/run.py b/lib/run.py index 020e10f..e17321a 100644 --- a/lib/run.py +++ b/lib/run.py @@ -696,6 +696,7 @@ def _run_picked(model, opts, env, cwd): before = workspace(cwd, env) if left > 0 else None seen = {"profile": cand["profile"]} held = None + released = None result = {"error": None} try: if opts.owner: @@ -708,11 +709,15 @@ def _run_picked(model, opts, env, cwd): result.update(code=exc.code, cli_exit=None, result_text="", truncated=False, tokens=None, error=str(exc)) finally: if held is not None: - lease.release(env, held, opts.owner, time.time()) + released = lease.release(env, held, opts.owner, time.time()) result.update(kind=kind_name, profile=seen["profile"], duration=time.time() - began) final = result entry = {"kind": kind_name, "profile": seen["profile"], "exit": result["code"], "cli_exit": result["cli_exit"], "duration_s": round(result["duration"], 3), "reason": None} + if opts.owner: + # The lease this attempt held: taken before the CLI started, released when it ended. + # null when it could not be taken (another owner holds an exclusive account). + entry["lease"] = {"owner": opts.owner, "released": bool(released)} if held is not None else None attempts.append(entry) if cancelled or opts.failover == 0: break diff --git a/lib/sessions.py b/lib/sessions.py index eeb34a6..9b68a87 100644 --- a/lib/sessions.py +++ b/lib/sessions.py @@ -295,15 +295,28 @@ def capacity_of(model, env, doc, now): return {"verdict": read["verdict"], "headroom_pct": read["headroom_pct"], "resets_at": read["resets_at"], "age_s": age} +def leases_of(doc, records): + """The active leases on a session's account: [{owner, purpose}].""" + account = state.account_cli(doc["cli"], doc["provider"]) + return [{"owner": r["owner"], "purpose": r.get("purpose")} for r in records + if r["cli"] == account and r["profile"] == doc["profile"]] + + def document(model, env, now, alive=_alive, start=proc_start): import common + import lease import usage + try: + records = lease.active(env, now) + except Exception: # an unreadable lease store hides the leases, never the sessions + records = [] rows = [] for doc, verified in live_sessions(env, alive, start): rows.append({"pid": doc["pid"], "pid_verified": verified, "mode": "interactive", "kind": doc["kind"], "cli": doc["cli"], "provider": doc["provider"], "profile": doc["profile"], "cwd": doc["cwd"], "started_at": usage.iso_utc(doc["started_at"]), "posture": doc["posture"], - "herdr_pane": doc["herdr_pane"], "capacity": capacity_of(model, env, doc, now)}) + "herdr_pane": doc["herdr_pane"], "capacity": capacity_of(model, env, doc, now), + "leases": leases_of(doc, records)}) return {"schema": SCHEMA, "interface": common.INTERFACE, "generated_at": usage.iso_utc(now), "sessions": rows} diff --git a/tests/py/sessions_checks.py b/tests/py/sessions_checks.py index 94fa982..d22a6ef 100644 --- a/tests/py/sessions_checks.py +++ b/tests/py/sessions_checks.py @@ -271,8 +271,8 @@ def reading(cli, profile, used5, used7, status="ok"): == [("codex", "@default"), ("claude", "@work"), ("claude-glm", "@default")], out) check("ps: the output validates against docs/schema/sessions-v1.json", schema_valid(out) == "valid", schema_valid(out)) check("ps: each session carries exactly the documented keys", - all(sorted(r) == ["capacity", "cli", "cwd", "herdr_pane", "kind", "mode", "pid", "pid_verified", "posture", "profile", - "provider", "started_at"] for r in rows), str(rows[:1])) + all(sorted(r) == ["capacity", "cli", "cwd", "herdr_pane", "kind", "leases", "mode", "pid", "pid_verified", "posture", + "profile", "provider", "started_at"] for r in rows), str(rows[:1])) check("ps: pid, mode, posture, pane, provider and the UTC launch time", (rows[0]["pid"], rows[0]["mode"], rows[0]["posture"], rows[0]["herdr_pane"], rows[0]["provider"], rows[0]["started_at"]) == (a.pid, "interactive", "ask", None, None, usage.iso_utc(NOW - 300)) @@ -314,6 +314,28 @@ def reading(cli, profile, used5, used7, status="ok"): check("ps capacity: a bad threshold setting does not hide the sessions", code == 0 and len(json.loads(tolerant)["sessions"]) == 3) check("ps: no key value reaches the output", PLANTED not in out and PLANTED not in ps(())[1]) +import lease as lease_mod # noqa: E402 + +lease_mod.take(PS_ENV, ("claude", "@work", False), "local:w9:p1", 3600, "handoff", NOW + 590, kind="claude") +lease_mod.take(PS_ENV, ("zai", "@default", False), "fanout:run-x", 3600, None, NOW + 590, kind="claude-glm") +lease_mod.take(PS_ENV, ("claude", "@default", False), "someone:else", 3600, "brain", NOW + 590, kind="claude") +_c, leased = ps() +by_kind = dict((r["kind"], r["leases"]) for r in json.loads(leased)["sessions"]) +check("ps leases: a session lists the leases on its account, owner and purpose", + by_kind.get("claude") == [{"owner": "local:w9:p1", "purpose": "handoff"}], str(by_kind)) +check("ps leases: a provider kind's session lists the provider account's leases", + by_kind.get("claude-glm") == [{"owner": "fanout:run-x", "purpose": None}], str(by_kind)) +check("ps leases: a lease on another profile of the same CLI is not this session's", + by_kind.get("codex") == [] and all(l["owner"] != "someone:else" for ls in by_kind.values() for l in ls), str(by_kind)) +check("ps leases: the output still validates", schema_valid(leased) == "valid", schema_valid(leased)) +with open(os.path.join(PS_STATE, "leases", "leases.json"), "w") as handle: + handle.write("{ damaged") +code, broken = ps() +check("ps leases: an unreadable lease store hides the leases, never the sessions", + code == 0 and len(json.loads(broken)["sessions"]) == 3 and all(r["leases"] == [] for r in json.loads(broken)["sessions"]), + broken[:200]) +os.remove(os.path.join(PS_STATE, "leases", "leases.json")) + unverified = json.loads(json.dumps(sessions.document(MODEL, PS_ENV, NOW + 600, start=lambda pid: None))) check("ps: where the start time cannot be read the session is listed as unverified", len(unverified["sessions"]) == 3 and not any(r["pid_verified"] for r in unverified["sessions"]), str(unverified)) diff --git a/tests/scopes/run.sh b/tests/scopes/run.sh index 2a968b5..d5deef4 100644 --- a/tests/scopes/run.sh +++ b/tests/scopes/run.sh @@ -190,6 +190,10 @@ run_failover() { expect_has "run owner: while the attempt runs the account is leased to the owner" "${lease_seen}" "claude @a test:lead" expect_has "run owner: ... with its purpose" "${lease_seen}" "ak run" expect_eq "run owner: the lease is released when the run ends" "$(ak -- lease ls)" "no active lease" + expect_eq "run owner: the attempt says which lease it held and that it was released" \ + "$(json_get "${BOX}/out" '[a["lease"] for a in d["attempts"]]')" '[{"owner": "test:lead", "released": true}]' + ak_split "${base[@]}" -- run claude --pick --cwd "${repo}" --output-format json -- "do it" + expect_eq "run owner: without --owner an attempt has no lease key" "$(json_get "${BOX}/out" '["lease" in a for a in d["attempts"]]')" '[false]' ak_split "${base[@]}" FAKE_SLEEP=5 -- run claude --pick --owner test:lead --timeout 1 --cwd "${repo}" --output-format json -- "do it" expect_eq "run owner: ... also after a timeout" "$(ak -- lease ls)" "no active lease" failover_prime 10 50; failover_routes 100 50 From df28664737eb490be6209e2d23699b69319074bb Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 08:35:59 -0500 Subject: [PATCH 03/11] feat(ps): thresholds, the Herdr server, and headless runs with --all ak ps --json states the thresholds every verdict was judged by (null when the settings are invalid) and, per session, herdr_server: an opaque id of the Herdr server, since pane ids are unique per server, not per host. A headless ak run now keeps a record while it runs (rewritten when it moves to another account, removed when it ends); ak ps --all lists those with mode run, run_id for ak fanout lanes and owner. ak ps without --all lists what it did before. The fan-out marker variable never reaches the CLI. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/ps.md | 23 +++++-- docs/schema/sessions-v1.json | 16 ++++- lib/ak.py | 4 +- lib/fanout.py | 3 +- lib/run.py | 19 ++++++ lib/sessions.py | 124 +++++++++++++++++++++++++++++------ skills/agentkit/SKILL.md | 2 +- tests/py/sessions_checks.py | 74 +++++++++++++++++++-- tests/scopes/fanout.sh | 18 +++++ tests/scopes/sessions.sh | 28 +++++++- 11 files changed, 273 insertions(+), 39 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 3baa15d..01df4fa 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ permission posture changes. ### Added +- **`ak ps` shows more.** `--json` carries the effective `thresholds` `{low, critical}` and, per session, `herdr_server` (an opaque id: pane ids are unique per Herdr server, not per host). `ak ps --all` also lists running headless `ak run` processes (`mode` `run`, with `run_id` for fan-out lanes and `owner`). `ak ps` without `--all` lists what it listed before. Additive. - **Leases are visible.** With `ak run --pick --owner`, each entry of `attempts` carries `lease: {owner, released}` (or `null` when the lease could not be taken), and `docs/run.md` states its lifetime. Each `ak ps --json` session carries `leases: [{owner, purpose}]` for its account. Additive. - **A declared account pool.** `--only @a,@b` on `ak pick` (also with `--kinds`), `ak run --pick` and `ak fanout run`, or `AGENTKIT_POOL=@a,@b` when no flag is given, keeps every choice — failover included — inside those profiles. A profile outside the pool is listed as `outside the pool` and never chosen. Additive; without either nothing changes. diff --git a/docs/ps.md b/docs/ps.md index 7fc01bc..23a5c90 100644 --- a/docs/ps.md +++ b/docs/ps.md @@ -1,7 +1,7 @@ # `ak ps` — the sessions that are running ``` -ak ps [--json] +ak ps [--all] [--json] ``` Lists the agent sessions `ak` launched on this machine that are still @@ -43,8 +43,10 @@ alone: `pid_verified` is `false`, and the table shows a `?` after the id. else tracks sessions — there is no daemon and no exit hook. When records pile up because nobody ran `ak ps`, a later launch clears the ended ones. -Of several live sessions that name the same Herdr pane, only the newest is -listed. +Of several live sessions that name the same Herdr pane of the same Herdr +server, only the newest is listed. `herdr_server` is an opaque id of that +server (two servers on one host can give out the same pane ids); its socket +path is never recorded. A record belongs to the host that wrote it. When the state directory is shared between a machine and its containers, each side lists, ends and @@ -55,7 +57,11 @@ boundary. - **An agent started without `ak`** (a bare `claude`, an IDE) has no record. Read a missing session as *unknown*, never as "no account". -- **Headless `ak run` processes.** +- **Headless `ak run` processes**, unless you pass `--all`: then every + running `ak run` is listed too, `mode` `run`, with `run_id` (the `ak fanout` + run it is a lane of) and `owner` (its `--owner`). A run's record is written + when its attempt starts, rewritten when it moves to another account, and + removed when it ends. - **What changed inside the CLI.** `posture` is what `ak` launched with (`auto`: the CLI's autonomy flag; `ask`: the opt-out), not a mode switched later in the CLI. @@ -88,10 +94,15 @@ core directly: `py -3 \lib\ak.py ps --json`. "capacity": {"verdict": "ok", "headroom_pct": 62, "resets_at": "2026-12-01T14:00:00Z", "age_s": 180}}]} ``` +Top level: `schema`, `interface`, `generated_at`, `thresholds` (the +`{low, critical}` every verdict was judged by — `AGENTKIT_CAPACITY_LOW` and +`_CRITICAL`, or 25 and 10; `null` when those settings are invalid) and +`sessions`. Per session: + | Key | Meaning | | --- | --- | | `pid`, `pid_verified` | the session's process id; whether its start time was compared | -| `mode` | `interactive` — the only value in this version | +| `mode` | `interactive`, or `run` for a headless `ak run` (only with `--all`) | | `kind`, `cli`, `provider` | what was launched; `provider` is `null` for the CLI's own login | | `profile` | `@default` or `@name` | | `cwd` | the launch directory (the schema's one path) | @@ -99,6 +110,8 @@ core directly: `py -3 \lib\ak.py ps --json`. | `posture` | `ask` or `auto` | | `herdr_pane` | the Herdr pane id, or `null` | | `capacity` | `null`, or `verdict`, `headroom_pct`, `resets_at` (ISO-8601 UTC or `null`), `age_s` | +| `herdr_server` | an opaque id of the Herdr server, or `null` | +| `run_id`, `owner` | `mode` `run` only (`--all`): the fan-out run and the lease owner, each or `null` | | `leases` | the active [`ak lease`](usage.md#leases-ak-lease) records on the session's account: `[{owner, purpose}]`, empty when none — it ties a launched agent to the lead or daemon that leased its account | No key, token or account identity (e-mail, organisation, id) is ever in it. diff --git a/docs/schema/sessions-v1.json b/docs/schema/sessions-v1.json index 93fa25a..8bad87b 100644 --- a/docs/schema/sessions-v1.json +++ b/docs/schema/sessions-v1.json @@ -5,21 +5,28 @@ "description": "The agent sessions ak launched on this machine that are still running, oldest first, each joined to its account's capacity. A session is listed while the process ak launched is alive with the start time recorded at launch; of several live sessions naming one Herdr pane only the newest is listed. A session started without ak has no entry: read a missing entry as unknown, never as no account. Headless ak run processes are not listed. Read-only: capacity comes from the kit's usage cache alone, no vendor is queried and no login is refreshed. Never contains a secret value or an account identity (e-mail, organisation, id); `cwd` is the only path. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions.", "type": "object", "additionalProperties": false, - "required": ["schema", "interface", "generated_at", "sessions"], + "required": ["schema", "interface", "generated_at", "thresholds", "sessions"], "properties": { "schema": { "const": "sessions-v1" }, "interface": { "const": 1 }, "generated_at": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" }, + "thresholds": { + "description": "The thresholds every capacity verdict here was judged by, as ak capacity applies them (AGENTKIT_CAPACITY_LOW / _CRITICAL or the defaults 25 and 10); null when those settings are invalid.", + "type": ["object", "null"], + "additionalProperties": false, + "required": ["low", "critical"], + "properties": { "low": { "type": "number" }, "critical": { "type": "number" } } + }, "sessions": { "type": "array", "items": { "type": "object", "additionalProperties": false, - "required": ["pid", "pid_verified", "mode", "kind", "cli", "provider", "profile", "cwd", "started_at", "posture", "herdr_pane", "capacity", "leases"], + "required": ["pid", "pid_verified", "mode", "kind", "cli", "provider", "profile", "cwd", "started_at", "posture", "herdr_pane", "herdr_server", "capacity", "leases"], "properties": { "pid": { "type": "integer", "description": "The session's process id: the CLI's own on POSIX (ak replaces itself with it), ak's on Windows (it stays the CLI's parent)." }, "pid_verified": { "type": "boolean", "description": "true when the process's start time was compared with the one recorded at launch; false when this host could not read it, and the entry rests on the process id alone." }, - "mode": { "enum": ["interactive"], "description": "How the session was started. Only interactive launches are listed in this version; other values may be added." }, + "mode": { "enum": ["interactive", "run"], "description": "interactive: an ak launch. run: a headless ak run process (a fan-out lane among them), listed only by ak ps --all. Further values may be added in a later minor version." }, "kind": { "type": "string", "description": "The ak kind that was launched (claude, codex-glm, ...)." }, "cli": { "type": "string", "description": "The CLI behind the kind." }, "provider": { "type": ["string", "null"], "description": "The provider of a provider kind (zai, azure, xai, ...); null for the CLI's own login. A provider kind draws on the provider key's quota, not the CLI subscription's." }, @@ -28,6 +35,9 @@ "started_at": { "type": "string", "pattern": "^[0-9]{4}-[0-9]{2}-[0-9]{2}T[0-9]{2}:[0-9]{2}:[0-9]{2}Z$" }, "posture": { "enum": ["ask", "auto"], "description": "The permission posture ak launched with: auto (the CLI's autonomy flag) or ask (the opt-out). Not what was changed inside the CLI afterwards." }, "herdr_pane": { "type": ["string", "null"], "description": "The Herdr pane id the session was launched in (HERDR_PANE_ID with HERDR_ENV=1), or null." }, + "herdr_server": { "type": ["string", "null"], "pattern": "^herdr-[0-9a-f]{12}$", "description": "An opaque id of the Herdr server the session runs under (derived from its socket path, which is never shown): pane ids are unique per server, not per host. null outside Herdr." }, + "run_id": { "type": ["string", "null"], "description": "mode run only: the ak fanout run this process is a lane of, or null." }, + "owner": { "type": ["string", "null"], "description": "mode run only: the lease owner the run was started with (--owner), or null." }, "capacity": { "description": "The account's capacity from the kit's usage cache, by ak capacity's rule; null when no reading of the last day is cached. A cached reading can be old: judge it by age_s.", "type": ["object", "null"], diff --git a/lib/ak.py b/lib/ak.py index 0a284f1..262a3ed 100644 --- a/lib/ak.py +++ b/lib/ak.py @@ -16,7 +16,7 @@ ak install […] [--all] ak update […] [--version VERSION] [--take-over] [--json] ak last [-c | -r] | ak last ls - ak ps [--json] + ak ps [--all] [--json] ak --skill [setup | orchestrate] | --version | --help """ @@ -46,7 +46,7 @@ ak install […] [--all] ak update […] [--version VERSION] [--take-over] [--json] ak last [-c | -r] | ak last ls (back to the last ak launch in this directory) - ak ps [--json] (the sessions ak launched that are still running, with their account's capacity) + ak ps [--all] [--json] (the sessions ak launched that are still running, with their account's capacity) ak --skill [setup | orchestrate] | --version | --help Kinds: {kinds} diff --git a/lib/fanout.py b/lib/fanout.py index 5d75ed8..d68c259 100644 --- a/lib/fanout.py +++ b/lib/fanout.py @@ -354,7 +354,8 @@ def attempt(run, lane, moves_left=None): before = _leases(run) fd = os.open(lane["log"], os.O_WRONLY | os.O_CREAT | os.O_APPEND, 0o600) try: - proc = subprocess.Popen(run_argv(run, lane, moves_left), cwd=lane["worktree"], env=run.env, stdin=subprocess.DEVNULL, + lane_env = dict(run.env, AGENTKIT_FANOUT_RUN=run.run_id) # names the run in ak ps --all; ak run drops it + proc = subprocess.Popen(run_argv(run, lane, moves_left), cwd=lane["worktree"], env=lane_env, stdin=subprocess.DEVNULL, stdout=subprocess.PIPE, stderr=fd, **popen) finally: os.close(fd) diff --git a/lib/run.py b/lib/run.py index e17321a..fa1a265 100644 --- a/lib/run.py +++ b/lib/run.py @@ -76,6 +76,8 @@ def __init__(self): self.owner = None # --owner ADDR: hold a lease on the account while an attempt runs self.exclude = [] # --exclude @profile: an account the choice leaves out (repeatable) self.only = None # --only @a,@b: the pool the choice keeps to (else AGENTKIT_POOL) + self.run_id = None # the fan-out run this is a lane of (AGENTKIT_FANOUT_RUN), for ak ps --all + self.record = None # this process's session record, removed when the run ends def parse(args, env): @@ -532,6 +534,9 @@ def _attempt(model, opts, env, cwd, kind_name, profile_token, seen): argv = build_argv(prep, opts, cwd) if prep.kind.data.get("pre"): launch.run_pre(prep) + import sessions + path = sessions.record_run(env, prep.kind, prep.profile, prep.auto, cwd, opts.run_id, opts.owner) + opts.record = path or opts.record code, cli_exit, stdout_text, overflow = execute(prep, argv, opts, cwd) result_text, reported_error = "", False if fmt == "json": @@ -746,6 +751,18 @@ def _run_picked(model, opts, env, cwd): def main(model, args, env): + import sessions + env = dict(env) + run_id = env.pop(sessions.FANOUT_RUN_VAR, None) # bookkeeping for ak ps; never reaches the CLI + holder = {} + try: + return _main(model, args, env, run_id, holder) + finally: + if holder.get("opts") is not None: + sessions.forget(holder["opts"].record) + + +def _main(model, args, env, run_id, holder): start = time.time() fmt = _early_format(args) opts = None @@ -754,6 +771,8 @@ def main(model, args, env): cwd = None try: opts = parse(args, env) + opts.run_id = run_id + holder["opts"] = opts fmt = opts.fmt opts.kind = model.canonical(opts.kind) if opts.kind not in model.kinds: diff --git a/lib/sessions.py b/lib/sessions.py index 9b68a87..a9e998b 100644 --- a/lib/sessions.py +++ b/lib/sessions.py @@ -26,6 +26,7 @@ be read the record lives on the id alone and says so (`verified` False). """ +import hashlib import os import re import socket @@ -39,6 +40,10 @@ DIRECTORY = "sessions" PANE = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:._-]{0,63}$") POSTURES = ("ask", "auto") +MODES = ("interactive", "run") +RUN_ID = re.compile(r"^[0-9]{8}-[0-9]{6}-[0-9a-f]{4}$") +OWNER = re.compile(r"^[A-Za-z0-9][A-Za-z0-9:._@/-]{0,79}$") +FANOUT_RUN_VAR = "AGENTKIT_FANOUT_RUN" # set by ak fanout for its lanes; ak run takes it out before the CLI PS_TIMEOUT = 2.0 @@ -120,24 +125,61 @@ def pane_of(env): return pane if env.get("HERDR_ENV") == "1" and PANE.match(pane) else None +def server_of(env): + """An opaque id of the Herdr server this launch runs under: two servers on + one host can give out the same pane ids. Derived from the socket path, + which itself is never recorded or shown.""" + sock = env.get("HERDR_SOCKET_PATH") or "" + if env.get("HERDR_ENV") != "1" or not sock: + return None + return "herdr-" + hashlib.sha256(os.path.realpath(sock).encode("utf-8", "replace")).hexdigest()[:12] + + +def _doc(env, kind, profile_name, auto, now, pid, start, cwd=None, mode="interactive", run_id=None, owner=None): + doc = {"schema": RECORD_SCHEMA, "host": host(), "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(cwd or os.getcwd()), "started_at": int(now), "posture": "auto" if auto else "ask", + "herdr_pane": pane_of(env), "herdr_server": server_of(env), "mode": mode} + if mode == "run": + doc["run_id"] = run_id if isinstance(run_id, str) and RUN_ID.match(run_id) else None + doc["owner"] = owner if isinstance(owner, str) and OWNER.match(owner) else None + return doc + + 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, "host": host(), "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) + state.write_json(path, _doc(env, kind, profile_name, auto, now, pid, start)) sweep(env) return path except Exception: # best effort by contract: nothing here may stop or change a launch return None +def record_run(env, kind, profile_name, auto, cwd, run_id=None, owner=None, now=None, pid=None, start=proc_start): + """Leave (or replace) the record of a headless `ak run` attempt: one file + per run process, rewritten when the run moves to another account. The + caller removes it with forget() when the run ends. Never raises.""" + try: + pid = os.getpid() if pid is None else pid + now = time.time() if now is None else now + path = os.path.join(directory(env), "run-%d.json" % pid) + state.write_json(path, _doc(env, kind, profile_name, auto, now, pid, start, cwd, "run", run_id, owner)) + return path + except Exception: # best effort: a run never depends on it + return None + + +def forget(path): + """Remove a record this process wrote (best effort).""" + if path: + _remove(path) + + # ------------------------------------------------------------------- read def _text(value, limit=4096): @@ -161,6 +203,15 @@ def valid(doc): return False if doc.get("provider") is not None and not _text(doc["provider"], 128): return False + if doc.get("mode", "interactive") not in MODES: + return False + if doc.get("herdr_server") is not None and not (isinstance(doc["herdr_server"], str) + and re.match(r"^herdr-[0-9a-f]{12}$", doc["herdr_server"])): + return False + if doc.get("run_id") is not None and not (isinstance(doc["run_id"], str) and RUN_ID.match(doc["run_id"])): + return False + if doc.get("owner") is not None and not (isinstance(doc["owner"], str) and OWNER.match(doc["owner"])): + return False return doc.get("herdr_pane") is None or (isinstance(doc["herdr_pane"], str) and bool(PANE.match(doc["herdr_pane"]))) @@ -233,18 +284,19 @@ def _remove(path): SCHEMA = "sessions-v1" CAPACITY_MAX_AGE = state.MAX_MAX_AGE # the oldest cached reading any command accepts (one day) -USAGE = """usage: ak ps [--json] +USAGE = """usage: ak ps [--all] [--json] The agent sessions ak launched that are still running, oldest first: kind, profile, posture (ask or auto), the Herdr pane and the account's capacity. Read-only: capacity comes from the kit's usage cache alone (its age is shown), no vendor is queried and no login is touched. A session started -without ak has no row; headless `ak run` processes are not listed. +without ak has no row. + --all also the headless `ak run` processes (fan-out lanes included) --json exactly one JSON object, schema sessions-v1 Exit: 0 (also with no session) · 2 usage """ -def live_sessions(env, alive=_alive, start=proc_start): +def live_sessions(env, alive=_alive, start=proc_start, runs=False): """[(record, verified)] of the sessions still running, oldest first; the files of ended records are removed. Of several live records naming one Herdr pane only the newest is kept (the others stay on disk: their @@ -257,19 +309,29 @@ def live_sessions(env, alive=_alive, start=proc_start): if doc["host"] != here: # another host's or container's process ids: not ours to judge or remove continue live, verified = liveness(doc, alive, start) + if live and doc.get("mode", "interactive") == "run" and not runs: + continue # a live headless run: listed with --all only if not live: _remove(path) continue kept.append((doc, verified)) newest = {} for doc, _v in kept: - pane = doc["herdr_pane"] + pane = _pane_key(doc) if pane is not None and (pane not in newest or _order(doc) > _order(newest[pane])): newest[pane] = doc - kept = [(doc, v) for doc, v in kept if doc["herdr_pane"] is None or newest[doc["herdr_pane"]] is doc] + kept = [(doc, v) for doc, v in kept if _pane_key(doc) is None or newest[_pane_key(doc)] is doc] return sorted(kept, key=lambda item: _order(item[0])) +def _pane_key(doc): + """The pane an interactive session occupies, per Herdr server; None for a + headless run or outside Herdr.""" + if doc.get("mode", "interactive") != "interactive" or doc["herdr_pane"] is None: + return None + return (doc.get("herdr_server"), doc["herdr_pane"]) + + def _order(doc): return (doc["started_at"], doc["pid"]) @@ -302,7 +364,18 @@ def leases_of(doc, records): if r["cli"] == account and r["profile"] == doc["profile"]] -def document(model, env, now, alive=_alive, start=proc_start): +def effective_thresholds(env): + """{low, critical} as ak capacity applies them, or None when the + settings are invalid (ak capacity refuses them; ak ps never guesses).""" + import pick + try: + low, critical = pick.thresholds(env) + except Exception: + return None + return {"low": low, "critical": critical} + + +def document(model, env, now, alive=_alive, start=proc_start, runs=False): import common import lease import usage @@ -311,13 +384,19 @@ def document(model, env, now, alive=_alive, start=proc_start): except Exception: # an unreadable lease store hides the leases, never the sessions records = [] rows = [] - for doc, verified in live_sessions(env, alive, start): - rows.append({"pid": doc["pid"], "pid_verified": verified, "mode": "interactive", "kind": doc["kind"], - "cli": doc["cli"], "provider": doc["provider"], "profile": doc["profile"], "cwd": doc["cwd"], - "started_at": usage.iso_utc(doc["started_at"]), "posture": doc["posture"], - "herdr_pane": doc["herdr_pane"], "capacity": capacity_of(model, env, doc, now), - "leases": leases_of(doc, records)}) - return {"schema": SCHEMA, "interface": common.INTERFACE, "generated_at": usage.iso_utc(now), "sessions": rows} + for doc, verified in live_sessions(env, alive, start, runs): + mode = doc.get("mode", "interactive") + row = {"pid": doc["pid"], "pid_verified": verified, "mode": mode, "kind": doc["kind"], + "cli": doc["cli"], "provider": doc["provider"], "profile": doc["profile"], "cwd": doc["cwd"], + "started_at": usage.iso_utc(doc["started_at"]), "posture": doc["posture"], + "herdr_pane": doc["herdr_pane"], "herdr_server": doc.get("herdr_server"), + "capacity": capacity_of(model, env, doc, now), "leases": leases_of(doc, records)} + if mode == "run": + row["run_id"] = doc.get("run_id") + row["owner"] = doc.get("owner") + rows.append(row) + return {"schema": SCHEMA, "interface": common.INTERFACE, "generated_at": usage.iso_utc(now), + "thresholds": effective_thresholds(env), "sessions": rows} def _span(seconds): @@ -346,8 +425,9 @@ def render_table(doc, now, home=None): cwd = row["cwd"] if home and (cwd == home or cwd.startswith(home.rstrip(os.sep) + os.sep)): cwd = "~" + cwd[len(home.rstrip(os.sep)):] + where = row["herdr_pane"] or ("run " + (row.get("run_id") or "-") if row["mode"] == "run" else "-") lines.append((str(row["pid"]) + ("" if row["pid_verified"] else "?"), row["kind"], row["profile"], row["posture"], - row["herdr_pane"] or "-", room, _span(now - usage.epoch_of(row["started_at"])), cwd)) + where, room, _span(now - usage.epoch_of(row["started_at"])), cwd)) widths = [max(len(line[i]) for line in lines) for i in range(len(lines[0]) - 1)] out = [" ".join([cell.ljust(width) for cell, width in zip(line, widths)] + [line[-1]]).rstrip() for line in lines] return "\n".join(out) + "\n" @@ -359,17 +439,19 @@ def main(model, args, env, now=None, stdout=None): import usage from common import AkError, EXIT_USAGE stdout = stdout or sys.stdout - as_json = False + as_json = runs = False for arg in args: if arg in ("-h", "--help"): usage.emit(stdout, USAGE) return 0 if arg == "--json": as_json = True + elif arg == "--all": + runs = True else: raise AkError("unknown argument '%s'. %s" % (arg, USAGE.splitlines()[0]), EXIT_USAGE) now = time.time() if now is None else now - doc = document(model, env, now) + doc = document(model, env, now, runs=runs) if as_json: usage.emit(stdout, json.dumps(doc, indent=2, sort_keys=True) + "\n") else: diff --git a/skills/agentkit/SKILL.md b/skills/agentkit/SKILL.md index d2bf642..7482f19 100644 --- a/skills/agentkit/SKILL.md +++ b/skills/agentkit/SKILL.md @@ -74,7 +74,7 @@ ak claude -- @src/app.ts # after --, everything goes to the CLI untouched Grammar: `ak [@profile] [--ask | --auto] [--trust-cwd] [-c | --continue | -r [id] | --resume [id] | -l] [--] [cli args…]`. Only a first `@name` is a profile; `@default` is the CLI's own home. Inside a Herdr pane, a launch makes Herdr restore it as `ak @ --resume ` after a restart (`AGENTKIT_HERDR_RESUME=0` turns it off). In any terminal, `ak last` relaunches the last `ak @` of this directory with `-c` (`ak last -r`: picker; `ak last ls`: the record). -`ak ps [--json]` lists the sessions `ak` launched that are still running (kind, profile, posture, Herdr pane, and the account's capacity from the usage cache with its age; schema `sessions-v1`). It queries no vendor. An agent started without `ak` has no row: read a missing row as unknown. +`ak ps [--json]` lists the sessions `ak` launched that are still running (kind, profile, posture, Herdr pane, and the account's capacity from the usage cache with its age; schema `sessions-v1`). It queries no vendor. `--all` also lists headless `ak run` processes (`ak fanout` lanes included). An agent started without `ak` has no row: read a missing row as unknown. ## Headless runs that choose their account diff --git a/tests/py/sessions_checks.py b/tests/py/sessions_checks.py index d22a6ef..2bdcbbd 100644 --- a/tests/py/sessions_checks.py +++ b/tests/py/sessions_checks.py @@ -61,8 +61,8 @@ def doc_of(path): path = sessions.record(env_for(), MODEL.kind("claude"), "work", True, now=NOW) doc = doc_of(path) if path else {} -KEYS = ["cli", "cwd", "herdr_pane", "host", "kind", "pid", "posture", "proc_start", "profile", "provider", "schema", - "started_at"] +KEYS = ["cli", "cwd", "herdr_pane", "herdr_server", "host", "kind", "mode", "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))) @@ -271,8 +271,8 @@ def reading(cli, profile, used5, used7, status="ok"): == [("codex", "@default"), ("claude", "@work"), ("claude-glm", "@default")], out) check("ps: the output validates against docs/schema/sessions-v1.json", schema_valid(out) == "valid", schema_valid(out)) check("ps: each session carries exactly the documented keys", - all(sorted(r) == ["capacity", "cli", "cwd", "herdr_pane", "kind", "leases", "mode", "pid", "pid_verified", "posture", - "profile", "provider", "started_at"] for r in rows), str(rows[:1])) + all(sorted(r) == ["capacity", "cli", "cwd", "herdr_pane", "herdr_server", "kind", "leases", "mode", "pid", "pid_verified", + "posture", "profile", "provider", "started_at"] for r in rows), str(rows[:1])) check("ps: pid, mode, posture, pane, provider and the UTC launch time", (rows[0]["pid"], rows[0]["mode"], rows[0]["posture"], rows[0]["herdr_pane"], rows[0]["provider"], rows[0]["started_at"]) == (a.pid, "interactive", "ask", None, None, usage.iso_utc(NOW - 300)) @@ -350,7 +350,7 @@ def reading(cli, profile, used5, used7, status="ok"): check("ps table: a session without a cached reading shows a dash, never a guess", any(str(a.pid) in line and " ask " in line and " - " in line for line in lines), table) check("ps: an unknown argument is a usage error (exit 2)", ps(("--bogus",))[0] == common.EXIT_USAGE) -check("ps: --help prints the grammar and exits 0", ps(("--help",))[0] == 0 and "ak ps [--json]" in ps(("--help",))[1]) +check("ps: --help prints the grammar and exits 0", ps(("--help",))[0] == 0 and "ak ps [--all] [--json]" in ps(("--help",))[1]) for proc in (a, b, c): proc.stdin.close() @@ -391,5 +391,69 @@ def reading(cli, profile, used5, used7, status="ok"): check("sessions sweep: it never removes another host's records", len([n for n in os.listdir(os.path.join(SW_STATE, "sessions")) if n.endswith("-far.json")]) == sessions.SWEEP_AT + 1) + +# ------------------------------------------------- thresholds, server, headless runs + +TH_STATE = os.path.join(TMP, "th-state") +TH_ENV = env_for({"AGENTKIT_STATE_DIR": TH_STATE}) +check("ps thresholds: the defaults are stated (25, 10)", sessions.document(MODEL, TH_ENV, NOW)["thresholds"] == {"low": 25, "critical": 10}) +check("ps thresholds: AGENTKIT_CAPACITY_LOW / _CRITICAL are what is stated", + sessions.document(MODEL, dict(TH_ENV, AGENTKIT_CAPACITY_LOW="40", AGENTKIT_CAPACITY_CRITICAL="15"), NOW)["thresholds"] + == {"low": 40, "critical": 15}) +check("ps thresholds: invalid settings are null, never a guess", + sessions.document(MODEL, dict(TH_ENV, AGENTKIT_CAPACITY_LOW="lots"), NOW)["thresholds"] is None) + +sock = os.path.join(TMP, "herdr.sock") +in_herdr = {"HERDR_ENV": "1", "HERDR_PANE_ID": "w1:p1", "HERDR_SOCKET_PATH": sock} +server = sessions.server_of(in_herdr) +check("ps server: inside Herdr the server id is opaque, stable, and never the socket path", + bool(server) and server.startswith("herdr-") and server == sessions.server_of(dict(in_herdr)) and sock not in server + and "herdr.sock" not in server, str(server)) +check("ps server: another socket is another server; outside Herdr there is none", + sessions.server_of(dict(in_herdr, HERDR_SOCKET_PATH=sock + "2")) != server and sessions.server_of({"HERDR_SOCKET_PATH": sock}) is None) +a1, a2 = sleeper(), sleeper() +plant_dir = os.path.join(TH_STATE, "sessions") +os.makedirs(plant_dir, exist_ok=True) +for name, proc, srv, at in (("1-one", a1, "herdr-aaaaaaaaaaaa", 100), ("2-two", a2, "herdr-bbbbbbbbbbbb", 200)): + state.write_json(os.path.join(plant_dir, name + ".json"), + {"schema": sessions.RECORD_SCHEMA, "host": sessions.host(), "pid": proc.pid, "proc_start": sessions.proc_start(proc.pid), + "kind": "claude", "cli": "claude", "provider": None, "profile": "@work", "cwd": TMP, "started_at": int(NOW) - at, + "posture": "auto", "herdr_pane": "w1:p1", "herdr_server": srv, "mode": "interactive"}) +listed = sessions.document(MODEL, TH_ENV, NOW)["sessions"] +check("ps server: the same pane id under two Herdr servers is two sessions, not one", + sorted(r["herdr_server"] for r in listed) == ["herdr-aaaaaaaaaaaa", "herdr-bbbbbbbbbbbb"], str(listed)) +blob = open(os.path.join(plant_dir, "1-one.json")).read() +rec = doc_of(sessions.record(dict(TH_ENV, **in_herdr), MODEL.kind("claude"), "work", True, now=NOW)) +check("ps server: a launch records the server id, never the socket path", + rec["herdr_server"] == server and sock not in json.dumps(rec), str(rec)) + +run_path = sessions.record_run(TH_ENV, MODEL.kind("codex"), "work", False, TMP, run_id="20260101-000000-abcd", + owner="fanout:20260101-000000-abcd", now=NOW + 5) +runs = sessions.document(MODEL, TH_ENV, NOW + 10, runs=True)["sessions"] +mine = [r for r in runs if r["mode"] == "run"] +check("ps --all: a headless run is listed with mode run, its fan-out run id and owner", + [(r["pid"], r["kind"], r["profile"], r["posture"], r["run_id"], r["owner"]) for r in mine] + == [(os.getpid(), "codex", "@work", "ask", "20260101-000000-abcd", "fanout:20260101-000000-abcd")], str(mine)) +check("ps: without --all a headless run is not listed", + not [r for r in sessions.document(MODEL, TH_ENV, NOW + 10)["sessions"] if r["mode"] == "run"]) +check("ps --all: an interactive session carries no run_id or owner key", + all("run_id" not in r and "owner" not in r for r in runs if r["mode"] == "interactive")) +again = sessions.record_run(TH_ENV, MODEL.kind("claude"), "b", False, TMP, now=NOW + 20) +mine = [r for r in sessions.document(MODEL, TH_ENV, NOW + 30, runs=True)["sessions"] if r["mode"] == "run"] +check("ps --all: a run that moves to another account rewrites its one record", + again == run_path and [(r["kind"], r["profile"], r["run_id"], r["owner"]) for r in mine] == [("claude", "@b", None, None)], str(mine)) +sessions.forget(run_path) +check("ps --all: forget() removes it", not os.path.exists(run_path)) +bad = sessions.record_run(TH_ENV, MODEL.kind("codex"), "w", False, TMP, run_id="../../x", owner="bad owner!", now=NOW) +check("ps --all: a run id or owner of the wrong form is recorded as null", doc_of(bad)["run_id"] is None and doc_of(bad)["owner"] is None) +sessions.forget(bad) +out = json.dumps(sessions.document(MODEL, TH_ENV, NOW + 30, runs=True)) +check("ps --all: the document validates against the schema", schema_valid(out) == "valid", schema_valid(out)) +check("ps --all: --all parses, an unknown argument still does not", + ps(("--all", "--json"), env=TH_ENV)[0] == 0 and ps(("--everything",), env=TH_ENV)[0] == 2) +for proc in (a1, a2): + proc.stdin.close() + proc.wait() + if FAILS: sys.exit(1) diff --git a/tests/scopes/fanout.sh b/tests/scopes/fanout.sh index 037f07b..0a78e4a 100644 --- a/tests/scopes/fanout.sh +++ b/tests/scopes/fanout.sh @@ -107,6 +107,8 @@ scope_fanout() { expect_eq "fanout: it never merges or moves the repository: same branch, same commit, clean" \ "$(fanout_git "${FAN_REPO}" rev-parse HEAD):$(fanout_git "${FAN_REPO}" status --porcelain | wc -l | tr -d ' ')" "${FAN_BASE}:0" expect_eq "fanout: every lease is released" "$(ak -- lease ls)" "no active lease" + expect_eq "fanout: the lanes' ak ps records are gone once they end" \ + "$(find "${BOX}/home/.local/state/agentkit/sessions" -name 'run-*.json' 2>/dev/null | wc -l | tr -d ' ')" 0 record="${BOX}/home/.local/state/agentkit/fanout/${run}/run.json" expect_eq "fanout record: 0600, finished, both lanes created with their paths" \ "$(file_mode "${record}"):$(json_get "${record}" '[d["status"], d["repo"] == d["repo"], [[l["id"], l["created"], l["exit"]] for l in d["lanes"]]]')" \ @@ -144,6 +146,22 @@ scope_fanout() { "$(json_get "${BOX}/fan2.json" 'd["lanes"][1]["worktree"]')" "${BOX}/trees/${run}/docs" check "fanout: ... starting from the base, not from the newer HEAD" bash -c '[[ ! -e "$1/second.txt" ]]' _ "${BOX}/trees/${run}/docs" + # --- ak ps --all sees the lanes of a run ------------------------------------------ + local lanes_seen fanpid + fanout_tasks "${tasks}" claude seen + ( cd "${FAN_REPO}" && exec env -i HOME="${BOX}/home" PATH="${BOX}/bin:${BASE_PATH}" TMPDIR="${BOX}/tmp" AGENTKIT_KEYCHAIN=off \ + AGENTKIT_PERMISSIONS=ask "${FAN_URLS[@]}" FAKE_MODE=headless FAKE_SLEEP=4 \ + bash "${ROOT}/bin/ak" fanout run --tasks "${tasks}" --json >"${BOX}/seen.json" 2>/dev/null ) & + fanpid=$!; lanes_seen=""; tries=0 + while [[ ${tries} -lt 60 && -z "${lanes_seen}" ]]; do + ak_split -- ps --all --json + lanes_seen="$(json_get "${BOX}/out" '[s["run_id"] for s in d["sessions"] if s["mode"] == "run"]' 2>/dev/null | grep -v '^\[\]$' || true)" + tries=$((tries + 1)) + "${AK_PY}" -c 'import time; time.sleep(0.1)' + done + wait "${fanpid}" + expect_eq "fanout: while a lane runs, ak ps --all lists it with the run's id" "${lanes_seen}" "[\"$(json_get "${BOX}/seen.json" 'd["run_id"]')\"]" + # --- the declared pool --------------------------------------------------------- fanout_tasks "${tasks}" claude one two fanout_run -- fanout run --tasks "${tasks}" --only @b --max-parallel 1 --json; status=$? diff --git a/tests/scopes/sessions.sh b/tests/scopes/sessions.sh index 1d34c8e..43d49b1 100644 --- a/tests/scopes/sessions.sh +++ b/tests/scopes/sessions.sh @@ -139,5 +139,31 @@ sys.exit(0 if sessions.liveness(doc)[0] is False else 1)' "${rec}" "${ROOT}/lib" usage_server_stop ak_split -- ps --json expect_eq "ps cli: when the CLI exits the session is gone" "$(json_get "${BOX}/out" 'd["sessions"]')" "[]" - expect_has "ps cli: ak --help lists the command" "$(ak -- --help)" "ak ps [--json]" + expect_has "ps cli: ak --help lists the command" "$(ak -- --help)" "ak ps [--all] [--json]" + + # A headless ak run: listed by ak ps --all while it runs, gone when it ends; the fan-out marker never reaches the CLI. + local runner seen_run + printf '{"oauthAccount":{"emailAddress":"x"}}\n' > "${BOX}/home/.local/share/agentkit/profiles/claude/work/.claude.json" # logged in, for ak run + ( cd "${BOX}/work" && exec env -i HOME="${BOX}/home" PATH="${BOX}/bin:${BASE_PATH}" TMPDIR="${BOX}/tmp" AGENTKIT_KEYCHAIN=off \ + FAKE_MODE=headless FAKE_SLEEP=3 FAKE_ENV_NAMES=1 "FAKE_LOG=${BOX}/run-log" AGENTKIT_FANOUT_RUN=20260101-000000-abcd \ + bash "${ROOT}/bin/ak" run claude @work -- "hi" > "${BOX}/run-out" 2>/dev/null ) & + runner=$!; seen_run=""; tries=0 + while [[ ${tries} -lt 40 && -z "${seen_run}" ]]; do + ak_split -- ps --all --json + seen_run="$(json_get "${BOX}/out" '[[s["kind"], s["profile"], s["run_id"]] for s in d["sessions"] if s["mode"] == "run"]' 2>/dev/null | grep claude || true)" + tries=$((tries + 1)) + "${AK_PY}" -c 'import time; time.sleep(0.1)' + done + expect_eq "ps --all: a running ak run is listed, with the fan-out run it belongs to" "${seen_run}" '[["claude", "@work", "20260101-000000-abcd"]]' + ak_split -- ps --json + expect_eq "ps: ... and ak ps without --all does not list it" "$(json_get "${BOX}/out" '[s["mode"] for s in d["sessions"]]')" "[]" + wait "${runner}" + expect_has "ps --all: the CLI's variable names were recorded (the check below can see)" "$(cat "${BOX}/run-log")" "ENVNAME=HOME" + expect_lacks "ps --all: the fan-out marker never reaches the CLI" "$(cat "${BOX}/run-log")" "ENVNAME=AGENTKIT_FANOUT_RUN" + ak_split -- ps --all --json + expect_eq "ps --all: when the run ends its record is gone" "$(json_get "${BOX}/out" 'd["sessions"]')" "[]" + expect_eq "ps --all: no record file is left behind" "$(sessions_count)" 0 + ak FAKE_MODE=headless -- run claude @work -- "hi" >/dev/null + expect_eq "ps --all: a finished run removed its own record (before anything prunes it)" \ + "$(find "$(sessions_dir)" -name 'run-*.json' 2>/dev/null | wc -l | tr -d ' ')" 0 } From f9a272ebe7e564fed536bd9fce5734a8146ed375 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 08:56:57 -0500 Subject: [PATCH 04/11] feat(fanout): branch prefix, label and per-task limits ak fanout run --branch-prefix P puts lanes on P/, refused before anything is created when such a branch exists; --label is echoed in fanout-v1 and the record; a task may carry its own timeout and exclude. ak fanout clean deletes a prefixed branch only when the lane's proven worktree has it checked out, and names it when the worktree is gone. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/SECURITY.md | 6 +- docs/fanout.md | 17 +++++- docs/schema/fanout-v1.json | 6 +- lib/fanout.py | 111 ++++++++++++++++++++++++++++++++----- tests/py/fanout_checks.py | 92 ++++++++++++++++++++++++++++++ tests/scopes/fanout.sh | 33 +++++++++++ 7 files changed, 246 insertions(+), 20 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index 01df4fa..c9c5263 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ permission posture changes. ### Added +- **A fan-out that fits a plan.** `ak fanout run --branch-prefix P` puts lanes on `P/` (refused before anything is created when such a branch exists), `--label TEXT` is echoed in `fanout-v1` and the record, and a task may carry its own `timeout` and `exclude`. `ak fanout clean` deletes a prefixed branch only when the lane's proven worktree has it checked out. Additive. - **`ak ps` shows more.** `--json` carries the effective `thresholds` `{low, critical}` and, per session, `herdr_server` (an opaque id: pane ids are unique per Herdr server, not per host). `ak ps --all` also lists running headless `ak run` processes (`mode` `run`, with `run_id` for fan-out lanes and `owner`). `ak ps` without `--all` lists what it listed before. Additive. - **Leases are visible.** With `ak run --pick --owner`, each entry of `attempts` carries `lease: {owner, released}` (or `null` when the lease could not be taken), and `docs/run.md` states its lifetime. Each `ak ps --json` session carries `leases: [{owner, purpose}]` for its account. Additive. - **A declared account pool.** `--only @a,@b` on `ak pick` (also with `--kinds`), `ak run --pick` and `ak fanout run`, or `AGENTKIT_POOL=@a,@b` when no flag is given, keeps every choice — failover included — inside those profiles. A profile outside the pool is listed as `outside the pool` and never chosen. Additive; without either nothing changes. diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 39c4c31..3fa2b5b 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -170,8 +170,10 @@ profile and its headroom, nothing else. account, and `ak fanout clean` — and only when the path is in the run's record, has the place and name the run gives its lanes, is a linked worktree of the recorded repository and is its own git top level; the - branch it deletes is computed from the run and the lane, never read from - the record. A branch that holds commits is never reset, and is deleted + branch it deletes is computed from the run and the lane (or the run's + `--branch-prefix` and the lane), never read from the record, and a + prefixed branch is deleted only when the proven worktree has it checked + out. A branch that holds commits is never reset, and is deleted only with `--discard`. It never merges, pushes or rebases. A lane's transcript holds whatever its CLI printed: treat the log files like the CLI's own session files. diff --git a/docs/fanout.md b/docs/fanout.md index 955c380..c9ea306 100644 --- a/docs/fanout.md +++ b/docs/fanout.md @@ -3,7 +3,8 @@ ``` ak fanout run --tasks FILE|- [--kind KIND] [--fallback KIND,KIND] [--base REF] [--max-parallel N] [--failover N] [--timeout SECONDS] [--owner ADDR] - [--worktrees DIR] [--only @a,@b] [--ask] [--trust-cwd] [--json] + [--worktrees DIR] [--only @a,@b] [--branch-prefix P] [--label TEXT] + [--ask] [--trust-cwd] [--json] ak fanout ls ak fanout clean [--discard] ``` @@ -33,6 +34,10 @@ in each worktree and merging what passes is still yours. `-`). - `kind` is optional per task; `--kind` is the kind of every task that names none. +- `timeout` (seconds, above 0, at most a day) and `exclude` (a list of + `@profile`s) are optional per task: a task's own `timeout` wins over + `--timeout`, and its `exclude` is added to the run's. +- An id is lowercase: `T-1` is refused, not lowercased — write `t-1`. - Any other key, and anything else wrong with the list, is a usage error (exit 2) **before anything is created**: no record, no worktree, no branch. @@ -74,6 +79,8 @@ opt-out always wins. A new worktree is a folder the CLI has not seen: pass | `--fallback KIND,KIND` | further kinds a lane may fall back to, in priority order | | `--timeout SECONDS` | per attempt | | `--base REF` | the commit every lane starts from | +| `--branch-prefix P` | lanes on `P/` (for a plan: `dwp/PLAN_014`) instead of `ak//`; refused, before anything is created, when one of those branches already exists | +| `--label TEXT` | up to 80 printable characters echoed in the result and the record — the plan or batch the run serves | | `--only @a,@b` | lanes use only these profiles ([the declared pool](usage.md#the-declared-pool---only-agentkit_pool)); default `AGENTKIT_POOL` | ## When an account runs dry @@ -120,6 +127,7 @@ surface of its own; interface 1 is unchanged. | Key | Meaning | | --- | --- | | `run_id`, `repo`, `base`, `owner` | the run, the repository's top level, the base commit, the lease owner | +| `label`, `branch_prefix` | as given, or `null` | | `exit` | the command's exit code | | `summary` | `ok`, `failed`, `not_started` — lane counts | | `lanes[]` | one entry per task, in the order given | @@ -186,8 +194,11 @@ run 20261201-101500-3fa2: 1 lane kept; its record stays this holds: it is in the run's record; it is where this run puts a lane (`…//wt/`, or `…//` under `--worktrees`); git lists it as a linked worktree of the recorded repository; and it is its -own git top level. The branch it deletes is always `ak//`, -computed, never read from the record. A record that was edited to name +own git top level. The branch it deletes is computed — `ak//`, +or `/` for a run with `--branch-prefix` — never read from +the record. A prefixed name is no longer the run's alone, so such a branch is +deleted only when the lane's proven worktree has it checked out; when the +worktree is already gone, the branch is left in place and named. A record that was edited to name anything else — another directory, the repository, another run's worktree — makes that lane *kept*, with or without `--discard`. A run that is still running is left alone. diff --git a/docs/schema/fanout-v1.json b/docs/schema/fanout-v1.json index 9936632..a55c580 100644 --- a/docs/schema/fanout-v1.json +++ b/docs/schema/fanout-v1.json @@ -5,7 +5,7 @@ "description": "The result of one fan-out: N tasks, each run in its own git worktree on its own new branch, on an account ak pick chose. One entry per task, in the order given. A lane's result is the agent's claim: nothing here was verified, merged, pushed or rebased by ak. Never contains a secret value or an account identity (e-mail, organisation, id); profiles are names. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions.", "type": "object", "additionalProperties": false, - "required": ["schema", "interface", "generated_at", "run_id", "repo", "base", "owner", "exit", "lanes", "summary"], + "required": ["schema", "interface", "generated_at", "run_id", "repo", "base", "owner", "label", "branch_prefix", "exit", "lanes", "summary"], "properties": { "schema": { "const": "fanout-v1" }, "interface": { "const": 1 }, @@ -14,6 +14,8 @@ "repo": { "type": "string", "description": "The top level of the repository the run was started in (absolute)." }, "base": { "type": "string", "pattern": "^[0-9a-f]{40,64}$", "description": "The commit every lane started from." }, "owner": { "type": "string", "description": "The lease owner of the run's lanes." }, + "label": { "type": ["string", "null"], "description": "The --label the run was given (e.g. the plan it serves), or null." }, + "branch_prefix": { "type": ["string", "null"], "description": "The --branch-prefix: lanes are on /; null when they are on ak//." }, "exit": { "enum": [0, 1, 3, 5], "description": "The command's exit code: 0 every lane succeeded; 1 a lane failed; 3 no lane could start; 5 cancelled." }, "summary": { "type": "object", @@ -37,7 +39,7 @@ "kind": { "type": "string", "description": "The kind of the last attempt (a fallback kind when the lane fell back), else the task's kind." }, "profile": { "type": ["string", "null"], "description": "The account of the last attempt (@default or @name); null when no attempt was made." }, "worktree": { "type": ["string", "null"], "description": "The lane's worktree (absolute); null when it could not be created." }, - "branch": { "type": ["string", "null"], "description": "The lane's branch, ak//; null when it could not be created." }, + "branch": { "type": ["string", "null"], "description": "The lane's branch, ak// or /; null when it could not be created." }, "exit": { "type": "integer", "description": "The lane's ak run exit code (docs/run.md): 0 success, 1 failure, 3 never started, 4 timeout, 5 cancelled, >= 64 internal." }, "duration_s": { "type": "number", "minimum": 0, "description": "Wall-clock seconds of the last attempt." }, "result_text": { "type": "string", "description": "The agent's final answer, as ak run extracted it." }, diff --git a/lib/fanout.py b/lib/fanout.py index d68c259..10f84e2 100644 --- a/lib/fanout.py +++ b/lib/fanout.py @@ -42,6 +42,7 @@ import time import common +import profiles import state from common import (AkError, EXIT_AGENT_FAILED, EXIT_CANCELLED, EXIT_INTERNAL, EXIT_NOT_READY, EXIT_OK, EXIT_USAGE) @@ -61,11 +62,27 @@ # and no such word may appear in the kit's code (tests/scopes/permissions.sh). GIT_DISCARD = "-f" LEASE_WAIT = 10.0 # seconds a lane's start waits for its lease to show before the next lane starts -TASK_KEYS = ("id", "prompt", "kind") +TASK_KEYS = ("id", "prompt", "kind", "timeout", "exclude") +PREFIX = re.compile(r"^[A-Za-z0-9][A-Za-z0-9._-]*(/[A-Za-z0-9][A-Za-z0-9._-]*)*$") +LABEL_MAX = 80 +MAX_TASK_TIMEOUT = 86400 + + +def valid_prefix(text): + """A branch prefix git accepts as leading ref components: letters, + digits, '.', '_', '-', separated by '/'; no '..', no '.lock' component.""" + return (isinstance(text, str) and 0 < len(text) <= 100 and bool(PREFIX.match(text)) and ".." not in text + and not any(part.endswith(".lock") or part.endswith(".") for part in text.split("/"))) + + +def branch_name(run_id, tid, prefix=None): + """The branch of a lane: /, or ak// by default.""" + return "%s/%s" % (prefix, tid) if prefix else "ak/%s/%s" % (run_id, tid) USAGE = """usage: ak fanout run --tasks FILE|- [--kind KIND] [--fallback KIND,KIND] [--base REF] [--max-parallel N] [--failover N] [--timeout SECONDS] [--owner ADDR] - [--worktrees DIR] [--only @a,@b] [--ask] [--trust-cwd] [--json] + [--worktrees DIR] [--only @a,@b] [--branch-prefix P] [--label TEXT] + [--ask] [--trust-cwd] [--json] ak fanout ls ak fanout clean [--discard] Runs each task of a list in its own git worktree, on its own new branch, on @@ -81,6 +98,9 @@ --owner ADDR the lease owner of every lane (default fanout:) --worktrees DIR where the lanes' worktrees go (default: the kit's state directory) --only @a,@b lanes use only these profiles (default: AGENTKIT_POOL when set) + --branch-prefix P lanes on P/ instead of ak// (refused if one exists) + --label TEXT a label echoed in the result and the record (e.g. the plan's id) +A task may also carry "timeout" (seconds) and "exclude" (["@profile", ...]). --ask opt out of autonomy for every lane (also AGENTKIT_PERMISSIONS=ask) --json exactly one JSON object, schema fanout-v1 It never merges, pushes or rebases: run your gate in each worktree, merge what passes. @@ -141,12 +161,14 @@ def facts(env, worktree, base): # ------------------------------------------------------------------ input def parse_run(args): - opts = {"tasks": None, "kind": None, "fallback": [], "base": "HEAD", "max_parallel": None, + opts = {"tasks": None, "kind": None, "fallback": [], "base": "HEAD", "max_parallel": None, "branch_prefix": None, + "label": None, "failover": DEFAULT_FAILOVER, "timeout": None, "owner": None, "worktrees": None, "ask": False, "only": None, "trust_cwd": False, "json": False} valued = {"--tasks": "tasks", "--kind": "kind", "--fallback": "fallback", "--base": "base", "--max-parallel": "max_parallel", "--failover": "failover", "--timeout": "timeout", - "--owner": "owner", "--worktrees": "worktrees", "--only": "only"} + "--owner": "owner", "--worktrees": "worktrees", "--only": "only", "--branch-prefix": "branch_prefix", + "--label": "label"} i = 0 while i < len(args): arg = args[i] @@ -200,6 +222,16 @@ def _value(flag, text): return lease.check_owner(text) except AkError as exc: raise AkError(str(exc), EXIT_USAGE) + if flag == "--branch-prefix": + prefix = text.rstrip("/") + if not valid_prefix(prefix): + raise AkError("--branch-prefix takes ref components such as dwp/PLAN_014 (letters, digits, '.', '_', '-', " + "separated by '/'), got '%s'" % text, EXIT_USAGE) + return prefix + if flag == "--label": + if not text or len(text) > LABEL_MAX or any(ord(c) < 32 or ord(c) == 127 for c in text): + raise AkError("--label takes 1-%d printable characters" % LABEL_MAX, EXIT_USAGE) + return text if flag == "--only": import pick try: @@ -238,7 +270,8 @@ def read_tasks(source, model, default_kind, fallback, stdin=None): out, seen = [], set() for index, task in enumerate(tasks, 1): if not isinstance(task, dict) or set(task) - set(TASK_KEYS): - raise AkError("task %d: a task is an object with id, prompt and an optional kind" % index, EXIT_USAGE) + raise AkError("task %d: a task is an object with id, prompt and optional kind, timeout and exclude" % index, + EXIT_USAGE) tid, prompt, kind = task.get("id"), task.get("prompt"), task.get("kind", default_kind) if not isinstance(tid, str) or not TASK_ID.match(tid): raise AkError("task %d: the id is 1-32 lowercase letters, digits and '-', starting with a letter or digit" @@ -255,7 +288,23 @@ def read_tasks(source, model, default_kind, fallback, stdin=None): kind = model.canonical(kind) if kind not in model.kinds: raise AkError("task '%s': unknown kind '%s'. Kinds: %s" % (tid, kind, " ".join(model.kind_names())), EXIT_USAGE) - out.append({"id": tid, "prompt": prompt, "kind": kind}) + timeout = task.get("timeout") + if timeout is not None and (isinstance(timeout, bool) or not isinstance(timeout, (int, float)) + or not 0 < timeout <= MAX_TASK_TIMEOUT): + raise AkError("task '%s': timeout is a number of seconds above 0 and at most %d" % (tid, MAX_TASK_TIMEOUT), + EXIT_USAGE) + exclude = task.get("exclude", []) + if not isinstance(exclude, list) or not all(isinstance(e, str) and e.startswith("@") for e in exclude): + raise AkError("task '%s': exclude is a list of @profiles" % tid, EXIT_USAGE) + labels = [] + for name in exclude: + try: + label = profiles.label(profiles.normalize(name[1:])) + except AkError as exc: + raise AkError("task '%s': %s" % (tid, exc), EXIT_USAGE) + if label not in labels: + labels.append(label) + out.append({"id": tid, "prompt": prompt, "kind": kind, "timeout": timeout, "exclude": labels}) return out @@ -273,7 +322,9 @@ def __init__(self, env, run_id, repo, base, owner, opts, tasks): self.directory = os.path.join(root(env), run_id) trees = os.path.join(os.path.abspath(opts["worktrees"]), run_id) if opts["worktrees"] \ else os.path.join(self.directory, "wt") - self.lanes = [{"id": t["id"], "kind": t["kind"], "prompt": t["prompt"], "branch": "ak/%s/%s" % (run_id, t["id"]), + self.lanes = [{"id": t["id"], "kind": t["kind"], "prompt": t["prompt"], + "branch": branch_name(run_id, t["id"], opts.get("branch_prefix")), + "timeout": t.get("timeout"), "exclude": list(t.get("exclude") or []), "worktree": os.path.join(trees, t["id"]), "log": os.path.join(self.directory, t["id"] + ".log"), "created": False, "state": "pending", "result": None} for t in tasks] self.lock = threading.Lock() # the record and the lanes' states @@ -288,6 +339,7 @@ def save(self): """Write the record. Call with self.lock held (or before any lane runs).""" doc = {"schema": RECORD_SCHEMA, "run_id": self.run_id, "repo": self.repo, "base": self.base, "owner": self.owner, "created_at": int(self.created), "pid": os.getpid(), "status": self.status, + "branch_prefix": self.opts.get("branch_prefix"), "label": self.opts.get("label"), "lanes": [{"id": lane["id"], "kind": lane["kind"], "branch": lane["branch"], "worktree": lane["worktree"], "log": lane["log"], "created": lane["created"], "exit": lane["result"]["exit"] if lane["result"] else None} for lane in self.lanes]} @@ -328,8 +380,14 @@ def run_argv(run, lane, moves_left=None): argv += ["--only", ",".join(opts["only"])] if opts["fallback"]: argv += ["--fallback", ",".join(opts["fallback"])] - if opts["timeout"]: + timeout = lane.get("timeout") + if timeout is not None: + argv += ["--timeout", ("%g" % timeout)] + elif opts["timeout"]: argv += ["--timeout", opts["timeout"]] + for label in lane.get("exclude") or []: + if label not in run.spent: + argv += ["--exclude", label] if opts["ask"]: argv.append("--ask") if opts["trust_cwd"]: @@ -540,6 +598,13 @@ def execute(model, opts, env, cwd=None, now=None, stdin=None): code, base = git(env, repo, "rev-parse", "-q", "--verify", "%s^{commit}" % opts["base"]) if code != 0 or not base: raise AkError("--base %s is not a commit in this repository" % opts["base"], EXIT_USAGE) + if opts.get("branch_prefix"): + # Before anything is created: a lane never takes over a branch that already exists. + taken = [t["id"] for t in tasks + if git(env, repo, "rev-parse", "-q", "--verify", "refs/heads/" + branch_name("", t["id"], opts["branch_prefix"]))[0] == 0] + if taken: + raise AkError("branch %s already exists; pick another --branch-prefix" + % branch_name("", taken[0], opts["branch_prefix"]), EXIT_USAGE) run_id = new_run_id(now) for _ in range(8): # an id already on record is another run's: never share its record if not os.path.lexists(os.path.join(root(env), run_id)): @@ -604,6 +669,7 @@ def on_signal(_signum, _frame): import usage return code, {"schema": SCHEMA, "interface": common.INTERFACE, "generated_at": usage.iso_utc(time.time()), "run_id": run_id, "repo": repo, "base": base, "owner": run.owner, "exit": code, "lanes": lanes, + "label": opts.get("label"), "branch_prefix": opts.get("branch_prefix"), "summary": summary} @@ -692,13 +758,28 @@ def clean(env, run_id, discard=False): kept += 1 continue tid = lane["id"] - branch = "ak/%s/%s" % (run_id, tid) # derived, never read from the record - if lane.get("created") and os.path.lexists(str(lane.get("worktree"))): + prefix = doc.get("branch_prefix") + if prefix is not None and not valid_prefix(prefix): + lines.append("kept %-16s the record names a branch prefix that is not one" % tid) + kept += 1 + continue + # Derived from the run id and the lane id, never read from the record. With a prefix the name is + # no longer the run's own, so it is deleted only once its worktree proves it (below). + branch = branch_name(run_id, tid, prefix) + proven = prefix is None + present = lane.get("created") and os.path.lexists(str(lane.get("worktree"))) + if present: problem = own_worktree(env, repo, run_id, lane) if problem: lines.append("kept %-16s %s" % (tid, problem)) kept += 1 continue + code, head = git(env, lane["worktree"], "symbolic-ref", "-q", "HEAD") + if prefix is not None and (code != 0 or head != "refs/heads/" + branch): + lines.append("kept %-16s %s is not on branch %s" % (tid, lane["worktree"], branch)) + kept += 1 + continue + proven = True code, status = git(env, lane["worktree"], "status", "--porcelain=v1", "--untracked-files=all") if code != 0 or (status and not discard): lines.append("kept %-16s %s has uncommitted changes (--discard removes it)" % (tid, lane["worktree"])) @@ -710,17 +791,21 @@ def clean(env, run_id, discard=False): % (tid, branch, ahead, "" if ahead == 1 else "s")) kept += 1 continue - if lane.get("created") and os.path.lexists(str(lane.get("worktree"))): + if present: code, _out = git(env, repo, "worktree", "remove", GIT_DISCARD, lane["worktree"]) if code != 0: lines.append("kept %-16s git could not remove %s" % (tid, lane["worktree"])) kept += 1 continue git(env, repo, "worktree", "prune") - if ahead is not None: # the branch exists + if ahead is not None and proven: # the branch exists, and is this run's git(env, repo, "branch", "-D", branch) _unlink(os.path.join(directory, tid + ".log")) - lines.append("removed %-16s %s" % (tid, branch)) + if ahead is not None and not proven: + lines.append("removed %-16s (branch %s left: its worktree is gone, so it cannot be proven this run's)" + % (tid, branch)) + else: + lines.append("removed %-16s %s" % (tid, branch)) if kept: return EXIT_KEPT, lines + ["run %s: %d lane%s kept; its record stays" % (run_id, kept, "" if kept == 1 else "s")] # Every lane is gone: the record goes too. Known names only, never a tree. diff --git a/tests/py/fanout_checks.py b/tests/py/fanout_checks.py index e72540b..f7c90bd 100644 --- a/tests/py/fanout_checks.py +++ b/tests/py/fanout_checks.py @@ -312,5 +312,97 @@ class ArgvRun(object): check("fanout clean: ... and cleaned, leaving DIR itself in place", code == 0 and not os.path.exists(os.path.join(trees, RUN_W)) and os.path.isdir(trees), "%s %s" % (code, lines)) + +# ------------------------------------------------------- --branch-prefix and clean + +check("prefix: valid prefixes are accepted", all(fanout.valid_prefix(p) for p in ("dwp", "dwp/PLAN_014", "a.b/c-d_e"))) +check("prefix: what git or a path would misread is refused", + not any(fanout.valid_prefix(p) for p in ("", "/dwp", "dwp/", "dwp//x", "dwp/../x", "-x", "dwp/.x", "x.lock", "a/b.", "a b", "a~b", + "a^b", "a:b", "x" * 101, None))) +check("prefix: a lane's branch is /, else ak//", + fanout.branch_name("R", "one", "dwp/P") == "dwp/P/one" and fanout.branch_name("R", "one") == "ak/R/one") + + +def new_prefixed_run(repo, base, run_id, ids, prefix): + directory, doc = new_run(repo, base, run_id, [], status="finished") + lanes = [] + for tid in ids: + tree = os.path.join(directory, "wt", tid) + os.makedirs(os.path.dirname(tree), exist_ok=True) + assert g(repo, "worktree", "add", "-q", "-b", "%s/%s" % (prefix, tid), tree, base)[0] == 0 + lanes.append({"id": tid, "kind": "claude", "branch": "%s/%s" % (prefix, tid), "worktree": tree, + "log": os.path.join(directory, tid + ".log"), "created": True, "exit": 0}) + rewrite(directory, lambda d: d.update(lanes=lanes, branch_prefix=prefix)) + return directory, dict(doc, lanes=lanes, branch_prefix=prefix) + + +RUN_P = "20260101-000000-5555" +dir_p, doc_p = new_prefixed_run(REPO, BASE, RUN_P, ["one", "two"], "dwp/PLAN_X") +code, lines = clean(RUN_P) +check("prefix clean: lanes on / are cleaned, worktree and branch", + code == 0 and g(REPO, "branch", "--list", "dwp/PLAN_X/*")[1] == "" and not os.path.exists(dir_p), "%s %s" % (code, lines)) + +# an edited prefix can never reach a branch the run did not make +g(REPO, "branch", "keep/one", BASE) # the user's own branch, fully merged +RUN_Q = "20260101-000000-6666" +dir_q, doc_q = new_prefixed_run(REPO, BASE, RUN_Q, ["one"], "dwp/PLAN_Y") +rewrite(dir_q, lambda d: d.update(branch_prefix="keep")) +code, lines = clean(RUN_Q, discard=True) +check("prefix clean: a record whose prefix was edited to name another branch keeps that lane (the worktree is not on it)", + code == 1 and any(line.startswith("kept") and "is not on branch keep/one" in line for line in lines) + and g(REPO, "rev-parse", "-q", "--verify", "refs/heads/keep/one")[0] == 0, "%s %s" % (code, lines)) +rewrite(dir_q, lambda d: d.update(branch_prefix="dwp/PLAN_Y")) +g(REPO, "worktree", "remove", "--force", doc_q["lanes"][0]["worktree"]) +rewrite(dir_q, lambda d: d.update(branch_prefix="keep")) +code, lines = clean(RUN_Q, discard=True) +check("prefix clean: with the worktree gone, a prefixed branch is never deleted (it cannot be proven the run's)", + code == 0 and g(REPO, "rev-parse", "-q", "--verify", "refs/heads/keep/one")[0] == 0 + and any("left" in line and "cannot be proven" in line for line in lines), "%s %s" % (code, lines)) +check("prefix clean: ... and the run's own branch stays too (not proven either); the user deletes it by name", + g(REPO, "rev-parse", "-q", "--verify", "refs/heads/dwp/PLAN_Y/one")[0] == 0) +g(REPO, "branch", "-D", "dwp/PLAN_Y/one") +RUN_B = "20260101-000000-4444" +dir_b, doc_b = new_prefixed_run(REPO, BASE, RUN_B, ["one"], "dwp/PLAN_Z") +rewrite(dir_b, lambda d: d.update(branch_prefix="../../x")) +code, lines = clean(RUN_B, discard=True) +check("prefix clean: a prefix that is not one keeps the lane", code == 1 and any("not one" in line for line in lines), str(lines)) +rewrite(dir_b, lambda d: d.update(branch_prefix="dwp/PLAN_Z")) +check("prefix clean: restored, it cleans", clean(RUN_B)[0] == 0) +g(REPO, "branch", "-D", "keep/one") + +# per-task timeout and exclude reach the lane's argv +import kinds # noqa: E402 +tasks_file = os.path.join(TMP, "per-task.json") +with open(tasks_file, "w") as handle: + json.dump({"tasks": [{"id": "a", "prompt": "x", "kind": "claude", "timeout": 90, "exclude": ["@work", "@1"]}, + {"id": "b", "prompt": "y", "kind": "claude"}]}, handle) +tasks = fanout.read_tasks(tasks_file, kinds.load(), None, []) +check("per-task: timeout and exclude are read and normalised", + tasks[0]["timeout"] == 90 and tasks[0]["exclude"] == ["@work", "@default"] and tasks[1]["timeout"] is None and tasks[1]["exclude"] == [], + str(tasks)) + + +class PerTaskRun(object): + owner, spent = "fanout:x", [] + opts = {"failover": 1, "fallback": [], "timeout": "600", "ask": False, "trust_cwd": False} + + +argv_a = fanout.run_argv(PerTaskRun, {"kind": "claude", "worktree": "/w/a", "prompt": "x", "timeout": 90, "exclude": ["@work"]}) +argv_b = fanout.run_argv(PerTaskRun, {"kind": "claude", "worktree": "/w/b", "prompt": "y", "timeout": None, "exclude": []}) +check("per-task: a task's timeout wins over --timeout; its excludes are added", + argv_a[argv_a.index("--timeout") + 1] == "90" and "@work" in argv_a and argv_b[argv_b.index("--timeout") + 1] == "600", + "%s | %s" % (argv_a, argv_b)) +for label, task in (("a timeout of 0", {"timeout": 0}), ("a timeout that is text", {"timeout": "90"}), ("a timeout of true", {"timeout": True}), + ("an exclude that is not a list", {"exclude": "@work"}), ("an exclude without @", {"exclude": ["work"]}), + ("an exclude that is not a profile name", {"exclude": ["@bad/name"]})): + with open(tasks_file, "w") as handle: + json.dump({"tasks": [dict({"id": "a", "prompt": "x", "kind": "claude"}, **task)]}, handle) + try: + fanout.read_tasks(tasks_file, kinds.load(), None, []) + refused = False + except AkError as exc: + refused = exc.code == 2 + check("per-task: %s is a usage error" % label, refused) + if FAILS: sys.exit(1) diff --git a/tests/scopes/fanout.sh b/tests/scopes/fanout.sh index 0a78e4a..5e1088a 100644 --- a/tests/scopes/fanout.sh +++ b/tests/scopes/fanout.sh @@ -162,6 +162,39 @@ scope_fanout() { wait "${fanpid}" expect_eq "fanout: while a lane runs, ak ps --all lists it with the run's id" "${lanes_seen}" "[\"$(json_get "${BOX}/seen.json" 'd["run_id"]')\"]" + # --- a fan-out that fits a plan: --branch-prefix, --label, per-task limits ------------- + fanout_tasks "${tasks}" claude t-1 t-2 + fanout_run -- fanout run --tasks "${tasks}" --branch-prefix dwp/PLAN_014 --label PLAN_014 --json; status=$? + expect_eq "fanout plan: lanes land on /; the label and prefix are echoed" \ + "${status}:$(json_get "${BOX}/out" '[d["label"], d["branch_prefix"], [l["branch"] for l in d["lanes"]]]')" \ + '0:["PLAN_014", "dwp/PLAN_014", ["dwp/PLAN_014/t-1", "dwp/PLAN_014/t-2"]]' + expect_eq "fanout plan: the branches exist in the repository" \ + "$(fanout_git "${FAN_REPO}" branch --list 'dwp/PLAN_014/*' | wc -l | tr -d ' ')" 2 + run="$(json_get "${BOX}/out" 'd["run_id"]')" + expect_eq "fanout plan: the record keeps the label and the prefix" \ + "$(json_get "${BOX}/home/.local/state/agentkit/fanout/${run}/run.json" '[d["label"], d["branch_prefix"]]')" '["PLAN_014", "dwp/PLAN_014"]' + before="$(fanout_side_effects)" + fanout_run -- fanout run --tasks "${tasks}" --branch-prefix dwp/PLAN_014 --json; status=$? + expect_eq "fanout plan: a branch that already exists refuses the run (exit 2) before anything is created" \ + "${status}:$(fanout_side_effects)" "2:${before}" + expect_has "fanout plan: ... naming the branch" "$(cat "${BOX}/err")" "branch dwp/PLAN_014/t-1 already exists" + out="$(ak -- fanout clean "${run}")"; status=$? + expect_eq "fanout plan: clean removes prefixed lanes and their branches" \ + "${status}:$(fanout_git "${FAN_REPO}" branch --list 'dwp/PLAN_014/*' | wc -l | tr -d ' ')" "0:0" + fanout_run -- fanout run --tasks "${tasks}" --label "$(printf 'plan\tx')" --json; status=$? + expect_eq "fanout plan: a label with a control character is a usage error" "${status}" 2 + for row in "--branch-prefix ../x" "--branch-prefix /x" ; do + # shellcheck disable=SC2086 # the words of one command line + fanout_run -- fanout run --tasks "${tasks}" ${row} --json; status=$? + expect_eq "fanout plan: '${row}' is a usage error" "${status}" 2 + done + "${AK_PY}" -c 'import json, sys; json.dump({"tasks": [{"id": "slow", "prompt": "x", "kind": "claude", "timeout": 1}]}, open(sys.argv[1], "w"))' "${tasks}" + fanout_run FAKE_SLEEP=5 -- fanout run --tasks "${tasks}" --timeout 600 --failover 0 --json; status=$? + expect_eq "fanout plan: a task's own timeout wins over --timeout (exit 4)" "${status}:$(json_get "${BOX}/out" 'd["lanes"][0]["exit"]')" "1:4" + "${AK_PY}" -c 'import json, sys; json.dump({"tasks": [{"id": "picky", "prompt": "x", "kind": "claude", "exclude": ["@a"]}]}, open(sys.argv[1], "w"))' "${tasks}" + fanout_run -- fanout run --tasks "${tasks}" --json; status=$? + expect_eq "fanout plan: a task's own exclude keeps its lane off that account" "${status}:$(json_get "${BOX}/out" 'd["lanes"][0]["profile"]')" "0:@b" + # --- the declared pool --------------------------------------------------------- fanout_tasks "${tasks}" claude one two fanout_run -- fanout run --tasks "${tasks}" --only @b --max-parallel 1 --json; status=$? From eafdd79f4445b50fa88b4c670088a7ee556faa39 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 09:06:33 -0500 Subject: [PATCH 05/11] docs(schema): the ak run envelope schema; closed sets; identifiers docs/schema/run-envelope-v1.json describes the interface 1 envelope of ak run, with attempts[].reason and failover as closed sets that only grow, and the exit codes stated stable. Every schema says its identifiers are profile names. docs/usage.md lists which window ids mean the same across vendors for --need; docs/run.md states that ak capacity --self works inside an ak run --pick or ak fanout lane. The contract scope pins all of it. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 1 + docs/TESTING_GUIDE.md | 2 +- docs/fanout.md | 4 +++ docs/run.md | 14 ++++++++ docs/schema/capacity-v1.json | 2 +- docs/schema/fanout-v1.json | 4 +-- docs/schema/leases-v1.json | 2 +- docs/schema/pick-v1.json | 2 +- docs/schema/pick-v2.json | 2 +- docs/schema/run-envelope-v1.json | 59 ++++++++++++++++++++++++++++++++ docs/schema/sessions-v1.json | 2 +- docs/schema/usage-v1.json | 2 +- docs/usage.md | 16 +++++++++ tests/scopes/contract.sh | 23 +++++++++++++ tests/scopes/run.sh | 22 ++++++++++++ 15 files changed, 148 insertions(+), 9 deletions(-) create mode 100644 docs/schema/run-envelope-v1.json diff --git a/CHANGELOG.md b/CHANGELOG.md index c9c5263..4f8d91d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -15,6 +15,7 @@ permission posture changes. ### Added +- **The `ak run` envelope has a schema**, [`docs/schema/run-envelope-v1.json`](docs/schema/run-envelope-v1.json). `attempts[].reason` and `failover` are closed sets that only grow (a new value is a new interface minor), the exit codes are stated stable, and every schema says its identifiers are profile names. `docs/usage.md` lists which window ids mean the same across vendors for `--need`, and `docs/run.md` states that `ak capacity --self` works inside an `ak run --pick` or `ak fanout` lane. - **A fan-out that fits a plan.** `ak fanout run --branch-prefix P` puts lanes on `P/` (refused before anything is created when such a branch exists), `--label TEXT` is echoed in `fanout-v1` and the record, and a task may carry its own `timeout` and `exclude`. `ak fanout clean` deletes a prefixed branch only when the lane's proven worktree has it checked out. Additive. - **`ak ps` shows more.** `--json` carries the effective `thresholds` `{low, critical}` and, per session, `herdr_server` (an opaque id: pane ids are unique per Herdr server, not per host). `ak ps --all` also lists running headless `ak run` processes (`mode` `run`, with `run_id` for fan-out lanes and `owner`). `ak ps` without `--all` lists what it listed before. Additive. - **Leases are visible.** With `ak run --pick --owner`, each entry of `attempts` carries `lease: {owner, released}` (or `null` when the lease could not be taken), and `docs/run.md` states its lifetime. Each `ak ps --json` session carries `leases: [{owner, purpose}]` for its account. Additive. diff --git a/docs/TESTING_GUIDE.md b/docs/TESTING_GUIDE.md index 5ae284a..1f368e4 100644 --- a/docs/TESTING_GUIDE.md +++ b/docs/TESTING_GUIDE.md @@ -33,7 +33,7 @@ when nothing failed. | permission posture (`--ask`, `--auto`, `AGENTKIT_PERMISSIONS`, `box_posture`) | `permissions` | | `ak fanout` (`lib/fanout.py`, `docs/schema/fanout-v1.json`) | `fanout` (the task list and its refusals before any side effect, a worktree and a branch per lane, accounts and leases through `ak run --pick`, an exclusive account one lane at a time, parallelism, the opt-out in every lane, `fanout-v1`, the run record; lane failover with a reset worktree, cancellation, `ak fanout clean`; a throwaway git repository in the sandbox; the removal guards bash free in `tests/py/fanout_checks.py`), `run` (the lane engine), `lease`, `security` | | `ak env` (`lib/envcmd.py`), `ak doctor` (`lib/doctor.py`), `docs/schema/doctor-v1.json` | `doctor` | -| `ak run` (`lib/run.py`), including `--pick`, `--failover`, `--fallback` and `--owner` (the choice through `pick.select`, the two triggers, the workspace rule, the lease; two fake accounts against the loopback usage endpoint, `FAKE_FAIL_FOR` and `FAKE_WRITE` in `tests/fakes/_fake.sh`) | `run` (+ `pick`, `lease` for the shared choice and the lease store; the full suite for a change to the envelope) | +| `ak run` (`lib/run.py`, the envelope schema `docs/schema/run-envelope-v1.json`, also pinned by `contract`), including `--pick`, `--failover`, `--fallback` and `--owner` (the choice through `pick.select`, the two triggers, the workspace rule, the lease; two fake accounts against the loopback usage endpoint, `FAKE_FAIL_FOR` and `FAKE_WRITE` in `tests/fakes/_fake.sh`) | `run` (+ `pick`, `lease` for the shared choice and the lease store; the full suite for a change to the envelope) | | `ak setup` (`lib/setup.py`, `docs/schema/setup-*.json`, checks in `tests/py/setup_checks.py`) | `setup` (probe, verify, docker on simulated Linux, macOS, Windows, WSL, musl and container hosts), `security` | | `skills/agentkit-setup/` (`tests/py/skill_checks.py agentkit-setup`, `tests/py/skill_scenarios.py`) | `setup-skill` (form, marketplace rules, consent gates, and the documented flows run in sandboxes), `skill` | | `skills/agentkit-orchestrate/` (`tests/py/skill_checks.py agentkit-orchestrate`, the scenarios in `tests/py/orchestrate_scenarios.py`) | `orchestrate-skill` (form, marketplace rules, the real `ak pick` grammar of every line, safety rules, `ak --skill orchestrate`, and the taught loop run against fake accounts), `skill` | diff --git a/docs/fanout.md b/docs/fanout.md index c9ea306..8ac4e02 100644 --- a/docs/fanout.md +++ b/docs/fanout.md @@ -141,6 +141,10 @@ surface of its own; interface 1 is unchanged. No key value and no account identity is ever in it; profiles are names. +These exit codes are stable: 1 (a lane ran and failed) and 3 (no lane could +start) stay distinct. A lane's `attempts[].reason` takes the values of +[`ak run`'s closed set](run.md#--output-format-json). + | Exit | Meaning | | --- | --- | | 0 | every lane exited 0 | diff --git a/docs/run.md b/docs/run.md index f0e858e..b3e64e0 100644 --- a/docs/run.md +++ b/docs/run.md @@ -79,6 +79,12 @@ cleans anything: when the work tree changed, the run stops there and says `cwd changed`. For retries that start from a clean copy each time, use a worktree per task ([Orchestration](orchestration.md)). +**Inside a lane, `ak capacity --self` works.** Each attempt runs with the +account marker `ak` sets on every launch (`AGENTKIT_ACTIVE_ACCOUNT`), so an +agent started by `ak run --pick` — or by an `ak fanout` lane — can check its +own room at task boundaries, and after a failover it reads the account it was +moved to. + The failed account is left out of the next choice; `--ask` and `AGENTKIT_PERMISSIONS=ask` apply to every attempt; each move is one line on stderr (`ak: claude @work: account spent; trying another account`). @@ -126,6 +132,14 @@ exit 1. ## `--output-format json` +Schema: [`schema/run-envelope-v1.json`](schema/run-envelope-v1.json). The +exit codes above are stable; a consumer may branch on 3 ("nothing started") +as distinct from 1 ("the agent failed"). The closed sets `attempts[].reason` +(`not ready`, `account spent`, `null`) and `failover` (`null`, `no account +left`, `limit reached`, `cwd changed`) only ever grow: a new value is a new +interface minor, listed in the CHANGELOG. Every identifier is a profile name +— never an e-mail, an account id or a token. + stdout is **exactly one JSON object**, also when the run never started; the CLI's own output (its transcript, including its JSON stream) goes to stderr. diff --git a/docs/schema/capacity-v1.json b/docs/schema/capacity-v1.json index bf69101..eb50556 100644 --- a/docs/schema/capacity-v1.json +++ b/docs/schema/capacity-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/capacity-v1.json", "title": "ak capacity --json (capacity-v1)", - "description": "One account's headroom and a verdict, computed with ak pick's arithmetic (pick.evaluate: the smallest free share of the governing windows, a 10% reserve on windows of 7 days or more) and pick's lower-only drill cap. The reading comes from the kit's usage cache when fresh (usage numbers only; ak usage is the only command that always reads live). Exit 0 for every reading; the verdict is here, not in the exit code. Never contains a secret value. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions.", + "description": "One account's headroom and a verdict, computed with ak pick's arithmetic (pick.evaluate: the smallest free share of the governing windows, a 10% reserve on windows of 7 days or more) and pick's lower-only drill cap. The reading comes from the kit's usage cache when fresh (usage numbers only; ak usage is the only command that always reads live). Exit 0 for every reading; the verdict is here, not in the exit code. Never contains a secret value. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "additionalProperties": false, "required": ["schema", "interface", "generated_at", "kind", "cli", "profile", "status", "verdict", "headroom_pct", "binding_window", "resets_at", "reason", "thresholds", "source", "age_s", "capped", "leases", "cache_note"], diff --git a/docs/schema/fanout-v1.json b/docs/schema/fanout-v1.json index a55c580..f22f242 100644 --- a/docs/schema/fanout-v1.json +++ b/docs/schema/fanout-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/fanout-v1.json", "title": "ak fanout run --json (fanout-v1)", - "description": "The result of one fan-out: N tasks, each run in its own git worktree on its own new branch, on an account ak pick chose. One entry per task, in the order given. A lane's result is the agent's claim: nothing here was verified, merged, pushed or rebased by ak. Never contains a secret value or an account identity (e-mail, organisation, id); profiles are names. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions.", + "description": "The result of one fan-out: N tasks, each run in its own git worktree on its own new branch, on an account ak pick chose. One entry per task, in the order given. A lane's result is the agent's claim: nothing here was verified, merged, pushed or rebased by ak. Never contains a secret value or an account identity (e-mail, organisation, id); profiles are names. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "additionalProperties": false, "required": ["schema", "interface", "generated_at", "run_id", "repo", "base", "owner", "label", "branch_prefix", "exit", "lanes", "summary"], @@ -57,7 +57,7 @@ "exit": { "type": "integer" }, "cli_exit": { "type": ["integer", "null"] }, "duration_s": { "type": "number" }, - "reason": { "type": ["string", "null"] }, + "reason": { "enum": ["not ready", "account spent", null], "description": "Why the lane moved on from this attempt; null on the last one. Additive-only: a new value is a new interface minor." }, "lease": { "type": ["object", "null"], "description": "The lease the attempt held: its owner and whether it was released at the end; null when it could not be taken.", diff --git a/docs/schema/leases-v1.json b/docs/schema/leases-v1.json index f6ac857..5dad7f5 100644 --- a/docs/schema/leases-v1.json +++ b/docs/schema/leases-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/leases-v1.json", "title": "ak lease ls --json (leases-v1)", - "description": "Every active (unexpired) advisory account lease on this machine, oldest first. Leases grant nothing: ak pick --owner and the orchestration skill respect them. Holds profile names, owner addresses, times and a purpose note; never a secret value or a path. Additional keys may appear in later minor versions.", + "description": "Every active (unexpired) advisory account lease on this machine, oldest first. Leases grant nothing: ak pick --owner and the orchestration skill respect them. Holds profile names, owner addresses, times and a purpose note; never a secret value or a path. Additional keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "required": ["schema", "interface", "generated_at", "leases"], "properties": { diff --git a/docs/schema/pick-v1.json b/docs/schema/pick-v1.json index 0644d7d..91174b1 100644 --- a/docs/schema/pick-v1.json +++ b/docs/schema/pick-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/pick-v1.json", "title": "ak pick --json (pick-v1)", - "description": "The account(s) with the most usable headroom for a kind, chosen from the same rows as `ak usage` by one documented policy (docs/usage.md#choosing-an-account). No login is refreshed, no reset is spent; since 0.6.0 a fresh reading may come from the kit's usage cache (usage numbers only; --max-age). Never contains a secret value or an account identity. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions.", + "description": "The account(s) with the most usable headroom for a kind, chosen from the same rows as `ak usage` by one documented policy (docs/usage.md#choosing-an-account). No login is refreshed, no reset is spent; since 0.6.0 a fresh reading may come from the kit's usage cache (usage numbers only; --max-age). Never contains a secret value or an account identity. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "required": ["schema", "interface", "generated_at", "target", "model", "reserve_pct", "need", "count", "chosen", "candidates", "soonest_reset"], "properties": { diff --git a/docs/schema/pick-v2.json b/docs/schema/pick-v2.json index 3aac61f..8730b3c 100644 --- a/docs/schema/pick-v2.json +++ b/docs/schema/pick-v2.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/pick-v2.json", "title": "ak pick --kinds --json (pick-v2)", - "description": "The cross-kind priority pick for daemons (herdr-peers autopilot --loop and its agents): the FIRST kind of --kinds with a qualifying account, chosen by the same rows, cache and policy as pick-v1 (docs/usage.md#choosing-an-account). Read-only: no login is refreshed, no reset is spent. `launch.argv` is the exact interactive argv to start that agent, so a caller never learns any CLI's own flags; `model` is what the caller asked for that kind (resolution happens at launch). Never contains a secret value or an account identity. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions.", + "description": "The cross-kind priority pick for daemons (herdr-peers autopilot --loop and its agents): the FIRST kind of --kinds with a qualifying account, chosen by the same rows, cache and policy as pick-v1 (docs/usage.md#choosing-an-account). Read-only: no login is refreshed, no reset is spent. `launch.argv` is the exact interactive argv to start that agent, so a caller never learns any CLI's own flags; `model` is what the caller asked for that kind (resolution happens at launch). Never contains a secret value or an account identity. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "required": ["schema", "interface", "generated_at", "kinds", "qualifies", "priority_index", "kind", "cli", "profile", "model", "headroom_pct", "binding_window", "resets_at", "reason", "launch", "lease", "soonest_reset"], "properties": { diff --git a/docs/schema/run-envelope-v1.json b/docs/schema/run-envelope-v1.json new file mode 100644 index 0000000..0e00e47 --- /dev/null +++ b/docs/schema/run-envelope-v1.json @@ -0,0 +1,59 @@ +{ + "$schema": "https://json-schema.org/draft/2020-12/schema", + "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/run-envelope-v1.json", + "title": "ak run --output-format json (the interface 1 envelope)", + "description": "The one JSON object ak run prints with --output-format json, also when the run never started. Part of interface 1: its keys and their meaning are frozen; keys are only ever added. The closed value sets below (attempts[].reason, failover) are additive-only: a new value is a new interface minor and is listed in the CHANGELOG, so a consumer may branch on the values it knows and treat an unknown one as 'stopped for another reason'. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token; no secret value is ever in it. Exit codes are stable: 0 success, 1 agent failure, 2 usage, 3 nothing started (not installed, not logged in, key or profile missing, or with --pick no account with room), 4 timeout, 5 cancelled, >= 64 internal.", + "type": "object", + "additionalProperties": false, + "required": ["interface", "kind", "profile", "cwd", "exit", "duration_s", "result_text", "cli_exit", "truncated"], + "properties": { + "interface": { "const": 1 }, + "kind": { "type": ["string", "null"], "description": "The kind of the last attempt; null when the command line named none." }, + "profile": { "type": "string", "pattern": "^@", "description": "@default or @name." }, + "cwd": { "type": ["string", "null"] }, + "exit": { "type": "integer", "description": "The exit code above; the same as the process's." }, + "duration_s": { "type": "number", "minimum": 0 }, + "result_text": { "type": "string" }, + "cli_exit": { "type": ["integer", "null"], "description": "The CLI's own exit status; null when it never started; negative = killed by that signal." }, + "truncated": { "type": "boolean" }, + "error": { "type": "string", "description": "Present only when the run never started: the one-line reason." }, + "tokens": { + "type": "object", + "description": "Present on runs that started: the counts the CLI reported; a field it did not report is null, never imputed.", + "additionalProperties": false, + "required": ["input", "output", "cache_read", "cache_write", "total"], + "properties": { + "input": { "type": ["integer", "null"], "minimum": 0 }, + "output": { "type": ["integer", "null"], "minimum": 0 }, + "cache_read": { "type": ["integer", "null"], "minimum": 0 }, + "cache_write": { "type": ["integer", "null"], "minimum": 0 }, + "total": { "type": ["integer", "null"], "minimum": 0 } + } + }, + "attempts": { + "type": "array", + "description": "Only with --pick: every attempt, in order. Empty when no account had room. The top-level fields describe the last one.", + "items": { + "type": "object", + "additionalProperties": false, + "required": ["kind", "profile", "exit", "cli_exit", "duration_s", "reason"], + "properties": { + "kind": { "type": "string" }, + "profile": { "type": "string", "pattern": "^@" }, + "exit": { "type": "integer" }, + "cli_exit": { "type": ["integer", "null"] }, + "duration_s": { "type": "number", "minimum": 0 }, + "reason": { "enum": ["not ready", "account spent", null], "description": "Why the run moved on from this attempt; null on the last one. Additive-only." }, + "lease": { + "type": ["object", "null"], + "description": "Only with --owner: the lease the attempt held; null when it could not be taken.", + "additionalProperties": false, + "required": ["owner", "released"], + "properties": { "owner": { "type": "string" }, "released": { "type": "boolean" } } + } + } + } + }, + "failover": { "enum": [null, "no account left", "limit reached", "cwd changed"], "description": "Only with --pick: null, or why the run stopped moving to another account. Additive-only." } + } +} diff --git a/docs/schema/sessions-v1.json b/docs/schema/sessions-v1.json index 8bad87b..15c5535 100644 --- a/docs/schema/sessions-v1.json +++ b/docs/schema/sessions-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/sessions-v1.json", "title": "ak ps --json (sessions-v1)", - "description": "The agent sessions ak launched on this machine that are still running, oldest first, each joined to its account's capacity. A session is listed while the process ak launched is alive with the start time recorded at launch; of several live sessions naming one Herdr pane only the newest is listed. A session started without ak has no entry: read a missing entry as unknown, never as no account. Headless ak run processes are not listed. Read-only: capacity comes from the kit's usage cache alone, no vendor is queried and no login is refreshed. Never contains a secret value or an account identity (e-mail, organisation, id); `cwd` is the only path. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions.", + "description": "The agent sessions ak launched on this machine that are still running, oldest first, each joined to its account's capacity. A session is listed while the process ak launched is alive with the start time recorded at launch; of several live sessions naming one Herdr pane only the newest is listed. A session started without ak has no entry: read a missing entry as unknown, never as no account. Headless ak run processes are not listed. Read-only: capacity comes from the kit's usage cache alone, no vendor is queried and no login is refreshed. Never contains a secret value or an account identity (e-mail, organisation, id); `cwd` is the only path. Consumers check `schema` and `interface` first; additional keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "additionalProperties": false, "required": ["schema", "interface", "generated_at", "thresholds", "sessions"], diff --git a/docs/schema/usage-v1.json b/docs/schema/usage-v1.json index 988b584..b529321 100644 --- a/docs/schema/usage-v1.json +++ b/docs/schema/usage-v1.json @@ -2,7 +2,7 @@ "$schema": "https://json-schema.org/draft/2020-12/schema", "$id": "https://github.com/DailybotHQ/coding-agents-kit/blob/v1.5.2/docs/schema/usage-v1.json", "title": "ak usage --json (usage-v1)", - "description": "Quota and usage of each account the kit can see, one row per credential identity. Never contains a secret value, an account identity (e-mail, organisation, id) or a token. The endpoints behind it are vendor-internal and unofficial: a row whose source changed shape reports status `error`, never a crash. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions.", + "description": "Quota and usage of each account the kit can see, one row per credential identity. Never contains a secret value, an account identity (e-mail, organisation, id) or a token. The endpoints behind it are vendor-internal and unofficial: a row whose source changed shape reports status `error`, never a crash. Consumers check `schema` and `interface` before reading anything else; additional top-level keys may appear in later minor versions. Identifiers are profile names (@default, @name), never an e-mail, an account id or a token.", "type": "object", "required": [ "schema", diff --git a/docs/usage.md b/docs/usage.md index 6fb8ed4..71ca28b 100644 --- a/docs/usage.md +++ b/docs/usage.md @@ -453,6 +453,22 @@ value it does not accept; without one the value passes through and the CLI validates it (Claude accepts its sonnet/opus/haiku aliases natively). +### Window ids across vendors (`--need`) + +`--need WIN:PCT` names a window by its id, and ids are the vendor's, not a +shared vocabulary. What holds today: + +| Id | Means | Claude | Codex | Z.AI | Antigravity | +| --- | --- | --- | --- | --- | --- | +| `5h` | the 5-hour window | yes | yes | yes | no (its ids name a model family and a period) | +| `7d` | the 7-day window, all models | yes | yes | no (`weekly`) | no | +| `7d-` | a 7-day window of one model | per model | no | no | no | + +So `--need 5h:40` means the same for Claude, Codex and Z.AI, and `--need +7d:20` for Claude and Codex only. A kind without that window is not chosen +(`no 7d window`) — a cross-kind pick that needs a weekly window should list +only kinds that have one. `ak usage --json` shows each account's ids. + ### The declared pool: `--only`, `AGENTKIT_POOL` Work is often given a fixed set of accounts. `--only @a,@b` (repeatable; bare diff --git a/tests/scopes/contract.sh b/tests/scopes/contract.sh index 4dad3cf..f924e67 100644 --- a/tests/scopes/contract.sh +++ b/tests/scopes/contract.sh @@ -147,4 +147,27 @@ assert c.EXIT_INTERNAL >= 64' "${ROOT}" "${ROOT}/install.ps1" "${ROOT}/win" "${ROOT}/skills" >/dev/null; then fail "the product works without DeepWorkPlan (no .dwp/ or deepworkplan reference in runtime files)" else pass "the product works without DeepWorkPlan (no .dwp/ or deepworkplan reference in runtime files)"; fi + + # Identifiers and closed sets are stated where consumers read them. + local name + for name in capacity-v1 leases-v1 pick-v1 pick-v2 sessions-v1 usage-v1 fanout-v1 run-envelope-v1; do + check "§3 docs/schema/${name}.json says its identifiers are profile names" \ + grep -q "Identifiers are profile names" "${ROOT}/docs/schema/${name}.json" + done + check "§3 the run envelope schema closes attempts[].reason and failover, additive-only" "${AK_PY}" -c ' +import json, sys +d = json.load(open(sys.argv[1])) +reason = d["properties"]["attempts"]["items"]["properties"]["reason"]["enum"] +failover = d["properties"]["failover"]["enum"] +ok = set(reason) == {"not ready", "account spent", None} and set(failover) == {None, "no account left", "limit reached", "cwd changed"} +sys.exit(0 if ok and "additive-only" in d["description"] else 1)' "${ROOT}/docs/schema/run-envelope-v1.json" + check "§3 the values ak run emits are exactly the schema's" "${AK_PY}" -c ' +import json, sys +sys.path.insert(0, sys.argv[2]) +import run +d = json.load(open(sys.argv[1])) +emitted = {run.REASON_NOT_READY, run.REASON_SPENT, None} +stops = {None, run.STOP_NONE_LEFT, run.STOP_LIMIT, run.STOP_CWD} +sys.exit(0 if emitted == set(d["properties"]["attempts"]["items"]["properties"]["reason"]["enum"]) + and stops == set(d["properties"]["failover"]["enum"]) else 1)' "${ROOT}/docs/schema/run-envelope-v1.json" "${ROOT}/lib" } diff --git a/tests/scopes/run.sh b/tests/scopes/run.sh index d5deef4..14ae8c9 100644 --- a/tests/scopes/run.sh +++ b/tests/scopes/run.sh @@ -221,6 +221,28 @@ run_failover() { ak_split "${base[@]}" -- run claude --pick --exclude @a --exclude @b --cwd "${repo}" --output-format json -- "do it"; status=$? expect_eq "run pick: with every account excluded nothing starts" "${status}:$(json_get "${BOX}/out" 'd["attempts"]')" "3:[]" + # The envelope against its schema, and the account a lane sees. + local envschema="${ROOT}/docs/schema/run-envelope-v1.json" + failover_prime 10 50; failover_routes 100 50 + : > "${BOX}/log" + ak_split "${base[@]}" FAKE_FAIL_FOR=/claude/a -- run claude --pick --failover 1 --owner test:lead --cwd "${repo}" --output-format json -- "do it" + cp "${BOX}/out" "${BOX}/env-pick.json" + expect_eq "run schema: a --pick envelope with a failover and leases matches docs/schema/run-envelope-v1.json" \ + "$("${AK_PY}" "${ROOT}/tests/py/schema_check.py" "${envschema}" "${BOX}/env-pick.json")" "valid" + expect_eq "run lane: each attempt's CLI got the account marker of its own account, so ak capacity --self names it" \ + "$(grep '^AGENTKIT_ACTIVE_ACCOUNT=' "${BOX}/log" | tr '\n' ' ')" "AGENTKIT_ACTIVE_ACCOUNT=claude/@a AGENTKIT_ACTIVE_ACCOUNT=claude/@b " + out="$(ak "${FO_URL}" AGENTKIT_ACTIVE_ACCOUNT=claude/@b -- capacity --self --json)" + expect_has "run lane: ak capacity --self with that marker reads the account the run moved to" "${out}" '"profile": "@b"' + ak_split "${base[@]}" -- run claude @a --cwd "${repo}" --output-format json -- "do it" + cp "${BOX}/out" "${BOX}/env-plain.json" + expect_eq "run schema: a plain envelope matches it too" "$("${AK_PY}" "${ROOT}/tests/py/schema_check.py" "${envschema}" "${BOX}/env-plain.json")" "valid" + ak_split "${base[@]}" -- run claude --pick --only @nobody --cwd "${repo}" --output-format json -- "do it" + cp "${BOX}/out" "${BOX}/env-none.json" + expect_eq "run schema: a run that never started matches it too" "$("${AK_PY}" "${ROOT}/tests/py/schema_check.py" "${envschema}" "${BOX}/env-none.json")" "valid" + printf '{"interface":1,"kind":"claude","profile":"@a","cwd":"/x","exit":1,"duration_s":0,"result_text":"","cli_exit":1,"truncated":false,"attempts":[{"kind":"claude","profile":"@a","exit":1,"cli_exit":1,"duration_s":0,"reason":"felt tired"}],"failover":null}' > "${BOX}/env-bad.json" + expect_has "run schema: a reason outside the closed set does not validate" \ + "$("${AK_PY}" "${ROOT}/tests/py/schema_check.py" "${envschema}" "${BOX}/env-bad.json")" "not in" + # The declared pool. failover_prime 10 50 ak_split "${base[@]}" -- run claude --pick --only @b --cwd "${repo}" --output-format json -- "do it"; status=$? From ac221eea58072657346ef3e42a90faa9c12de27e Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 09:18:46 -0500 Subject: [PATCH 06/11] feat(glm): default to glm-5.4 for the opus and sonnet slots Z.AI's latest flagship on the GLM Coding Plan is GLM-5.4. The opus and sonnet slots of every *-glm kind now default to glm-5.4 (from glm-5.3); the haiku slot stays on glm-5.3-flash, still the latest fast model. The values stay bare ids because they feed Claude Code, Codex, OpenCode and Pi alike; docs/kinds.md explains Z.AI's [1m] suffix for a 1M context in claude-glm. Co-Authored-By: Claude Opus 5.5 --- CHANGELOG.md | 4 ++++ docs/kinds.md | 13 ++++++++++++- lib/env.template | 5 +++-- providers.toml | 4 ++-- tests/py/kinds_checks.py | 7 ++++--- tests/scopes/dispatch.sh | 4 ++-- tests/scopes/profiles.sh | 4 ++-- 7 files changed, 29 insertions(+), 12 deletions(-) diff --git a/CHANGELOG.md b/CHANGELOG.md index ea369f1..5b64b82 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -13,6 +13,10 @@ permission posture changes. ## [Unreleased] +### Changed + +- **Z.AI GLM defaults move to the latest models.** The opus and sonnet slots of every `*-glm` kind now default to `glm-5.4` (GLM-5.4, Z.AI's flagship on the GLM Coding Plan), up from `glm-5.3`; the haiku slot stays on `glm-5.3-flash`, still the latest fast model (natively multimodal). `ZAI_DEFAULT_*_MODEL` still override them. `docs/kinds.md` explains Z.AI's `[1m]` suffix for a 1M context in `claude-glm`. + ### Added - **`ak usage` keeps showing an account it cannot read now.** A row that is diff --git a/docs/kinds.md b/docs/kinds.md index f464feb..120fd0e 100644 --- a/docs/kinds.md +++ b/docs/kinds.md @@ -33,10 +33,21 @@ Put these in `~/.config/agentkit/env` (mode 600). A named profile reads | Provider | Key | Optional settings (defaults) | |---|---|---| -| Z.AI GLM (`*-glm`) | `ZAI_CODING_API_KEY` | `ZAI_DEFAULT_SONNET_MODEL` (`glm-5.3`), `ZAI_DEFAULT_OPUS_MODEL` (`glm-5.3`), `ZAI_DEFAULT_HAIKU_MODEL` (`glm-5.3-flash`), `ZAI_ANTHROPIC_BASE_URL`, `ZAI_CODING_BASE_URL`, `ZAI_CODEX_BASE_URL`, `ZAI_CODEX_DEFAULT_MODEL`, `ZAI_OPENCODE_DEFAULT_MODEL`, `ZAI_PI_DEFAULT_MODEL`, `ZAI_CODING_API_TIMEOUT_MS`, `ZAI_CODING_AUTO_COMPACT_WINDOW` | +| Z.AI GLM (`*-glm`) | `ZAI_CODING_API_KEY` | `ZAI_DEFAULT_SONNET_MODEL` (`glm-5.4`), `ZAI_DEFAULT_OPUS_MODEL` (`glm-5.4`), `ZAI_DEFAULT_HAIKU_MODEL` (`glm-5.3-flash`), `ZAI_ANTHROPIC_BASE_URL`, `ZAI_CODING_BASE_URL`, `ZAI_CODEX_BASE_URL`, `ZAI_CODEX_DEFAULT_MODEL`, `ZAI_OPENCODE_DEFAULT_MODEL`, `ZAI_PI_DEFAULT_MODEL`, `ZAI_CODING_API_TIMEOUT_MS`, `ZAI_CODING_AUTO_COMPACT_WINDOW` | | Azure OpenAI / Foundry (`*-azure`) | `AZURE_OPENAI_API_KEY` | **required:** `AZURE_OPENAI_RESOURCE` or `AZURE_OPENAI_BASE_URL`, and `AZURE_OPENAI_MODEL_DAILY` (your deployment name — there is no default to guess); optional `AZURE_OPENAI_MODEL_REASONING`, `AZURE_OPENAI_DEFAULT_MODEL` | | xAI (`*-xai`, `grok`) | `XAI_API_KEY` | `XAI_BASE_URL` (`https://api.x.ai/v1`), `XAI_MODEL_DAILY` (`grok-4.3`), `XAI_MODEL_REASONING` (`grok-4.6`), `XAI_DEFAULT_MODEL` | +**Z.AI models.** The defaults are Z.AI's latest on the GLM Coding Plan: +GLM-5.4 (the flagship) for the opus and sonnet slots and GLM-5.3-Flash (the +fast model, natively multimodal: text, image, video and file in, text out) +for haiku. The same three values feed every `*-glm` kind, so they are the bare +ids every tool accepts. For a 1M-token context in Claude Code only, Z.AI +documents a `[1m]` suffix and a larger compaction window; with `ak` that is +`ZAI_DEFAULT_OPUS_MODEL=glm-5.4[1m]` (and the sonnet one) plus +`ZAI_CODING_AUTO_COMPACT_WINDOW=1000000` — set the suffix only when you use +`claude-glm` alone, since the other tools take the bare id. GLM-5.3-FlashX is +not on the Coding Plan yet. + | Gemini API (`antigravity`) | `GEMINI_API_KEY` | `GOOGLE_GEMINI_BASE_URL` | `grok` and `antigravity` treat the key as optional: without one each uses diff --git a/lib/env.template b/lib/env.template index 2a365e4..61c06ac 100644 --- a/lib/env.template +++ b/lib/env.template @@ -21,9 +21,10 @@ # --- Z.AI GLM (claude-glm, codex-glm, opencode-glm, pi-glm) # ZAI_CODING_API_KEY= -# ZAI_DEFAULT_SONNET_MODEL=glm-5.3 -# ZAI_DEFAULT_OPUS_MODEL=glm-5.3 +# ZAI_DEFAULT_SONNET_MODEL=glm-5.4 +# ZAI_DEFAULT_OPUS_MODEL=glm-5.4 # ZAI_DEFAULT_HAIKU_MODEL=glm-5.3-flash +# 1M context in claude-glm only: ZAI_DEFAULT_OPUS_MODEL=glm-5.4[1m] with ZAI_CODING_AUTO_COMPACT_WINDOW=1000000 # --- xAI (codex-xai, opencode-xai, pi-xai, cline-xai, grok) # XAI_API_KEY= diff --git a/providers.toml b/providers.toml index 428542d..6738cb3 100644 --- a/providers.toml +++ b/providers.toml @@ -588,8 +588,8 @@ timeout_s = 10 anthropic_base = "{ZAI_ANTHROPIC_BASE_URL:-https://api.z.ai/api/anthropic}" openai_base = "{ZAI_CODING_BASE_URL:-https://api.z.ai/api/coding/paas/v4}" codex_base = "{ZAI_CODEX_BASE_URL:-https://api.z.ai/api/v1}" -opus = "{ZAI_DEFAULT_OPUS_MODEL:-glm-5.3}" -sonnet = "{ZAI_DEFAULT_SONNET_MODEL:-glm-5.3}" +opus = "{ZAI_DEFAULT_OPUS_MODEL:-glm-5.4}" +sonnet = "{ZAI_DEFAULT_SONNET_MODEL:-glm-5.4}" haiku = "{ZAI_DEFAULT_HAIKU_MODEL:-glm-5.3-flash}" [providers.azure] diff --git a/tests/py/kinds_checks.py b/tests/py/kinds_checks.py index 98e3416..1bc6f7d 100644 --- a/tests/py/kinds_checks.py +++ b/tests/py/kinds_checks.py @@ -207,6 +207,7 @@ def variant(name, text): skipped == ["ANTHROPIC_AUTH_TOKEN"], json.dumps(skipped)) check("claude-glm defaults (Z.AI base URL, models)", printed.get("ANTHROPIC_BASE_URL") == "https://api.z.ai/api/anthropic" and + printed.get("ANTHROPIC_DEFAULT_OPUS_MODEL") == "glm-5.4" and printed.get("ANTHROPIC_DEFAULT_SONNET_MODEL") == "glm-5.4" and printed.get("ANTHROPIC_DEFAULT_HAIKU_MODEL") == "glm-5.3-flash" and "CLAUDE_CODE_AUTO_COMPACT_WINDOW" not in printed, json.dumps(printed)) lctx = kinds.Context(glm, env_in, SCRATCH, allow_secret=True) @@ -220,7 +221,7 @@ def variant(name, text): "https://res.services.ai.azure.com/openai/v1") pctx = kinds.Context(model.kind("pi-glm"), {}, SCRATCH) check("pi --models lists provider/model once each", - pctx.expand("{models}") == "zai-glm/glm-5.3,zai-glm/glm-5.3-flash", pctx.expand("{models}")) + pctx.expand("{models}") == "zai-glm/glm-5.4,zai-glm/glm-5.3-flash", pctx.expand("{models}")) # --- writers ----------------------------------------------------------------- w = os.path.join(SCRATCH, "writers") @@ -277,12 +278,12 @@ def variant(name, text): with open(pm, "w") as h: h.write('{"providers":{"mine":{"baseUrl":"http://x"}},"extra":1}\n') writers.write_pi(pm, "zai-glm", "https://api.z.ai/api/coding/paas/v4", "ZAI_CODING_API_KEY", 1000000, 131072, False, - ["glm-5.3:sonnet", "glm-5.3:opus", "glm-5.3-flash:haiku"]) + ["glm-5.4:sonnet", "glm-5.4:opus", "glm-5.3-flash:haiku"]) with open(pm) as h: d = json.load(h) p = d["providers"]["zai-glm"] check("pi writer stores \"$KEY\", keeps other providers", p["apiKey"] == "$ZAI_CODING_API_KEY" and "mine" in d["providers"] and d["extra"] == 1) -check("pi writer de-duplicates model ids", [m["id"] for m in p["models"]] == ["glm-5.3", "glm-5.3-flash"]) +check("pi writer de-duplicates model ids", [m["id"] for m in p["models"]] == ["glm-5.4", "glm-5.3-flash"]) check("pi writer refuses invalid JSON", raises(lambda: writers.write_pi(broken, "x", "u", "K", 1, 1, False, ["m"]), writers.WriterError)) diff --git a/tests/scopes/dispatch.sh b/tests/scopes/dispatch.sh index 6142c04..a2cbbc2 100644 --- a/tests/scopes/dispatch.sh +++ b/tests/scopes/dispatch.sh @@ -92,8 +92,8 @@ scope_dispatch() { dispatch_case "codex-glm -c" "-p|glm|resume|--last" ZAI_CODING_API_KEY=fake-zai-one dispatch_case "codex-xai -r abc" "-p|xai|resume|abc" XAI_API_KEY=fake-xai-one dispatch_case "opencode-xai -c" "-m|xai/grok-4.3|--continue" XAI_API_KEY=fake-xai-one - dispatch_case "opencode-glm" "-m|zai-coding-plan/glm-5.3" ZAI_CODING_API_KEY=fake-zai-one - dispatch_case "pi-glm -r abc" "--provider|zai-glm|--model|glm-5.3|--models|zai-glm/glm-5.3,zai-glm/glm-5.3-flash|--session|abc" ZAI_CODING_API_KEY=fake-zai-one + dispatch_case "opencode-glm" "-m|zai-coding-plan/glm-5.4" ZAI_CODING_API_KEY=fake-zai-one + dispatch_case "pi-glm -r abc" "--provider|zai-glm|--model|glm-5.4|--models|zai-glm/glm-5.4,zai-glm/glm-5.3-flash|--session|abc" ZAI_CODING_API_KEY=fake-zai-one dispatch_case "pi-azure" "--provider|azure-foundry|--model|my-dep|--models|azure-foundry/my-dep" \ AZURE_OPENAI_API_KEY=fake-azure-one AZURE_OPENAI_RESOURCE=res AZURE_OPENAI_MODEL_DAILY=my-dep out="$(ak ZAI_CODING_API_KEY=fake-zai-one -- claude-glm -c)" diff --git a/tests/scopes/profiles.sh b/tests/scopes/profiles.sh index 541ade5..004d771 100644 --- a/tests/scopes/profiles.sh +++ b/tests/scopes/profiles.sh @@ -171,11 +171,11 @@ scope_profiles() { "opencode|XDG_DATA_HOME=@DIR/data|--continue" "opencode-azure|XDG_DATA_HOME=@DIR/data|-m|azure/dep-daily|--continue" "opencode-xai|XDG_DATA_HOME=@DIR/data|-m|xai/grok-4.3|--continue" - "opencode-glm|XDG_DATA_HOME=@DIR/data|-m|zai-coding-plan/glm-5.3|--continue" + "opencode-glm|XDG_DATA_HOME=@DIR/data|-m|zai-coding-plan/glm-5.4|--continue" "pi|PI_CODING_AGENT_DIR=@DIR|--continue" "pi-azure|PI_CODING_AGENT_DIR=@DIR|--provider|azure-foundry|--model|dep-daily|--models|azure-foundry/dep-daily|--continue" "pi-xai|PI_CODING_AGENT_DIR=@DIR|--provider|xai-grok|--model|grok-4.3|--models|xai-grok/grok-4.3,xai-grok/grok-4.6|--continue" - "pi-glm|PI_CODING_AGENT_DIR=@DIR|--provider|zai-glm|--model|glm-5.3|--models|zai-glm/glm-5.3,zai-glm/glm-5.3-flash|--continue" + "pi-glm|PI_CODING_AGENT_DIR=@DIR|--provider|zai-glm|--model|glm-5.4|--models|zai-glm/glm-5.4,zai-glm/glm-5.3-flash|--continue" "cline|CLINE_DIR=@DIR|--id|sess-new" "cline-azure|CLINE_DIR=@DIR|-P|openai|-m|dep-daily|-k|fake-azure-@KEY|--id|sess-new" "cline-xai|CLINE_DIR=@DIR|-P|openai|-m|grok-4.3|-k|fake-xai-@KEY|--id|sess-new" From 52c6bacdf03e788c5103303375ecd14c92f2af19 Mon Sep 17 00:00:00 2001 From: Sergio Alexander Florez Galeano Date: Sat, 28 Nov 2026 09:19:44 -0500 Subject: [PATCH 07/11] docs(security): list the per-run session record and the Herdr server id Co-Authored-By: Claude Opus 5.5 --- docs/SECURITY.md | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/docs/SECURITY.md b/docs/SECURITY.md index 3fa2b5b..35c08ca 100644 --- a/docs/SECURITY.md +++ b/docs/SECURITY.md @@ -155,7 +155,9 @@ profile and its headroom, nothing else. never read a reading that old, so no account is chosen on it. - **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, a process id and the host's name — never a key, a + They hold names, a directory, times, a process id, the host's name and an + opaque id of the Herdr server (a hash of its socket path, never the path) — + 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 @@ -261,7 +263,7 @@ 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`, `fanout//` (a fan-out run's record and its lanes' transcripts and, by default, their worktrees), `launches.json` (per working directory: the kind, profile and posture of the last interactive launch, for `ak last`), `sessions/-