benignswarm 0.12.163 → 0.12.165

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.
@@ -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",
@@ -37,7 +37,7 @@ export const STRING_FLAGS = [
37
37
  "purpose", "storage-mode", "hosts", "arn", "version-id", "kms-key",
38
38
  "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class", "route",
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) {
@@ -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);
@@ -373,15 +380,18 @@ export class Client {
373
380
  static raw(url, key, requestOptions = {}) {
374
381
  return new Client(url, key, null, undefined, null, requestOptions);
375
382
  }
376
- requestSignal(external) {
383
+ callerSignal(external) {
377
384
  const signals = [this.requestOptions.signal, external].filter((signal) => Boolean(signal));
378
- const timeout = this.requestOptions.requestTimeoutMs ? AbortSignal.timeout(this.requestOptions.requestTimeoutMs) : undefined;
379
- if (timeout)
380
- signals.push(timeout);
385
+ return signals.length > 1 ? AbortSignal.any(signals) : signals[0];
386
+ }
387
+ requestSignal(external, timeoutMs = this.requestOptions.requestTimeoutMs) {
388
+ const callerSignal = this.callerSignal(external);
389
+ const timeout = timeoutMs ? AbortSignal.timeout(timeoutMs) : undefined;
390
+ const signals = [callerSignal, timeout].filter((signal) => Boolean(signal));
381
391
  return { signal: signals.length > 1 ? AbortSignal.any(signals) : signals[0], timeout };
382
392
  }
383
- timeoutError(method, path) {
384
- 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`);
385
395
  }
386
396
  headers(autoOverride) {
387
397
  const h = { authorization: `Bearer ${this.key}`, "user-agent": cliUserAgent() };
@@ -414,63 +424,124 @@ export class Client {
414
424
  return response;
415
425
  }
416
426
  /**
417
- * opts.retries: how many times to retry on a network failure or a 5xx. Only safe for calls
418
- * that are idempotent on the server (posts carry a client_id for exactly this reason).
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.
419
431
  */
420
432
  async call(method, path, body, opts = {}) {
421
433
  const headers = this.headers(opts.auto);
422
434
  if (body !== undefined)
423
435
  headers["content-type"] = "application/json";
424
- const retries = opts.retries ?? 0;
436
+ const upperMethod = method.toUpperCase();
437
+ const isRead = upperMethod === "GET" || upperMethod === "HEAD";
438
+ const explicitRetries = opts.retries ?? 0;
439
+ const overloadRetries = Math.max(explicitRetries, DEFAULT_OVERLOAD_RETRIES);
440
+ const sleep = opts.sleepFn ?? sleepWithAbort;
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
+ };
425
461
  for (let attempt = 0;; attempt++) {
426
462
  let res;
427
463
  let text;
428
464
  const startedAt = Date.now();
429
- const { signal, timeout } = this.requestSignal(opts.signal);
430
- 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 });
431
473
  try {
432
474
  res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
433
475
  text = await res.text();
434
476
  }
435
477
  catch (e) {
436
- this.requestOptions.onRequest?.({ phase: "end", method, path, durationMs: Date.now() - startedAt, error: timeout?.aborted ? "timeout" : e.message });
437
- if (timeout?.aborted)
438
- 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 });
439
484
  if (this.requestOptions.signal?.aborted || opts.signal?.aborted)
440
485
  throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
441
- if (attempt < retries) {
442
- await backoff(attempt);
486
+ if (willRetry && await waitBeforeRetry(attempt))
443
487
  continue;
444
- }
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`);
445
492
  throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
446
493
  }
447
- 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 } : {}) });
448
497
  noteServerVersions(res.headers, this.agentName);
449
498
  let json;
450
499
  try {
451
500
  json = JSON.parse(text);
452
501
  }
453
502
  catch {
503
+ const transient = isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers);
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);
515
+ }
454
516
  throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
455
517
  }
456
518
  if (!res.ok) {
457
- if (res.status >= 500 && attempt < retries) {
458
- process.stderr.write(`b9s: ${method} ${path} failed (${res.status}${json?.reference ? `, reference ${json.reference}` : ""}); retrying\n`);
459
- await backoff(attempt);
460
- continue;
519
+ // Explicit opts.retries marks idempotent POST callers (e.g. client_id / lock job_token);
520
+ // default POST calls without opts.retries stay fail-fast on 500 even if marked retryable.
521
+ const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500 && explicitRetries === 0 && retryWindowMs === undefined;
522
+ const transient = isTransientOverloadResponse(res.status, json, text, isRead, res.headers);
523
+ const maxAttempts = retryWindowMs !== undefined ? Number.POSITIVE_INFINITY : transient ? overloadRetries : explicitRetries;
524
+ if (res.status >= 500 && !nonIdempotentPost500 && canRetry(attempt, maxAttempts)) {
525
+ const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
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;
461
530
  }
531
+ if (requestFailure)
532
+ process.stderr.write(`b9s: ${method} ${requestPath} attempt ${attempt + 1} failed (${requestFailure}); retry window exhausted\n`);
462
533
  const err = json;
463
534
  const hint = res.status >= 500
464
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.`
465
536
  : undefined;
466
537
  throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint, res.status);
467
538
  }
468
- const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
539
+ const allowsRedactedExcerpt = upperMethod === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
469
540
  try {
470
541
  verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : [], expectedStoredText(method, path, body, json));
471
542
  }
472
543
  catch (error) {
473
- if (res.status >= 200 && res.status < 300 && error instanceof CliError && !["GET", "HEAD"].includes(method.toUpperCase())) {
544
+ if (res.status >= 200 && res.status < 300 && error instanceof CliError && !isRead) {
474
545
  throw new WrittenReceiptMismatchError(json, error);
475
546
  }
476
547
  throw error;
@@ -479,31 +550,57 @@ export class Client {
479
550
  }
480
551
  }
481
552
  /** Like call(), but returns HTTP status and parsed JSON even for 4xx responses (such as preflight or drain conflicts). */
482
- async callWithStatus(method, path, body) {
553
+ async callWithStatus(method, path, body, opts = {}) {
483
554
  const headers = this.headers();
484
555
  if (body !== undefined)
485
556
  headers["content-type"] = "application/json";
486
- let res;
487
- try {
488
- res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
489
- }
490
- catch (e) {
491
- throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
492
- }
493
- noteServerVersions(res.headers, this.agentName);
494
- const text = await res.text();
495
- let json;
496
- try {
497
- json = JSON.parse(text);
498
- }
499
- catch {
500
- throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
501
- }
502
- if (res.status >= 500) {
503
- const err = json;
504
- throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, undefined, res.status);
557
+ const upperMethod = method.toUpperCase();
558
+ const isRead = upperMethod === "GET" || upperMethod === "HEAD";
559
+ const sleep = opts.sleepFn ?? sleepWithAbort;
560
+ const retrySignal = this.callerSignal(opts.signal);
561
+ for (let attempt = 0;; attempt++) {
562
+ let res;
563
+ let text;
564
+ const { signal, timeout } = this.requestSignal(opts.signal);
565
+ try {
566
+ res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal });
567
+ text = await res.text();
568
+ }
569
+ catch (e) {
570
+ if (timeout?.aborted)
571
+ throw this.timeoutError(method, path);
572
+ if (retrySignal?.aborted)
573
+ throw new CliError("request_aborted", `${method} ${path} aborted before completion`);
574
+ if (isRead && attempt < DEFAULT_OVERLOAD_RETRIES) {
575
+ await sleep(computeBackoffMs(attempt), retrySignal);
576
+ continue;
577
+ }
578
+ throw new CliError("network", `could not reach ${this.url}: ${e.message}`);
579
+ }
580
+ noteServerVersions(res.headers, this.agentName);
581
+ let json;
582
+ try {
583
+ json = JSON.parse(text);
584
+ }
585
+ catch {
586
+ if (isTransientOverloadResponse(res.status, undefined, text, isRead, res.headers) && attempt < DEFAULT_OVERLOAD_RETRIES) {
587
+ await sleep(computeBackoffMs(attempt, parseRetryAfterSeconds(res.headers.get("retry-after"))), retrySignal);
588
+ continue;
589
+ }
590
+ throw new CliError("bad_response", `${method} ${path} returned non-JSON (${res.status}): ${text.slice(0, 200)}`);
591
+ }
592
+ if (res.status >= 500) {
593
+ const nonIdempotentPost500 = upperMethod === "POST" && res.status === 500;
594
+ if (!nonIdempotentPost500 && isTransientOverloadResponse(res.status, json, text, isRead, res.headers) && attempt < DEFAULT_OVERLOAD_RETRIES) {
595
+ const retryAfter = parseRetryAfterSeconds(res.headers.get("retry-after")) ?? (typeof json?.retry_after === "number" ? json.retry_after : undefined);
596
+ await sleep(computeBackoffMs(attempt, retryAfter), retrySignal);
597
+ continue;
598
+ }
599
+ const err = json;
600
+ throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, undefined, res.status);
601
+ }
602
+ return { status: res.status, ok: res.ok, json: json };
505
603
  }
506
- return { status: res.status, ok: res.ok, json: json };
507
604
  }
508
605
  wsUrl(path) {
509
606
  return this.url.replace(/^http/, "ws") + path;
@@ -514,6 +611,57 @@ export class Client {
514
611
  return ws;
515
612
  }
516
613
  }
517
- function backoff(attempt) {
518
- return new Promise((r) => setTimeout(r, Math.min(8000, 500 * 2 ** attempt)));
614
+ export const DEFAULT_OVERLOAD_RETRIES = 5;
615
+ export function isTransientOverloadResponse(status, json, _text, isRead, headers) {
616
+ if (isRead && status >= 500)
617
+ return true;
618
+ if (status === 502 || status === 504)
619
+ return true;
620
+ if (json?.error === "service_overloaded")
621
+ return true;
622
+ if (status === 503 && (json?.retryable === true || Boolean(headers?.get("retry-after"))))
623
+ return true;
624
+ return false;
625
+ }
626
+ export function parseRetryAfterSeconds(header) {
627
+ if (!header)
628
+ return undefined;
629
+ const trimmed = header.trim();
630
+ if (/^\d+(?:\.\d+)?$/.test(trimmed)) {
631
+ const n = Number(trimmed);
632
+ return Number.isFinite(n) && n >= 0 ? n : undefined;
633
+ }
634
+ const dateMs = Date.parse(trimmed);
635
+ if (Number.isFinite(dateMs)) {
636
+ return Math.max(0, (dateMs - Date.now()) / 1000);
637
+ }
638
+ return undefined;
639
+ }
640
+ export function computeBackoffMs(attempt, retryAfterSeconds, random = Math.random) {
641
+ const expBase = Math.min(15_000, 1000 * 2 ** attempt);
642
+ const floorMs = retryAfterSeconds !== undefined && Number.isFinite(retryAfterSeconds)
643
+ ? Math.max(expBase, Math.min(30_000, Math.round(retryAfterSeconds * 1000)))
644
+ : expBase;
645
+ const jitter = Math.round(floorMs * 0.3 * Math.max(0, Math.min(1, random())));
646
+ return Math.min(30_000, floorMs + jitter);
647
+ }
648
+ function sleepWithAbort(ms, signal) {
649
+ if (signal?.aborted)
650
+ return Promise.reject(new CliError("request_aborted", "request aborted during retry backoff"));
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();
656
+ return new Promise((resolve, reject) => {
657
+ const onAbort = () => {
658
+ clearTimeout(timer);
659
+ reject(new CliError("request_aborted", "request aborted during retry backoff"));
660
+ };
661
+ const timer = setTimeout(() => {
662
+ signal?.removeEventListener("abort", onAbort);
663
+ resolve();
664
+ }, actualMs);
665
+ signal?.addEventListener("abort", onAbort, { once: true });
666
+ });
519
667
  }
@@ -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
  ]);
@@ -168,7 +168,7 @@ export async function status(p, out) {
168
168
  const { client, creds } = agentClient(p);
169
169
  if (sub === "set") {
170
170
  const body = {};
171
- for (const k of ["goal", "task", "state", "blocked-on"]) {
171
+ for (const k of ["goal", "task", "state", "blocked-on", "blocked-kind", "blocked-ref"]) {
172
172
  const v = str(p.flags, k);
173
173
  if (v !== undefined)
174
174
  body[k.replace("-", "_")] = v === "" ? null : v;
@@ -195,7 +195,7 @@ export async function status(p, out) {
195
195
  throw new CliError("usage", "--checks-every takes whole minutes (1 to 1440), or none to clear it");
196
196
  }
197
197
  if (!Object.keys(body).length)
198
- throw new CliError("usage", "status set needs at least one of --state --goal --task --blocked-on --tags --custom --checks-every");
198
+ throw new CliError("usage", "status set needs at least one of --state --goal --task --blocked-on --blocked-kind --blocked-ref --tags --custom --checks-every");
199
199
  const r = await client.call("PUT", creds.project ? `/projects/${creds.project}/agents/me/status` : "/agents/me/status", body);
200
200
  out.print(fmtStatus(r.status), r);
201
201
  return;
@@ -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"