benignswarm 0.12.90 → 0.12.92

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.
@@ -34,7 +34,7 @@ function omitMeasuresAlreadyIn(text, updates) {
34
34
  }
35
35
  /** Reports host probes without refreshing the agent's presence; the host identity is still explicit. */
36
36
  export async function reportWatcherCapabilities(creds, project, definitions, cwd = process.cwd()) {
37
- const results = probeCapabilities(definitions, cwd);
37
+ const results = await probeCapabilities(definitions, cwd);
38
38
  await Client.forAgent(creds, undefined, { presence: false, machineIdentity: true }).call("POST", `/projects/${project}/agents/me/capabilities`, { results });
39
39
  }
40
40
  /**
@@ -96,7 +96,8 @@ export async function watch(p, out) {
96
96
  throw new CliError("usage", "--provider must be anthropic or deepseek");
97
97
  if (providerName === "deepseek" && harness !== "claude-code")
98
98
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
99
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model: str(p.flags, "model") };
99
+ const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
100
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model };
100
101
  }
101
102
  else if (p.flags.provider !== undefined) {
102
103
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -245,7 +246,7 @@ export async function watch(p, out) {
245
246
  try {
246
247
  if (probe)
247
248
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
248
- const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" && turn.provider === "deepseek" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn);
249
+ const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined);
249
250
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
250
251
  }, name, turn?.turnsPerHour ?? turnsPerHour);
251
252
  else {
@@ -334,7 +335,7 @@ async function waitIntervalOrStop(ms, stopped) {
334
335
  if (timer)
335
336
  clearTimeout(timer);
336
337
  }
337
- async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn) {
338
+ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId) {
338
339
  const state = readState(name);
339
340
  const pending = state.watch_pending;
340
341
  if (pending) {
@@ -421,7 +422,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
421
422
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
422
423
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
423
424
  const line = wake;
424
- if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, undefined, allowTurn)))
425
+ if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { sessionId }, allowTurn)))
425
426
  return { sent: false, recoveryBriefDelivered: false };
426
427
  writeState(name, {
427
428
  ...readState(name),
@@ -452,7 +453,7 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
452
453
  return true;
453
454
  }
454
455
  const cmd = exec.replaceAll("{count}", String(total)).replaceAll("{summary}", shellQuote(summary)).replaceAll("{text}", turnStdin ? "-" : shellQuote(wake));
455
- const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total) };
456
+ const env = { BSCHAT_TEXT: wake, BSCHAT_SUMMARY: summary, BSCHAT_COUNT: String(total), ...(model ? { BSCHAT_MODEL: model } : {}) };
456
457
  if (turnSink) {
457
458
  // The turn runs in the background; turnStep follows it, acknowledges it once the session shows
458
459
  // it started, and reports how it ended.
@@ -460,11 +461,19 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
460
461
  // The agent's own b9s calls in the turn know who they are without any repo file.
461
462
  // Provider credentials are read only when spawning the turn and are never persisted in the
462
463
  // launchd/systemd service or its command line.
463
- const providerEnv = claudeTurnEnv(provider, model, dependencies.providerRoot);
464
+ const turnModel = model ?? (provider === "deepseek" ? "deepseek-flash" : undefined);
465
+ const providerEnv = claudeTurnEnv(provider, turnModel, dependencies.providerRoot);
464
466
  if (allowTurn && !(await allowTurn()))
465
467
  return false;
466
468
  beforeTurn?.();
467
- turnSink((dependencies.startTurn ?? startTurn)(cmd, { ...env, BSCHAT_AGENT: name, ...providerEnv }, seq, turnStdin ? wake : undefined));
469
+ turnSink((dependencies.startTurn ?? startTurn)(cmd, {
470
+ ...env,
471
+ BSCHAT_AGENT: name,
472
+ ...(turnModel ? { BSCHAT_MODEL: turnModel } : {}),
473
+ ...(dependencies.sessionId ? { BSCHAT_SESSION_ID: dependencies.sessionId } : {}),
474
+ ...(provider ? { BSCHAT_PROVIDER: provider } : {}),
475
+ ...providerEnv,
476
+ }, seq, turnStdin ? wake : undefined));
468
477
  }
469
478
  else {
470
479
  log(`${prefix}[${tier}] queueing wake-up: ${summary}`);
@@ -522,17 +531,19 @@ const KEY_CHECK_MS = 5 * 60_000;
522
531
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
523
532
  * broken; one that runs past --turn-timeout is stopped and logged.
524
533
  */
525
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR) {
534
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env) {
526
535
  const turn = ctl.turn;
527
536
  if (turn) {
528
537
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
529
538
  turn.confirmed = true;
530
- await ackTurn(name, turn.seq, log);
539
+ await ackTurn(name, turn.seq, log, env);
531
540
  log(`turn #${turn.seq} started in the session; wake-up acknowledged`);
532
541
  }
533
542
  if (turn.exit) {
534
543
  const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
535
544
  const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
545
+ if (turn.stdinError)
546
+ log(`turn #${turn.seq}: ${turn.stdinError}`);
536
547
  // A harness may exit 0 with an error in its result (Claude Code's is_error), so both count.
537
548
  let error = null;
538
549
  if (!turn.killedForTimeout) {
@@ -545,7 +556,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
545
556
  }
546
557
  if (turn.exit.code === 0 && !error) {
547
558
  if (!turn.confirmed)
548
- await ackTurn(name, turn.seq, log);
559
+ await ackTurn(name, turn.seq, log, env);
549
560
  log(`turn #${turn.seq} finished after ${mins} min`);
550
561
  }
551
562
  else if (turn.killedForTimeout) {
@@ -564,11 +575,11 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
564
575
  log(`TURN #${turn.seq} FAILED (${how}) after ${mins} min${turn.confirmed ? "" : "; it never started in the session, so the wake-up stays unacknowledged"}${error ? `; ${probe.label} said: ${error}` : ""}${probe.isLimit(error) ? ` (a usage limit with no reset time named)` : ""}. Next turn in 5 min at the earliest; its output is in this log.`);
565
576
  }
566
577
  if (!turn.confirmed)
567
- writeState(name, { ...readState(name), watch_pending: undefined, watch_dormant_logged_at: undefined });
578
+ writeState(name, { ...readState(name, env), watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
568
579
  ctl.failedAt = Date.now();
569
580
  }
570
581
  ctl.turn = null;
571
- await completePendingTurnGuard(name, probe, log);
582
+ await completePendingTurnGuard(name, probe, log, undefined, env);
572
583
  return;
573
584
  }
574
585
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
@@ -578,7 +589,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
578
589
  return;
579
590
  }
580
591
  // b9s unpause: the operator switched the harness to an account with quota.
581
- const unpausedAt = readState(name).turn_unpaused_at ?? 0;
592
+ const unpausedAt = readState(name, env).turn_unpaused_at ?? 0;
582
593
  if (ctl.pausedUntil > Date.now() && unpausedAt > ctl.pausedAt) {
583
594
  log(`usage-limit pause lifted by b9s unpause`);
584
595
  ctl.pausedUntil = 0;
@@ -592,23 +603,23 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
592
603
  // running by a watcher that restarted (turns run in their own process group and outlive it).
593
604
  // Never start a second one.
594
605
  const ph = probe.phase();
595
- const savedGuard = readState(name).turn_guard;
606
+ const savedGuard = readState(name, env).turn_guard;
596
607
  if (savedGuard?.fault) {
597
608
  log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
598
609
  return;
599
610
  }
600
611
  if ("missing" in ph) {
601
612
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
602
- await completePendingTurnGuard(name, probe, log);
603
- if (readState(name).turn_guard?.fault)
613
+ await completePendingTurnGuard(name, probe, log, undefined, env);
614
+ if (readState(name, env).turn_guard?.fault)
604
615
  return;
605
616
  }
606
617
  log(ph.missing);
607
618
  return;
608
619
  }
609
620
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
610
- await completePendingTurnGuard(name, probe, log);
611
- if (readState(name).turn_guard?.fault)
621
+ await completePendingTurnGuard(name, probe, log, undefined, env);
622
+ if (readState(name, env).turn_guard?.fault)
612
623
  return;
613
624
  }
614
625
  if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
@@ -633,7 +644,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
633
644
  }
634
645
  // A turn that started before this machine last booted died with it: no process survives a
635
646
  // reboot, and waiting out the quiet limit would idle the agent for up to --turn-timeout.
636
- const bootedAt = Date.now() - uptime() * 1000;
647
+ const bootedAt = ph.running ? Date.now() - uptime() * 1000 : 0;
637
648
  if (ph.running && ph.startedAt && Date.parse(ph.startedAt) < bootedAt) {
638
649
  if (ctl.loggedRunning !== `boot:${ph.startedAt}`)
639
650
  log(`the turn started at ${ph.startedAt} was cut off when this machine restarted (booted ${new Date(bootedAt).toISOString()}); treating it as ended`);
@@ -660,47 +671,50 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
660
671
  ctl.loggedRunning = ph.startedAt;
661
672
  }
662
673
  // A maintenance window on this machine: no new turn from 15 min before it until it ends.
663
- const maint = drainingUntil();
674
+ const maint = drainingUntil(undefined, undefined, env);
664
675
  if (maint) {
665
676
  if (ctl.loggedRunning !== `maint:${maint.start}`)
666
677
  log(`maintenance on this machine ${maint.start.slice(0, 16)} to ${maint.end.slice(11, 16)} UTC: starting no new turns until it ends`);
667
678
  ctl.loggedRunning = `maint:${maint.start}`;
668
679
  return;
669
680
  }
670
- const st = readState(name);
681
+ const st = readState(name, env);
671
682
  if (st.watch_pending) {
672
683
  // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
673
684
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
674
- writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
685
+ writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
675
686
  }
676
687
  await wake((t) => { ctl.turn = t; }, async () => {
677
- return beginTurnGuardAttempt(name, turnsPerHour, log);
688
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env);
678
689
  });
679
690
  }
680
- async function turnActivity(name) {
681
- const snapshot = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
691
+ async function turnActivity(name, env) {
692
+ const snapshot = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
682
693
  if (!Number.isInteger(snapshot.activity_seq) || snapshot.activity_seq < 0)
683
694
  throw new Error("server returned an invalid turn activity sequence");
684
695
  return snapshot;
685
696
  }
686
697
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
687
- export async function beginTurnGuardAttempt(name, turnsPerHour, log) {
688
- const before = await turnActivity(name);
689
- const current = readState(name);
698
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env) {
699
+ const before = await turnActivity(name, env);
700
+ const current = readState(name, env);
690
701
  if (current.turn_guard?.fault) {
691
702
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
692
703
  return false;
693
704
  }
694
705
  const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
695
- writeState(name, { ...current, turn_guard: begun.state });
706
+ writeState(name, { ...current, turn_guard: begun.state }, env);
696
707
  if (!begun.start) {
697
708
  log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
698
709
  return false;
699
710
  }
700
711
  return true;
701
712
  }
702
- export async function completePendingTurnGuard(name, probe, log, outputOverride) {
703
- const current = readState(name);
713
+ export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverrideOrEnv, envOverride = process.env) {
714
+ // The watcher passes its isolated environment; start-turn callers may pass measured tokens.
715
+ const env = tokenOverrideOrEnv !== null && typeof tokenOverrideOrEnv === "object" ? tokenOverrideOrEnv : envOverride;
716
+ const tokenOverride = tokenOverrideOrEnv === null || typeof tokenOverrideOrEnv === "number" ? tokenOverrideOrEnv : undefined;
717
+ const current = readState(name, env);
704
718
  const guard = current.turn_guard;
705
719
  const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
706
720
  if (!guard || !pending || pending.activity_seq_before === undefined)
@@ -708,7 +722,7 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride)
708
722
  let activitySeq = pending.activity_seq_before;
709
723
  let sampleError = null;
710
724
  try {
711
- activitySeq = (await turnActivity(name)).activity_seq;
725
+ activitySeq = (await turnActivity(name, env)).activity_seq;
712
726
  }
713
727
  catch (e) {
714
728
  sampleError = `could not verify the agent's BenignSwarm activity: ${e.message}`;
@@ -733,16 +747,20 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride)
733
747
  }
734
748
  else
735
749
  output = outputOverride;
736
- try {
737
- directTokens = probe.turnTokens?.() ?? null;
738
- }
739
- catch (e) {
740
- sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
741
- }
750
+ if (tokenOverride !== undefined)
751
+ directTokens = tokenOverride;
752
+ else
753
+ try {
754
+ directTokens = probe.turnTokens?.() ?? null;
755
+ }
756
+ catch (e) {
757
+ sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
758
+ }
742
759
  output = (output || error || sampleError || "").slice(-800);
743
760
  const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
744
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null);
745
- writeState(name, { ...current, turn_guard: nextGuard });
761
+ const tokenCount = tokenOverride !== undefined ? tokenOverride : directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null;
762
+ const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount);
763
+ writeState(name, { ...current, turn_guard: nextGuard }, env);
746
764
  if (!productive)
747
765
  log(`turn made no agent-key call to BenignSwarm (${nextGuard.consecutive_unproductive}/${MAX_UNPRODUCTIVE_TURNS} consecutive); ${nextGuard.fault ? `FAULT: ${turnFaultSummary(nextGuard.fault)}` : `last output: ${output || "(empty)"}`}`);
748
766
  else if (nextGuard.consecutive_unproductive === 0)
@@ -752,10 +770,10 @@ function turnFaultSummary(fault) {
752
770
  return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
753
771
  }
754
772
  /** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
755
- async function ackTurn(name, seq, log) {
756
- writeState(name, applyAck(readState(name), seq).next);
773
+ async function ackTurn(name, seq, log, env = process.env) {
774
+ writeState(name, applyAck(readState(name, env), seq).next, env);
757
775
  try {
758
- await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
776
+ await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", "/agents/me/wake/ack", { seq });
759
777
  }
760
778
  catch (e) {
761
779
  log(`could not report the acknowledgement of turn #${seq} to the server: ${e.message}`);
@@ -5,11 +5,15 @@ import { Client } from "../client.js";
5
5
  import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
6
6
  import { readState } from "../state.js";
7
7
  import { codexRollout, sessionsOf } from "../sessions.js";
8
- import { sessionUsage } from "../usage.js";
8
+ import { sessionUsage, watcherClaudeUsage } from "../usage.js";
9
9
  import { CliError } from "../errors.js";
10
10
  import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, removeWorktreeIfClean, repoName, repoParent, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
11
11
  import { resolve } from "node:path";
12
12
  import { table } from "../output.js";
13
+ /** Only Claude's workspace-write sandbox needs SSH origins rewritten for its HTTP-only proxy. */
14
+ export function shouldInheritClaudeSandboxUrlRewrites(env = process.env) {
15
+ return env.CLAUDECODE === "1" && env.BSCHAT_CLAUDE_SANDBOX === "workspace-write";
16
+ }
13
17
  export function scopeEditFromArgs(p) {
14
18
  const replacement = bool(p.flags, "replace");
15
19
  const append = str(p.flags, "append");
@@ -267,14 +271,19 @@ export async function wu(p, out) {
267
271
  }
268
272
  const to = str(p.flags, "to");
269
273
  const reason = str(p.flags, "reason");
274
+ const allowLowerTier = bool(p.flags, "allow-lower-tier");
275
+ if (allowLowerTier && (!reason?.trim() || reason.trim().length > 1000))
276
+ throw new CliError("usage", '--allow-lower-tier requires --reason "why this lower-tier assignment is needed" (up to 1000 characters)');
277
+ if (allowLowerTier && (to === "auto" || to === "queue"))
278
+ throw new CliError("usage", "--allow-lower-tier applies only when naming an agent");
270
279
  if (!to)
271
280
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
272
281
  const existingNumber = Number(p.positionals[2]);
273
282
  if (Number.isInteger(existingNumber) && existingNumber > 0 && p.positionals.length === 3) {
274
283
  if (p.flags.after !== undefined)
275
284
  throw new CliError("usage", "--after applies when creating a unit; use b9s wu wait to change an existing unit's wait");
276
- const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }) });
277
- out.print(fmt(r.unit), r);
285
+ const r = await client.call("POST", `${base}/${existingNumber}/assign`, { to, ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
286
+ out.print(`${fmt(r.unit)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}`, r);
278
287
  return;
279
288
  }
280
289
  const title = p.positionals.slice(2).join(" ").trim();
@@ -282,8 +291,29 @@ export async function wu(p, out) {
282
291
  throw new CliError("usage", 'wu assign "<title>" --to <agent|auto|queue> --scope "<what it covers and does not>" [--scope-file <path> | --scope-from <n>] [--tags a,b] [--after <n>[,<m>]] [--tier routine|careful|expert] [--evidence id] [--replay-of <n>]');
283
292
  const scope = await scopeText();
284
293
  const replay = str(p.flags, "replay-of");
285
- const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }) });
286
- out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
294
+ const r = await client.call("POST", `${base}/assign`, { to, title, scope, tags: unitTags, requires: list("requires"), evidence: list("evidence"), after: afterUnits(), replay_of: replay ? Number(replay) : null, reworks: list("reworks").map(Number), branch: str(p.flags, "branch") ?? null, target: str(p.flags, "target") ?? null, milestone: str(p.flags, "milestone") ?? null, min_tier: str(p.flags, "tier"), hold: !!p.flags.hold, force: bool(p.flags, "force"), ...(reason === undefined ? {} : { reason }), ...(allowLowerTier ? { allow_lower_tier: true } : {}) });
295
+ out.print(`${fmt(r.unit)}\n${assignmentDisposition(r.unit, to)}${allowLowerTier ? `\nLower-tier override reason supplied: ${reason.trim()}` : ""}${r.warnings?.length ? `\nScope warnings:\n${r.warnings.map((w) => `- ${w}`).join("\n")}` : ""}`, r);
296
+ return;
297
+ }
298
+ case "park": {
299
+ const note = str(p.flags, "note");
300
+ if (!note?.trim())
301
+ throw new CliError("usage", 'wu park <n> --note "why this unit is being parked"');
302
+ const r = await client.call("POST", `${base}/${num()}/park`, { note: note.trim() });
303
+ out.print(`${fmt(r.unit)}\nParked; ${r.unit.owner_name} keeps the unit and branch, and its in-progress slot is free.`, r);
304
+ return;
305
+ }
306
+ case "unpark": {
307
+ const r = await client.call("POST", `${base}/${num()}/unpark`, {});
308
+ out.print(`${fmt(r.unit)}\nUnparked; the owner can continue it.`, r);
309
+ return;
310
+ }
311
+ case "requeue": {
312
+ const note = str(p.flags, "note");
313
+ if (!note?.trim())
314
+ throw new CliError("usage", 'wu requeue <n> --note "why this assigned unit is returning to the queue"');
315
+ const r = await client.call("POST", `${base}/${num()}/requeue`, { note: note.trim() });
316
+ out.print(`${fmt(r.unit)}\nReturned to the queue; branch and event history were kept.`, r);
287
317
  return;
288
318
  }
289
319
  case "take": {
@@ -421,7 +451,7 @@ export async function wu(p, out) {
421
451
  const approve = sub === "rule" && bool(p.flags, "approve");
422
452
  const text = (p.positionals.slice(3).join(" ") || str(p.flags, sub === "ask" ? "question" : "ruling") || str(p.flags, "note") || "").trim();
423
453
  if (!text && !approve)
424
- throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without"' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
454
+ throw new CliError("usage", sub === "ask" ? 'wu ask <n> "the decision this unit cannot move without" (works on queued units too)' : 'wu rule <n> "what was decided" | wu rule <n> --approve [--note ".."]');
425
455
  const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : approve ? { approve: true, ruling: text } : { ruling: text });
426
456
  const q = r.unit.question;
427
457
  out.print(`${fmt(r.unit)}\n${sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
@@ -783,7 +813,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
783
813
  branchCreated = true;
784
814
  log(`created ${pinned} from origin/${pinned}`);
785
815
  }
786
- const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude) : { created: false };
816
+ const result = !existing ? ensureWorktree(path, pinned, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites()) : { created: false };
787
817
  return { mode: "branch", path, branch: pinned, created: result.created, branchCreated };
788
818
  }
789
819
  const slug = String(unit.title).toLowerCase().replace(/[^a-z0-9]+/g, "-").replace(/^-|-$/g, "").slice(0, 40);
@@ -797,7 +827,7 @@ function prepareWorktree(n, unit, def, p, exclude = []) {
797
827
  baseRef = at;
798
828
  }
799
829
  const branchCreated = fullSha(branch) === null;
800
- const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude);
830
+ const result = ensureWorktree(path, branch, baseRef, process.cwd(), log, exclude, shouldInheritClaudeSandboxUrlRewrites());
801
831
  return { mode: "fresh", path, branch, created: result.created, branchCreated };
802
832
  }
803
833
  /** Select the replay commit from the same target ref used to create its worktree. */
@@ -1082,14 +1112,20 @@ async function roundUsage(client, base, n, name) {
1082
1112
  return { harness: "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read the unit's timeline: ${e.message}` };
1083
1113
  }
1084
1114
  let session = readState(name).harness_session;
1085
- if (!session) {
1086
- // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1087
- const ref = agentRef(loadAgent(name));
1088
- const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1089
- if (rollout)
1090
- session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1091
- }
1092
1115
  try {
1116
+ // Turn-mode watchers bind the session id they were configured to resume. Prefer that exact
1117
+ // transcript over any older hook binding left by another Claude Code session on this machine.
1118
+ if (process.env.BSCHAT_SESSION_ID) {
1119
+ const provider = process.env.BSCHAT_PROVIDER;
1120
+ return watcherClaudeUsage(process.env.BSCHAT_SESSION_ID, since, until, provider === "anthropic" || provider === "deepseek" ? provider : undefined);
1121
+ }
1122
+ if (!session) {
1123
+ // A Codex agent woken only by its watcher: its thread is bound, and the rollout names it.
1124
+ const ref = agentRef(loadAgent(name));
1125
+ const rollout = sessionsOf("codex", ref).map(codexRollout).find((f) => !!f);
1126
+ if (rollout)
1127
+ session = { harness: "codex", transcript: rollout, session_id: null, at: Date.now() };
1128
+ }
1093
1129
  return sessionUsage(session, since, until);
1094
1130
  }
1095
1131
  catch (e) {
package/dist/git.js CHANGED
@@ -148,7 +148,7 @@ export function commitAtTime(ref, iso, cwd = process.cwd()) {
148
148
  * which case it is checked out as is. Returns the path. Fails loudly: a half-made worktree is
149
149
  * worse than none.
150
150
  */
151
- export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = []) {
151
+ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = [], inheritUrlRewrites = false) {
152
152
  const exists = git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], cwd) !== null;
153
153
  const sparse = exclude.length > 0;
154
154
  // Always defer checkout until we have explicitly applied this project's policy. Otherwise Git
@@ -161,6 +161,45 @@ export function createWorktree(path, branch, base, cwd = process.cwd(), exclude
161
161
  applySparse(path, exclude);
162
162
  else
163
163
  applyFullCheckout(path);
164
+ // Git copies config.worktree into linked worktrees. Strip inherited URL rewrites first so a
165
+ // Claude-specific proxy workaround never leaks into Codex or full-access Claude worktrees.
166
+ clearWorktreeUrlRewrites(path);
167
+ if (inheritUrlRewrites)
168
+ copyWorktreeUrlRewrites(cwd, path);
169
+ }
170
+ /** Carry worktree-scoped URL rewrites to new unit worktrees so HTTPS proxy access survives `wu start`. */
171
+ export function copyWorktreeUrlRewrites(from, to) {
172
+ const listed = spawnSync("git", ["config", "--worktree", "--get-regexp", "^url\\..*\\.insteadof$"], { cwd: from, encoding: "utf8" });
173
+ if (listed.status !== 0)
174
+ return;
175
+ for (const line of listed.stdout.split(/\r?\n/).filter(Boolean)) {
176
+ const split = line.indexOf(" ");
177
+ if (split < 0)
178
+ continue;
179
+ const key = line.slice(0, split);
180
+ const value = line.slice(split + 1);
181
+ const copied = spawnSync("git", ["config", "--worktree", "--add", key, value], { cwd: to, encoding: "utf8" });
182
+ if (copied.status !== 0)
183
+ throw new Error(`could not copy worktree Git URL rewrite to ${to}: ${(copied.stderr || copied.stdout).trim()}`);
184
+ }
185
+ }
186
+ /** Remove only URL rewrites stored in this worktree's config, leaving shared and global config alone. */
187
+ function clearWorktreeUrlRewrites(cwd) {
188
+ const path = spawnSync("git", ["rev-parse", "--git-path", "config.worktree"], { cwd, encoding: "utf8" });
189
+ if (path.status !== 0)
190
+ return;
191
+ const configPath = path.stdout.trim();
192
+ if (!configPath)
193
+ return;
194
+ const listed = spawnSync("git", ["config", "--file", configPath, "--get-regexp", "^url\\..*\\.insteadof$"], { cwd, encoding: "utf8" });
195
+ if (listed.status !== 0)
196
+ return;
197
+ const keys = [...new Set(listed.stdout.split(/\r?\n/).filter(Boolean).map((line) => line.slice(0, line.indexOf(" "))))];
198
+ for (const key of keys) {
199
+ const removed = spawnSync("git", ["config", "--file", configPath, "--unset-all", key], { cwd, encoding: "utf8" });
200
+ if (removed.status !== 0)
201
+ throw new Error(`could not clear inherited Git URL rewrite from ${cwd}: ${(removed.stderr || removed.stdout).trim()}`);
202
+ }
164
203
  }
165
204
  /**
166
205
  * Non-cone sparse checkout patterns that keep everything except `exclude` (repository paths such as
@@ -227,7 +266,7 @@ function realpathOrSelf(p) {
227
266
  * `git worktree add` (a harness timeout on a large repo) is removed and created again rather than
228
267
  * failing on "already exists"; an existing complete worktree on the right branch is reused.
229
268
  */
230
- export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = () => { }, exclude = []) {
269
+ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = () => { }, exclude = [], inheritUrlRewrites = false) {
231
270
  const st = worktreeState(path, cwd);
232
271
  if (st.state === "foreign")
233
272
  throw new Error(`${path} exists but is not a worktree of this repository; move it aside or pass --here`);
@@ -251,7 +290,7 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
251
290
  log(exclude.length
252
291
  ? `creating ${path} with project checkout exclusions: ${exclude.join(", ")}${files > 20_000 ? ` (${files.toLocaleString()} tracked files)` : ""}`
253
292
  : `creating ${path} with a full checkout (no project exclusions)${files > 20_000 ? `; ${files.toLocaleString()} tracked files, this can take a minute or more` : ""}`);
254
- createWorktree(path, branch, base, cwd, exclude);
293
+ createWorktree(path, branch, base, cwd, exclude, inheritUrlRewrites);
255
294
  return { created: true, repaired };
256
295
  }
257
296
  /**
@@ -436,20 +475,30 @@ export function ensureReviewWorktree(path, sha, cwd = process.cwd()) {
436
475
  * worktree's own index and files are untouched and no commit hooks run. Returns the branch.
437
476
  * Throws when any step fails: nothing may be removed on the strength of a failed archive.
438
477
  */
439
- export function archiveWorktreeChanges(path, name, message) {
440
- const run = (args, env = process.env) => {
478
+ export function archiveWorktreeChanges(path, name, message, env = process.env) {
479
+ const run = (args) => {
441
480
  const r = spawnSync("git", args, { cwd: path, encoding: "utf8", env });
442
481
  if (r.status !== 0)
443
482
  throw new Error(`git ${args[0]} failed in ${path}: ${(r.stderr || r.stdout).trim()}`);
444
483
  return r.stdout.trim();
445
484
  };
485
+ const author = spawnSync("git", ["var", "GIT_AUTHOR_IDENT"], { cwd: path, encoding: "utf8", env });
486
+ const committer = spawnSync("git", ["var", "GIT_COMMITTER_IDENT"], { cwd: path, encoding: "utf8", env });
487
+ if (author.status !== 0 || committer.status !== 0) {
488
+ throw new Error(`cannot archive worktree changes without a Git author and committer identity; configure them with: git config --global user.name "Your Name" && git config --global user.email "you@example.com"`);
489
+ }
446
490
  const index = run(["rev-parse", "--git-path", "index"]);
447
491
  const tmp = `${index}.bschat-archive-${process.pid}`;
448
492
  copyFileSync(index.startsWith("/") ? index : join(path, index), tmp.startsWith("/") ? tmp : join(path, tmp));
449
493
  try {
450
- const env = { ...process.env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
451
- run(["add", "-A"], env);
452
- const tree = run(["write-tree"], env);
494
+ const indexEnv = { ...env, GIT_INDEX_FILE: tmp.startsWith("/") ? tmp : join(path, tmp) };
495
+ const add = spawnSync("git", ["add", "-A"], { cwd: path, encoding: "utf8", env: indexEnv });
496
+ if (add.status !== 0)
497
+ throw new Error(`git add failed in ${path}: ${(add.stderr || add.stdout).trim()}`);
498
+ const writeTree = spawnSync("git", ["write-tree"], { cwd: path, encoding: "utf8", env: indexEnv });
499
+ if (writeTree.status !== 0)
500
+ throw new Error(`git write-tree failed in ${path}: ${(writeTree.stderr || writeTree.stdout).trim()}`);
501
+ const tree = writeTree.stdout.trim();
453
502
  const commit = run(["commit-tree", "-p", "HEAD", "-m", message, tree]);
454
503
  const branch = `archive/${name}`;
455
504
  run(["branch", branch, commit]);
package/dist/harnesses.js CHANGED
@@ -1,5 +1,5 @@
1
1
  import { spawnSync } from "node:child_process";
2
- import { existsSync, readFileSync, readdirSync, statSync } from "node:fs";
2
+ import { accessSync, constants, existsSync, readFileSync, readdirSync, statSync } from "node:fs";
3
3
  import { homedir } from "node:os";
4
4
  import { dirname, join } from "node:path";
5
5
  import { CliError } from "./errors.js";
@@ -22,6 +22,100 @@ export function turnHarness(h) {
22
22
  }
23
23
  export const HARNESS_LABEL = { codex: "Codex", "claude-code": "Claude Code", dsh: "DeepSeek Harness" };
24
24
  export const HARNESS_BIN = { codex: "codex", "claude-code": "claude", dsh: "dsh" };
25
+ /** Node's fetch ignores the sandbox's HTTP(S)_PROXY unless this opt-in is present. */
26
+ export function claudeSandboxEnv(sandbox) {
27
+ return sandbox === "workspace-write" ? { NODE_USE_ENV_PROXY: "1", BSCHAT_CLAUDE_SANDBOX: "workspace-write" } : {};
28
+ }
29
+ /** Resolve PATH first, then the native Claude Code installer's versioned executables. */
30
+ export function claudeCodePath(path = process.env.PATH ?? "", home = homedir()) {
31
+ const executableFile = (candidate) => {
32
+ try {
33
+ if (!statSync(candidate).isFile())
34
+ return false;
35
+ accessSync(candidate, constants.X_OK);
36
+ return true;
37
+ }
38
+ catch {
39
+ return false;
40
+ }
41
+ };
42
+ for (const dir of path.split(":")) {
43
+ if (!dir)
44
+ continue;
45
+ const candidate = join(dir, "claude");
46
+ if (executableFile(candidate))
47
+ return candidate;
48
+ }
49
+ const versionsDir = join(home, ".local", "share", "claude", "versions");
50
+ let versions;
51
+ try {
52
+ versions = readdirSync(versionsDir).filter((v) => /^\d+(?:\.\d+)*(?:[-+][\w.-]+)?$/.test(v));
53
+ }
54
+ catch {
55
+ return null;
56
+ }
57
+ const compare = (a, b) => {
58
+ const [abase, apre] = a.split("-", 2);
59
+ const [bbase, bpre] = b.split("-", 2);
60
+ const av = abase.split(".").map(Number);
61
+ const bv = bbase.split(".").map(Number);
62
+ for (let i = 0; i < Math.max(av.length, bv.length); i++) {
63
+ const x = av[i] ?? 0;
64
+ const y = bv[i] ?? 0;
65
+ if (x === y)
66
+ continue;
67
+ return x - y;
68
+ }
69
+ if (apre === undefined || bpre === undefined)
70
+ return apre === bpre ? 0 : apre === undefined ? 1 : -1;
71
+ const preCompare = apre.localeCompare(bpre, undefined, { numeric: true });
72
+ if (preCompare)
73
+ return preCompare;
74
+ return 0;
75
+ };
76
+ for (const version of versions.sort(compare).reverse()) {
77
+ const versionPath = join(versionsDir, version);
78
+ if (executableFile(versionPath))
79
+ return versionPath;
80
+ const candidate = join(versionsDir, version, "claude");
81
+ if (executableFile(candidate))
82
+ return candidate;
83
+ }
84
+ return null;
85
+ }
86
+ export function claudeTurnArgs(maxBudgetUsd) {
87
+ return ["--max-budget-usd", String(maxBudgetUsd)];
88
+ }
89
+ /** Parse the strict JSON report requested from tools run inside Claude Code's sandbox. */
90
+ export function claudeSelfCheckError(stdout) {
91
+ let reportText = stdout;
92
+ try {
93
+ const envelope = JSON.parse(stdout);
94
+ if (typeof envelope.result === "string")
95
+ reportText = envelope.result;
96
+ }
97
+ catch { /* allow the direct report for tests and future CLI output formats */ }
98
+ let report;
99
+ try {
100
+ report = JSON.parse(reportText);
101
+ }
102
+ catch {
103
+ return `Claude Code did not return the self-check JSON report; output: ${stdout.trim().slice(0, 1500) || "(empty)"}`;
104
+ }
105
+ const errors = [];
106
+ const me = report.b9s_me;
107
+ if (!me || me.status !== 0 || typeof me.output !== "string" || !me.output.trim())
108
+ errors.push(`b9s me failed (exit ${typeof me?.status === "number" ? me.status : "unknown"}): ${String(me?.output ?? "(no output)").trim().slice(0, 600)}`);
109
+ const remote = report.git_ls_remote_origin;
110
+ if (!remote || remote.status !== 0 || typeof remote.output !== "string" || !/^([a-f0-9]{40}|[a-f0-9]{64})\s+\S+/m.test(remote.output))
111
+ errors.push(`git ls-remote origin failed (exit ${typeof remote?.status === "number" ? remote.status : "unknown"}): ${String(remote?.output ?? "(no refs returned)").trim().slice(0, 600)}`);
112
+ return errors.length ? errors.join("\n") : null;
113
+ }
114
+ export function assertClaudeSelfCheck(stdout) {
115
+ const error = claudeSelfCheckError(stdout);
116
+ if (error)
117
+ throw new CliError("sandbox_self_check_failed", `Claude Code workspace-write self-check failed; watcher was not enabled.\n${error}`);
118
+ }
25
119
  export function probeFor(harness, session, ref) {
26
120
  return harness === "codex" ? codexProbe(session) : harness === "claude-code" ? claudeProbe(session, ref) : dshProbe(session, ref);
27
121
  }
@@ -446,6 +540,7 @@ export function claudeSettings(sandbox, model, effort, cwd, bschatHome, extraWri
446
540
  throw new CliError("usage", `unknown sandbox ${sandbox}`);
447
541
  const dirs = [dirname(cwd), bschatHome, ...extraWritable];
448
542
  const settings = {
543
+ env: claudeSandboxEnv(sandbox),
449
544
  sandbox: {
450
545
  enabled: true,
451
546
  failIfUnavailable: true,