benignswarm 0.12.164 → 0.12.166

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
File without changes
@@ -6,7 +6,7 @@ import { basename, delimiter, dirname, isAbsolute, join, resolve, sep } from "no
6
6
  import { configRoot } from "./config.js";
7
7
  import { repoDirectory } from "./directories.js";
8
8
  import { CliError } from "./errors.js";
9
- import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
9
+ import { gitSandboxDeniedPaths, gitSandboxReadablePaths, gitSandboxWorktreeMetadataPath, gitSandboxWritablePaths, sandboxProbeWorktreeAdminPath } from "./git-sandbox-paths.js";
10
10
  export const ANTIGRAVITY_SETTINGS_PLACEHOLDER = "__B9S_ANTIGRAVITY_TURN_SETTINGS__";
11
11
  export function isAntigravityWorkspaceWrite(env = process.env) {
12
12
  return env.BSCHAT_HARNESS === "antigravity" && env.BSCHAT_ANTIGRAVITY_SANDBOX === "workspace-write";
@@ -87,6 +87,7 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
87
87
  throw new CliError("sandbox_root_too_broad", "Antigravity workspace-write refuses a writable root that contains the checkout or home directory; configure the exact writable folder instead");
88
88
  }
89
89
  const additionalCheckouts = unitWorktree ? [{ label: `WU #${unitWorktree.number} worktree`, path: unitWorktree.path }] : [];
90
+ const unitWorktreeMetadata = unitWorktree ? gitSandboxWorktreeMetadataPath(unitWorktree.path) : null;
90
91
  const gitPaths = gitSandboxWritablePaths(absoluteCwd, additionalCheckouts);
91
92
  const gitReadPaths = gitSandboxReadablePaths(absoluteCwd, additionalCheckouts);
92
93
  const exactGitFiles = new Set(["packed-refs", "packed-refs.lock", "FETCH_HEAD", "FETCH_HEAD.lock", "HEAD", "HEAD.lock", "index", "index.lock", "COMMIT_EDITMSG"]);
@@ -115,7 +116,11 @@ export function antigravitySettings(sandbox, cwd, b9sHome, apiHost, extraWritabl
115
116
  return [
116
117
  "--sandbox", "--settings",
117
118
  JSON.stringify({ enableTerminalSandbox: true, toolPermission: "proceed-in-sandbox", permissions: { allow, deny } }),
118
- ...beside.flatMap((dir) => ["--add-dir", dir]),
119
+ ...[...new Set([
120
+ ...beside,
121
+ ...(unitWorktree ? [resolve(unitWorktree.path)] : []),
122
+ ...(unitWorktreeMetadata ? [unitWorktreeMetadata] : []),
123
+ ])].flatMap((dir) => ["--add-dir", dir]),
119
124
  ];
120
125
  }
121
126
  export function antigravityTurnArgs(prompt, model, effort, timeoutSeconds, settings, conversation) {
@@ -214,6 +219,7 @@ export function runAntigravityTurn(bin, args, logPath, cwd, agent, expectedConve
214
219
  exit_code: result.status,
215
220
  ...(expectedConversation ? { expected_conversation: expectedConversation } : {}),
216
221
  ...(model ? { model } : {}),
222
+ ...(effort ? { effort } : {}),
217
223
  ...(parsed ? { result: parsed } : { raw: [output, result.stderr].filter(Boolean).join("\n").slice(-4000) }),
218
224
  };
219
225
  recordAntigravityTurn(logPath, record);
@@ -228,8 +234,8 @@ export function antigravityResumeCommand(bin, session, model, effort, timeoutSec
228
234
  const tmp = `${logPath}.pending`;
229
235
  const err = `${logPath}.stderr`;
230
236
  const base = [bin, "-p", "{text}", "--output-format", "json", "--model", model, ...(effort ? ["--effort", effort] : []), "--print-timeout", `${timeoutSeconds}s`, "--conversation", session, ...settings].map((arg) => arg === "{text}" ? arg : shq(arg)).join(" ");
231
- const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
232
- const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)}`;
237
+ const script = `const fs=require('node:fs');const [tmp,err,log,status,started,expected,model,effort]=process.argv.slice(1);const raw=fs.readFileSync(tmp,'utf8');const stderr=fs.readFileSync(err,'utf8');let result;try{result=JSON.parse(raw)}catch{}const record={started_at:started,finished_at:new Date().toISOString(),exit_code:Number(status),expected_conversation:expected,model,...(effort?{effort}:{}),...(result?{result}:{raw:(raw+'\\n'+stderr).slice(-4000)})};fs.appendFileSync(log,JSON.stringify(record)+'\\n',{mode:0o600});fs.rmSync(tmp,{force:true});fs.rmSync(err,{force:true});`;
238
+ const node = `${shq(process.execPath)} -e ${shq(script)} ${shq(tmp)} ${shq(err)} ${shq(logPath)} "$agy_status" "$agy_started" ${shq(session)} ${shq(model)} ${shq(effort ?? "")}`;
233
239
  return `agy_started=$(date -u +%Y-%m-%dT%H:%M:%SZ); ${base} > ${shq(tmp)} 2> ${shq(err)}; agy_status=$?; ${node}; exit "$agy_status"`;
234
240
  }
235
241
  function agyRecords(path) {
package/dist/args.js CHANGED
@@ -8,7 +8,7 @@ export const LIST_FLAGS = [
8
8
  "reworks", "confirm-causes", "processes", "cache", "caches", "root", "signing-key", "machines",
9
9
  ];
10
10
  export const STRING_FLAGS = [
11
- "as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task",
11
+ "as", "admin", "key", "url", "label", "level", "model", "since", "limit", "after", "topic", "goal", "task",
12
12
  "state", "blocked-on", "tags", "custom", "vendor", "role", "description", "permissions",
13
13
  "cardinality", "assign-outside-qualifications", "judges", "machine", "idempotency-key", "dir", "confirm", "impact-revision", "type",
14
14
  "name", "out", "token", "token-file", "job", "gate-command", "gate-override-note", "head", "baseline", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to",
@@ -23,7 +23,7 @@ export const STRING_FLAGS = [
23
23
  "require-pushed", "require-gate-receipt", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email",
24
24
  "repeat", "summary-minutes", "quota-share-threshold", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on",
25
25
  "flow-summary", "flow-min-age", "flow-min-impact", "checkout", "unit-worktree", "sibling-checkout", "api", "nonce",
26
- "sandbox", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
26
+ "sandbox", "subagents", "subagent-model", "thread", "turn-timeout", "turns-per-hour", "unproductive-per-hour", "turn-coalesce-seconds", "session", "operation",
27
27
  "plain", "if-yes", "if-no", "ssh", "variant", "count", "min", "max", "needs", "min-ram", "exclude", "carry", "from",
28
28
  "to-ssh", "ssh-from", "wait", "writable", "writable-root", "dsh", "agy", "for", "until", "reason", "at", "requires", "with",
29
29
  "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect",
@@ -35,9 +35,9 @@ export const STRING_FLAGS = [
35
35
  "stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
36
36
  "machine-session-id", "harness-binary", "pool-sessions", "registry", "detail", "worktree", "turn-claude-runtime", "turn-antigravity-runtime",
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
- "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
38
+ "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route", "intent", "brief", "brief-file",
39
39
  "expires-at", "conflicts-with", "source-channel-id", "source-message-id", "plain-summary",
40
- "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
40
+ "choices", "choice", "metadata-file", "confirm-agent", "confirm-parked", "step", "compare", "merge-candidate", "outcome",
41
41
  ];
42
42
  export const BOOL_FLAGS = [
43
43
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
@@ -63,6 +63,8 @@ export function parse(argv) {
63
63
  // replacement command needs its value. Resolve that spelling by command.
64
64
  if (argv[0] === "wu" && argv[1] === "reviewer")
65
65
  options.replace = { type: "string" };
66
+ if ((argv[0] === "mock" || argv[0] === "design-study") && argv[1] === "gaps")
67
+ options.json = { type: "string" };
66
68
  try {
67
69
  const seen = new Set();
68
70
  const negativeBooleans = new Set();
@@ -441,7 +441,7 @@ function processAlive(pid) {
441
441
  }
442
442
  }
443
443
  /** Computes total logical size and most recent modification time under a directory without following symlinks. */
444
- function measurePath(target) {
444
+ export function measurePath(target) {
445
445
  let bytes = 0;
446
446
  let mtimeMs = 0;
447
447
  const stack = [target];
package/dist/client.js CHANGED
@@ -2,6 +2,7 @@ import { createHash } from "node:crypto";
2
2
  import { CliError, WrittenReceiptMismatchError } from "./errors.js";
3
3
  import { collectAuto, machineIdentityForAgent } from "./git.js";
4
4
  import { resolveEffort } from "./model.js";
5
+ import { readState, updateState } from "./state.js";
5
6
  import { cliUserAgent } from "./legacy-alias.js";
6
7
  import { noteServerVersions } from "./update.js";
7
8
  function expectedTextReceiptFields(method, path, body, response) {
@@ -153,9 +154,9 @@ function expectedTextReceiptFields(method, path, body, response) {
153
154
  if (verb === "POST" && /^\/projects\/[^/]+\/locks\/[^/]+\/acquire$/.test(route))
154
155
  return strings("note");
155
156
  if (verb === "POST" && /^\/projects\/[^/]+\/ask-operator$/.test(route))
156
- return strings("text", "blocks", "proposal", "plain", "if_yes", "if_no");
157
+ return strings("text", "decision", "blocks", "proposal", "plain", "if_yes", "if_no");
157
158
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/amend$/.test(route))
158
- return strings("text", "plain", "blocks", "if_yes", "if_no", "proposal");
159
+ return strings("text", "decision", "plain", "blocks", "if_yes", "if_no", "proposal");
159
160
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/withdraw$/.test(route))
160
161
  return strings("note");
161
162
  if (verb === "POST" && /^\/projects\/[^/]+\/asks\/[^/]+\/explanation$/.test(route))
@@ -364,8 +365,14 @@ export class Client {
364
365
  * by the hook or the watcher, which say nothing about whether the agent is alive.
365
366
  */
366
367
  static forAgent(c, model, opts = {}) {
367
- const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort: resolveEffort(opts.effort, process.env, c.vendor), provider: process.env.BSCHAT_PROVIDER });
368
- return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null);
368
+ const ref = `${c.project ?? "account"}/${c.agent}`;
369
+ const observedEffort = c.vendor === "antigravity" ? readState(ref).effort ?? null : null;
370
+ const effort = resolveEffort(opts.effort, process.env, c.vendor, process.cwd(), observedEffort);
371
+ if (c.vendor === "antigravity" && effort !== "unknown" && (opts.effort || process.env.BSCHAT_EFFORT) && effort !== observedEffort) {
372
+ updateState(ref, (state) => ({ ...state, effort, effort_observed_at: Date.now() }));
373
+ }
374
+ const auto = collectAuto({ model, machine: machineIdentityForAgent(c.machine), effort, provider: process.env.BSCHAT_PROVIDER, harness: c.vendor });
375
+ return new Client(c.url, c.key, opts.presence === false ? null : { ...auto }, c.agent, opts.machineIdentity ? auto.machine : null, { requestTimeoutMs: opts.requestTimeoutMs, retryForMs: opts.retryForMs, onRequest: opts.onRequest });
369
376
  }
370
377
  static forAdmin(c) {
371
378
  return new Client(c.url, c.key, null);
@@ -377,14 +384,14 @@ export class Client {
377
384
  const signals = [this.requestOptions.signal, external].filter((signal) => Boolean(signal));
378
385
  return signals.length > 1 ? AbortSignal.any(signals) : signals[0];
379
386
  }
380
- requestSignal(external) {
387
+ requestSignal(external, timeoutMs = this.requestOptions.requestTimeoutMs) {
381
388
  const callerSignal = this.callerSignal(external);
382
- const timeout = this.requestOptions.requestTimeoutMs ? AbortSignal.timeout(this.requestOptions.requestTimeoutMs) : undefined;
389
+ const timeout = timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined;
383
390
  const signals = [callerSignal, timeout].filter((signal) => Boolean(signal));
384
391
  return { signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0], timeout };
385
392
  }
386
- timeoutError(method, path) {
387
- return new CliError("request_timeout", `${method} ${path} timed out after ${this.requestOptions.requestTimeoutMs}ms`);
393
+ timeoutError(method, path, timeoutMs = this.requestOptions.requestTimeoutMs) {
394
+ return new CliError("request_timeout", `${method} ${path} timed out after ${timeoutMs}ms`);
388
395
  }
389
396
  headers(autoOverride) {
390
397
  const h = { authorization: `Bearer ${this.key}`, "user-agent": cliUserAgent() };
@@ -417,11 +424,10 @@ export class Client {
417
424
  return response;
418
425
  }
419
426
  /**
420
- * opts.retries: how many times to retry on a network failure or a 5xx for callers that opt in
421
- * (safe for idempotent calls such as client_id or lock job_token). Without opts.retries,
422
- * GET/HEAD retry plain 5xx and rejected fetches up to DEFAULT_OVERLOAD_RETRIES (5) times,
423
- * transient overload/gateway responses (503/502/504/service_overloaded) retry up to 5 times,
424
- * and non-idempotent POST 500 stays fail-fast even when marked retryable.
427
+ * opts.retries opts an idempotent request into a fixed number of retries. retryForMs (or the
428
+ * client-level equivalent) opts it into bounded-window retries, including per-attempt timeouts.
429
+ * Without either opt-in, GET/HEAD and transient overload/gateway responses retain the
430
+ * platform-wide bounded retry policy; non-idempotent POST 500 remains fail-fast.
425
431
  */
426
432
  async call(method, path, body, opts = {}) {
427
433
  const headers = this.headers(opts.auto);
@@ -433,30 +439,61 @@ export class Client {
433
439
  const overloadRetries = Math.max(explicitRetries, DEFAULT_OVERLOAD_RETRIES);
434
440
  const sleep = opts.sleepFn ?? sleepWithAbort;
435
441
  const retrySignal = this.callerSignal(opts.signal);
442
+ const retryWindowMs = opts.retryForMs ?? this.requestOptions.retryForMs;
443
+ let retryWindowSpentMs = 0;
444
+ const remainingRetryWindowMs = () => retryWindowMs === undefined ? Number.POSITIVE_INFINITY : retryWindowMs - retryWindowSpentMs;
445
+ const canRetry = (attempt, maxAttempts) => retryWindowMs === undefined ? attempt < maxAttempts : remainingRetryWindowMs() > 0;
446
+ const waitBeforeRetry = async (attempt, retryAfterSeconds) => {
447
+ let delayMs = computeBackoffMs(attempt, retryAfterSeconds);
448
+ if (retryWindowMs !== undefined) {
449
+ const remainingMs = remainingRetryWindowMs();
450
+ if (remainingMs <= 1)
451
+ return false;
452
+ // Reserve at least one millisecond for the next attempt; if that attempt fails,
453
+ // the next wait sees the exhausted deadline and stops without another retry.
454
+ delayMs = Math.min(delayMs, Math.max(0, remainingMs - 1));
455
+ }
456
+ if (delayMs > 0)
457
+ await sleep(delayMs, retrySignal);
458
+ retryWindowSpentMs += delayMs;
459
+ return retryWindowMs === undefined || remainingRetryWindowMs() > 0;
460
+ };
436
461
  for (let attempt = 0;; attempt++) {
437
462
  let res;
438
463
  let text;
439
464
  const startedAt = Date.now();
440
- const { signal, timeout } = this.requestSignal(opts.signal);
441
- this.requestOptions.onRequest?.({ phase: "start", method, path });
465
+ const configuredTimeoutMs = opts.requestTimeoutMs ?? this.requestOptions.requestTimeoutMs;
466
+ const remainingRetryMs = remainingRetryWindowMs();
467
+ const requestTimeoutMs = retryWindowMs === undefined
468
+ ? configuredTimeoutMs
469
+ : Math.max(1, Math.min(configuredTimeoutMs ?? 30_000, remainingRetryMs));
470
+ const { signal, timeout } = this.requestSignal(opts.signal, requestTimeoutMs);
471
+ const requestPath = path.split("?", 1)[0] ?? path;
472
+ this.requestOptions.onRequest?.({ phase: "start", method, path: requestPath, attempt: attempt + 1 });
442
473
  try {
443
474
  res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
444
475
  text = await res.text();
445
476
  }
446
477
  catch (e) {
447
- this.requestOptions.onRequest?.({ phase: "end", method, path, durationMs: Date.now() - startedAt, error: timeout?.aborted ? "timeout" : e.message });
448
- if (timeout?.aborted)
449
- throw this.timeoutError(method, path);
478
+ retryWindowSpentMs += Date.now() - startedAt;
479
+ const failure = timeout?.aborted ? "timeout" : e.message;
480
+ const networkRetries = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : isRead ? overloadRetries : explicitRetries;
481
+ const willRetry = canRetry(attempt, networkRetries);
482
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (network error)${willRetry ? "; retrying" : "; retry window exhausted"}\n`);
483
+ this.requestOptions.onRequest?.({ phase: "end", method, path: requestPath, attempt: attempt + 1, durationMs: Date.now() - startedAt, error: failure });
450
484
  if (this.requestOptions.signal?.aborted || opts.signal?.aborted)
451
485
  throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
452
- const networkRetries = isRead ? overloadRetries : explicitRetries;
453
- if (attempt < networkRetries) {
454
- await sleep(computeBackoffMs(attempt), retrySignal);
486
+ if (willRetry && await waitBeforeRetry(attempt))
455
487
  continue;
456
- }
488
+ if (timeout?.aborted)
489
+ throw this.timeoutError(method, path, requestTimeoutMs);
490
+ if (retrySignal?.aborted)
491
+ throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
457
492
  throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
458
493
  }
459
- this.requestOptions.onRequest?.({ phase: "end", method, path, durationMs: Date.now() - startedAt });
494
+ retryWindowSpentMs += Date.now() - startedAt;
495
+ const requestFailure = !res.ok && res.status >= 500 ? `http_${res.status}` : undefined;
496
+ this.requestOptions.onRequest?.({ phase: "end", method, path: requestPath, attempt: attempt + 1, durationMs: Date.now() - startedAt, ...(requestFailure ? { error: requestFailure } : {}) });
460
497
  noteServerVersions(res.headers, this.agentName);
461
498
  let json;
462
499
  try {
@@ -464,28 +501,35 @@ export class Client {
464
501
  }
465
502
  catch {
466
503
  const transient = isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers);
467
- const maxAttempts = transient ? overloadRetries : explicitRetries;
468
- if (res.status >= 500 && attempt < maxAttempts) {
469
- const delayMs = computeBackoffMs(attempt, parseRetryAfterSeconds(res.headers.get("retry-after")));
470
- process.stderr.write(`b9s: ${method} ${path} failed (${res.status}); retrying in ${Math.round(delayMs / 1000)}s\n`);
471
- await sleep(delayMs, retrySignal);
472
- continue;
504
+ const maxAttempts = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : transient ? overloadRetries : explicitRetries;
505
+ if (res.status >= 500 && canRetry(attempt, maxAttempts)) {
506
+ const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after"));
507
+ const retrying = await waitBeforeRetry(attempt, retryAfter);
508
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure})${retrying ? "; retrying" : "; retry window exhausted"}\n`);
509
+ if (retrying)
510
+ continue;
511
+ }
512
+ if (!res.ok && res.status >= 500) {
513
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure}); retry window exhausted\n`);
514
+ throw new CliError(`http_${res.status}`, `${method} ${path} failed (${res.status}): ${text.slice(0, 200)}`, undefined, res.status);
473
515
  }
474
516
  throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
475
517
  }
476
518
  if (!res.ok) {
477
519
  // Explicit opts.retries marks idempotent POST callers (e.g. client_id / lock job_token);
478
520
  // default POST calls without opts.retries stay fail-fast on 500 even if marked retryable.
479
- const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0;
521
+ const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0 && retryWindowMs === undefined;
480
522
  const transient = isTransientOverloadResponse(res.status, json, text, isRead, res.headers);
481
- const maxAttempts = transient ? overloadRetries : explicitRetries;
482
- if (res.status >= 500 && !nonIdempotentPost500 && attempt < maxAttempts) {
523
+ const maxAttempts = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : transient ? overloadRetries : explicitRetries;
524
+ if (res.status >= 500 && !nonIdempotentPost500 && canRetry(attempt, maxAttempts)) {
483
525
  const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
484
- const delayMs = computeBackoffMs(attempt, retryAfter);
485
- process.stderr.write(`b9s: ${method} ${path} failed (${res.status}${json?.reference ? `, reference ${json.reference}` : ""}); retrying in ${Math.round(delayMs / 1000)}s (${attempt + 1}/${maxAttempts})\n`);
486
- await sleep(delayMs, retrySignal);
487
- continue;
526
+ const retrying = await waitBeforeRetry(attempt, retryAfter);
527
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure})${retrying ? "; retrying" : "; retry window exhausted"}\n`);
528
+ if (retrying)
529
+ continue;
488
530
  }
531
+ if (requestFailure)
532
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure}); retry window exhausted\n`);
489
533
  const err = json;
490
534
  const hint = res.status >= 500
491
535
  ? `This is a platform failure, not something to fix on your side. Do not retry in a loop. Report it once: b9s feedback "<what you were doing>${err.reference ? ` ref ${err.reference}` : ""}" and carry on with other work.`
@@ -604,8 +648,11 @@ export function computeBackoffMs(attempt, retryAfterSeconds, random = Math.rando
604
648
  function sleepWithAbort(ms, signal) {
605
649
  if (signal?.aborted)
606
650
  return Promise.reject(new CliError("request_aborted", "request aborted during retry backoff"));
607
- const testCap = Number(process.env.B9S_TEST_RETRY_SLEEP_MS);
608
- const actualMs = Number.isFinite(testCap) && testCap > 0 ? Math.min(ms, testCap) : ms;
651
+ const rawCap = process.env.B9S_TEST_RETRY_SLEEP_MS;
652
+ const testCap = rawCap !== undefined && rawCap !== "" ? Number(rawCap) : NaN;
653
+ const actualMs = Number.isFinite(testCap) && testCap >= 0 ? Math.min(ms, testCap) : ms;
654
+ if (actualMs <= 0)
655
+ return Promise.resolve();
609
656
  return new Promise((resolve, reject) => {
610
657
  const onAbort = () => {
611
658
  clearTimeout(timer);
@@ -1,10 +1,10 @@
1
1
  import { CliError } from "./errors.js";
2
2
  const AGENT_GLOBAL_FLAGS = new Set(["as", "effort", "help", "json", "model", "version"]);
3
3
  const ADMIN_GLOBAL_FLAGS = new Set(["admin", "as", "help", "json", "version"]);
4
- const OPTION_CONTRACT_ALIASES = new Map([["ask", "ask-operator"]]);
4
+ const OPTION_CONTRACT_ALIASES = new Map([["ask", "ask-operator"], ["design-study", "mock"]]);
5
5
  const INHERITED_OPTION_CONTRACTS = new Map([["codex start", ["start"]]]);
6
6
  const PROJECT_COMMANDS = new Set([
7
- "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
7
+ "mock", "design-study", "flow-agent", "notice", "who", "send", "read", "channel", "agents", "activity", "feed", "evidence", "retire", "handoffs", "lists", "list", "item",
8
8
  "wu", "process", "record", "milestones", "milestone", "lock", "unlock", "locks", "ask", "ask-operator",
9
9
  "explain", "worktrees", "measures", "measure", "environment", "test-results", "ux", "gate",
10
10
  ]);
@@ -21,12 +21,15 @@ import { flowAdmin } from "./flow.js";
21
21
  import { projectSecrets } from "./project-secrets.js";
22
22
  import { standingRuleAdmin } from "./standing-rules.js";
23
23
  import { diagAdmin } from "./diag-admin.js";
24
+ import { mockAdmin } from "./mock-admin.js";
24
25
  function adminClient(p) {
25
26
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
26
27
  }
27
28
  export async function admin(p, out) {
28
29
  const [, group, action, ...rest] = p.positionals;
29
30
  switch (group) {
31
+ case "mock":
32
+ return mockAdmin(action, rest, p, adminClient(p), out);
30
33
  case "login": {
31
34
  const url = (str(p.flags, "url") ?? process.env.BSCHAT_URL ?? DEFAULT_URL).replace(/\/$/, "");
32
35
  if (str(p.flags, "key") === undefined)
@@ -14,7 +14,7 @@ import { readState, updateState } from "../state.js";
14
14
  import { join } from "./join.js";
15
15
  import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService, parseWorkUnitBindingResponse, prepareTurnWorktree, preparedWorktreePromptLines, resolveWatcherWorkUnitBinding, turnArgs, watch } from "./watch.js";
16
16
  import { randomUUID } from "node:crypto";
17
- import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
17
+ import { HARNESS_BIN, HARNESS_LABEL, assertClaudeSelfCheck, claudeCodePath, claudeResultError, claudeResultFile, claudeSandboxEnv, claudeSettings, claudeSubagentModelEnv, claudeTranscript, claudeTurnArgs, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, inspectCurrentClaudeEgressCapability, probeFor } from "../harnesses.js";
18
18
  import { allocateClaudeEgressPortPair, resolveTrustedControlPlaneOrigin, spawnClaudeEgressSupervised } from "../claude-egress-proxy.js";
19
19
  import { claudeTurnEnv } from "../providers.js";
20
20
  import { DEFAULT_TURNS_PER_HOUR, DEFAULT_UNPRODUCTIVE_PER_HOUR, MAX_TURNS_PER_HOUR } from "../turn-guard.js";
@@ -26,6 +26,22 @@ import { checkAndRecordHarnessBinary } from "../machine-binary.js";
26
26
  import { clearSessionSecrets, normalizeAndValidateSecretHosts, parseSecretHostsJson, parseSecretKeyNamesJson, SECRET_DECLARED_HOSTS_VAR, SECRET_EGRESS_ENV_KEYS_VAR, wipeSecretMap, writeSessionSecrets, } from "../session-secrets.js";
27
27
  const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
28
28
  export const DEFAULT_CLAUDE_MAX_BUDGET_USD = 1;
29
+ const SUBAGENT_MODES = ["default", "encourage", "disabled"];
30
+ export function subagentStartupHint(harness, mode, model) {
31
+ const modeIsAdvisory = (mode === "encourage" && harness !== "codex")
32
+ || (mode === "disabled" && harness !== "claude-code" && harness !== "codex");
33
+ const modelIsAdvisory = Boolean(model && harness !== "claude-code");
34
+ if (!modeIsAdvisory && !modelIsAdvisory)
35
+ return null;
36
+ const instructions = [];
37
+ if (modeIsAdvisory && mode === "disabled")
38
+ instructions.push("do not delegate to subagents");
39
+ if (modeIsAdvisory && mode === "encourage")
40
+ instructions.push("use native subagents for cleanly separable subtasks when useful, parallelize research or disjoint files, then integrate and verify the result yourself");
41
+ if (modelIsAdvisory)
42
+ instructions.push(`prefer subagent model ${model} when the harness supports it`);
43
+ return `Advisory only; this harness does not enforce this subagent preference: ${instructions.join("; ")}.`;
44
+ }
29
45
  /** The guard states why it refuses. A refusal without a reason is still a refusal (no turn starts) and is reported as the defect it is. */
30
46
  function refusalReason(diagnostic) {
31
47
  return diagnostic.at(-1) ?? "the turn guard refused this turn without stating why; that is a CLI defect, report it with b9s feedback";
@@ -123,6 +139,13 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
123
139
  const name = str(p.flags, "as");
124
140
  if (!name)
125
141
  throw new CliError("usage", `${cmd} needs --as <agent-name>`);
142
+ const subagentsValue = str(p.flags, "subagents") ?? "default";
143
+ if (!SUBAGENT_MODES.includes(subagentsValue))
144
+ throw new CliError("usage", "--subagents must be default, encourage, or disabled");
145
+ const subagents = subagentsValue;
146
+ const subagentModel = str(p.flags, "subagent-model");
147
+ if (subagentModel !== undefined && (!subagentModel.trim() || subagentModel.length > 100))
148
+ throw new CliError("usage", "--subagent-model must be a non-empty model identifier of at most 100 characters");
126
149
  const machineSessionId = str(p.flags, "machine-session-id");
127
150
  if (machineSessionId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(machineSessionId))
128
151
  throw new CliError("usage", "--machine-session-id must be a UUID");
@@ -242,12 +265,12 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
242
265
  const writable = startWritableRoots(sandbox, machineWritable, explicitWritable);
243
266
  // Refuses a sandbox the harness cannot honour before anything is enrolled.
244
267
  const preflightSettings = harness === "codex"
245
- ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
268
+ ? codexSettings(sandbox, model, effort, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())], subagents)
246
269
  : harness === "dsh"
247
270
  ? dshSettings(sandbox, process.cwd(), configRoot(), [...writable, ...ownWorktreeGitDir(process.cwd())])
248
- : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable) : [];
271
+ : harness === "claude-code" ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, undefined, subagents) : [];
249
272
  let settings = preflightSettings;
250
- const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}) };
273
+ const providerEnv = { ...claudeTurnEnv(harness === "claude-code" ? provider : undefined, model), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "claude-code" ? claudeSubagentModelEnv(subagentModel) : {}) };
251
274
  // 1. Who: enroll with the invite token, or use credentials already on this machine.
252
275
  const lines = [];
253
276
  const token = str(p.flags, "token");
@@ -284,7 +307,7 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
284
307
  httpProxyPort,
285
308
  socksProxyPort,
286
309
  };
287
- settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, claudeSecretEgress);
310
+ settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, undefined, claudeSecretEgress, subagents);
288
311
  }
289
312
  if (harness === "antigravity") {
290
313
  if (inContainer)
@@ -381,11 +404,11 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
381
404
  const onboardingUnit = onboardingWorktree ? { number: onboardingWorktree.number, path: onboardingWorktree.path } : undefined;
382
405
  const onboardingCwd = onboardingWorktree?.path ?? process.cwd();
383
406
  const onboardingPreflightSettings = harness === "claude-code" && sandbox === "workspace-write" && onboardingUnit
384
- ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit)
407
+ ? claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, undefined, subagents)
385
408
  : preflightSettings;
386
409
  if (onboardingUnit) {
387
410
  if (harness === "claude-code") {
388
- settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, claudeSecretEgress);
411
+ settings = claudeSettings(sandbox, model, effort, process.cwd(), configRoot(), writable, onboardingUnit, claudeSecretEgress, subagents);
389
412
  }
390
413
  else if (harness === "antigravity") {
391
414
  settings = antigravitySettings(sandbox, process.cwd(), configRoot(), new URL(creds.url).host, [...writable, onboardingUnit.path], install.bin, process.execPath, ref, onboardingUnit);
@@ -405,6 +428,7 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
405
428
  `Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
406
429
  `Now: run \`b9s me\`, \`b9s process\` and \`b9s inbox --unread\`, then do what your role and inbox ask.`,
407
430
  `If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
431
+ ...(subagentStartupHint(harness, subagents, subagentModel) ? [subagentStartupHint(harness, subagents, subagentModel)] : []),
408
432
  ...(onboardingWorktree ? preparedWorktreePromptLines(onboardingWorktree, "b9s start") : []),
409
433
  ].join("\n");
410
434
  const diagnostic = [];
@@ -489,9 +513,9 @@ export async function harnessStart(p, out, harness, dependencies = {}) {
489
513
  mkdirSync(tmp, { recursive: true });
490
514
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
491
515
  const prune = bool(p.flags, "prune");
492
- watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
516
+ watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? { ...claudeSandboxEnv(sandbox), ...claudeSubagentModelEnv(subagentModel) } : {}), ...(harness === "antigravity" ? { ...antigravityTurnEnv(sandbox, install.bin, antigravityTmp), ...(antigravityTmpSessionKey ? { BSCHAT_ANTIGRAVITY_TMP_SESSION_KEY: antigravityTmpSessionKey } : {}), BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
493
517
  const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model,
494
- ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd, ...(claudeSecretEgress ? { secretEgress: { declaredHosts: claudeSecretEgress.declaredHosts, apiUrl: creds.url, envKeys: incomingSecretKeys, ...(!inContainer && secretSessionKey ? { sessionKey: secretSessionKey } : {}) } } : {}) } } : {}),
518
+ ...(harness === "claude-code" && sandbox === "workspace-write" ? { claudeRuntime: { sandbox, ...(effort ? { effort } : {}), writableRoots: writable, maxBudgetUsd, subagents, ...(subagentModel ? { subagentModel } : {}), ...(claudeSecretEgress ? { secretEgress: { declaredHosts: claudeSecretEgress.declaredHosts, apiUrl: creds.url, envKeys: incomingSecretKeys, ...(!inContainer && secretSessionKey ? { sessionKey: secretSessionKey } : {}) } } : {}) } } : {}),
495
519
  ...(harness === "antigravity" && sandbox === "workspace-write" ? { antigravityRuntime: { sandbox, apiHost: new URL(creds.url).host, b9sBin: install.bin, nodeBin: process.execPath, writableRoots: writable, tmpSessionKey: antigravityTmpSessionKey, tmpDir: antigravityTmp } } : {}),
496
520
  ...(machineSessionId ? { machineSessionId } : {}) };
497
521
  if (inContainer && claudeSecretEgress) {
@@ -865,10 +889,11 @@ export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, se
865
889
  * the API and write its own b9s state (~/.b9s), and `wu start` puts unit worktrees beside the
866
890
  * checkout, so those two places are writable and the network is on; nothing else is.
867
891
  */
868
- export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = []) {
892
+ export function codexSettings(sandbox, model, effort, cwd, bschatHome, extraWritable = [], subagents = "default") {
869
893
  return [
870
894
  ...(model ? ["-m", model] : []),
871
895
  ...(effort ? ["-c", `model_reasoning_effort="${effort}"`] : []),
896
+ ...(subagents === "disabled" ? ["-c", "features.multi_agent=false"] : subagents === "encourage" ? ["-c", "features.multi_agent=true", "-c", "agents.max_depth=1"] : []),
872
897
  "-c", `sandbox_mode="${sandbox}"`,
873
898
  "-c", `approval_policy="never"`,
874
899
  ...(sandbox === "workspace-write"
@@ -0,0 +1,88 @@
1
+ import { str } from "../args.js";
2
+ import { Client } from "../client.js";
3
+ import { loadAgent, resolveAgentName, loadAdmin, resolveAdminName } from "../config.js";
4
+ import { CliError } from "../errors.js";
5
+ import { projectOf } from "./agent.js";
6
+ export const FLOW_AGENT_LEVELS = ["advisory", "flow_ops", "autonomous_ops"];
7
+ const MAY = {
8
+ advisory: [
9
+ "Read the board, units, statuses and the merge train.",
10
+ "Post a structured diagnosis and a proposal in chat: what is stuck, why, and the one change that would move it.",
11
+ "Mutating unit, routing or pool endpoints are refused at this level; do not try them.",
12
+ ],
13
+ flow_ops: [
14
+ "Everything advisory may do.",
15
+ "Reassign a stalled unit's owner, replace a quiet or non-approving reviewer.",
16
+ "Clear a wait that has resolved, unpark a ready unit, enqueue an approved unit on the merge train.",
17
+ "Remove one false --after edge, naming the edge and giving a reason; keep the others.",
18
+ ],
19
+ autonomous_ops: [
20
+ "Everything flow_ops may do.",
21
+ "Set priority or expedite within the project's urgent_cap.",
22
+ "Split or rebalance a unit within the configured split bounds; a split child carries the registered split relationship.",
23
+ ],
24
+ };
25
+ /** The parameterized system prompt for one autonomy level. Pure, so it is tested per level. */
26
+ export function flowAgentPrompt(level, limits) {
27
+ const may = MAY[level].map((line) => `- ${line}`).join("\n");
28
+ return `You are this project's Flow Agent, at autonomy level ${level}.
29
+ Your job is flow: keep work moving through the process without doing the work, the review or the merge yourself.
30
+
31
+ Hard invariants (every level; the server refuses these with 403):
32
+ - Never approve a unit, request changes, or close one as done.
33
+ - Never lift an operator hold.
34
+ - Never touch billing, authentication or production data.
35
+ - Never change or exceed operator-owned per-session-hour, per-account-day, turns-per-hour, or per-turn limits.
36
+
37
+ At ${level} you may:
38
+ ${may}
39
+
40
+ Flow Agent action cap: at most ${limits.max_actions_per_hour} actions per hour. Account budget caps are shared with unattended turns and are owned by the operator: ${limits.account_day_tokens === null ? "no account-day token cap" : `${limits.account_day_tokens.toLocaleString()} tokens`} · ${limits.account_day_cost_micros === null ? "no account-day cost cap" : `$${(limits.account_day_cost_micros / 1_000_000).toFixed(4)}`}. Check b9s flow-agent status before acting. If the account budget is disabled, unconfigured, or reached, stop and hold for the operator.
41
+
42
+ Operating loop, once per wake-up:
43
+ 1. Read the triggers in the wake-up message, then b9s flow-agent status.
44
+ 2. For each trigger, look at the unit or chain it names (b9s wu show <n>) and decide whether anything is actually stuck.
45
+ 3. Take the smallest action your level allows that unblocks it, with a reason a person can follow; otherwise post the diagnosis and the proposal.
46
+ 4. Do not repeat an action the status shows you already took for the same situation.
47
+ 5. End the turn with one chat message listing what you did and what you left for others.`;
48
+ }
49
+ export async function flowAgent(p, out) {
50
+ const sub = p.positionals[1];
51
+ if (sub !== "status" && sub !== "prompt" && sub !== "run")
52
+ throw new CliError("usage", "flow-agent status | flow-agent prompt [--level advisory|flow_ops|autonomous_ops]");
53
+ if (sub === "run") {
54
+ const project = str(p.flags, "project") ?? process.env.BSCHAT_PROJECT ?? projectOf(p, loadAgent(resolveAgentName(str(p.flags, "as"))));
55
+ const client = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
56
+ const result = await client.call("POST", `/projects/${encodeURIComponent(project)}/flow-agent/run`, { force: p.flags.force === true });
57
+ out.print("Flow Agent run requested.", result);
58
+ return;
59
+ }
60
+ const creds = loadAgent(resolveAgentName(str(p.flags, "as")));
61
+ if (!creds.project)
62
+ throw new CliError("usage", "flow-agent needs a project agent; account agents pass --project <name>");
63
+ const project = creds.project;
64
+ const client = Client.forAgent(creds, str(p.flags, "model"));
65
+ const s = await client.call("GET", `/projects/${project}/flow-agent/status`);
66
+ if (sub === "status") {
67
+ const recent = (s.recent_actions ?? []);
68
+ const budget = s.account_budget;
69
+ const tokenCap = budget.account_day_tokens === null ? "unconfigured" : `${budget.tokens_counted.toLocaleString()}/${budget.account_day_tokens.toLocaleString()} tokens`;
70
+ const costCap = budget.account_day_cost_micros === null ? "unconfigured" : `$${(budget.cost_micros_counted / 1_000_000).toFixed(4)}/$${(budget.account_day_cost_micros / 1_000_000).toFixed(4)}`;
71
+ const lines = [
72
+ `flow agent: ${s.enabled ? "enabled" : "disabled"} · ${s.autonomy_level}`,
73
+ `actions this hour: ${s.actions_this_hour}/${s.max_actions_per_hour}`,
74
+ `account budget · rolling 24h: ${budget.enabled ? `${tokenCap} · ${costCap}` : "disabled"}${budget.reached ? " · held" : ""} · ${budget.pending_count} pending · ${budget.uncertain_count} uncertain`,
75
+ `last run: ${s.last_run_at ?? "never"}`,
76
+ ...recent.slice(0, 10).map((a) => ` ${a.at} ${a.kind}${a.unit_number === null ? "" : ` #${a.unit_number}`}${a.outcome ? ` (${a.outcome})` : ""}: ${a.summary}`),
77
+ ];
78
+ out.print(lines.join("\n"), s);
79
+ return;
80
+ }
81
+ const requested = str(p.flags, "level");
82
+ if (requested !== undefined && !FLOW_AGENT_LEVELS.includes(requested))
83
+ throw new CliError("usage", `--level must be one of ${FLOW_AGENT_LEVELS.join(", ")}`);
84
+ const level = (requested ?? s.autonomy_level);
85
+ const budget = s.account_budget;
86
+ const text = flowAgentPrompt(level, { ...budget, max_actions_per_hour: s.max_actions_per_hour });
87
+ out.print(text, { autonomy_level: level, enabled: s.enabled, prompt: text });
88
+ }
@@ -54,6 +54,11 @@ function flowText(snapshot) {
54
54
  lines.push("State counts: " + ["held", "blocked_on_dependency", "changes_requested", "in_review", "approved_waiting_to_merge", "in_progress", "assigned_not_started", "waiting_on_person", "ready", "starved", "unknown"].map((key) => `${key}=${show(counts[key])}`).join(" "));
55
55
  if (counts.eligibility_coverage)
56
56
  lines.push(` eligibility: ${counts.eligibility_coverage}`);
57
+ const agentSummary = record(snapshot.agent_summary);
58
+ if (Object.keys(agentSummary).length) {
59
+ const states = record(agentSummary.states);
60
+ lines.push(`Agent utilization: ${agentSummary.utilization == null ? "unavailable (no working, idle, or waiting agents)" : `${Math.round(agentSummary.utilization * 100)}% working`} · working ${show(states.working)}, idle ${show(states.idle)}, waiting ${show(states.waiting)}, not responding ${show(states.not_responding)} faults, away ${show(states.away)}, benched ${show(agentSummary.benched_agent_count)}`);
61
+ }
57
62
  const units = record(snapshot.units), items = list(units.items);
58
63
  lines.push(`Open units: ${show(units.total_open)} total; ${items.length} shown${units.next_cursor ? `; next page: ${units.next_cursor}` : ""}`);
59
64
  for (const itemValue of items) {