benignswarm 0.12.97 → 0.12.99

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.
@@ -109,7 +109,12 @@ export async function watch(p, out) {
109
109
  if (providerName === "deepseek" && harness !== "claude-code")
110
110
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
111
111
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
112
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model };
112
+ const machineSessionId = str(p.flags, "machine-session-id") ?? process.env.BSCHAT_MACHINE_SESSION_ID;
113
+ 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))
114
+ throw new CliError("usage", "machine session id must be a UUID");
115
+ if (machineSessionId)
116
+ process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
117
+ turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider: providerName, model, ...(machineSessionId ? { machineSessionId } : {}) };
113
118
  }
114
119
  else if (p.flags.provider !== undefined) {
115
120
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -130,6 +135,8 @@ export async function watch(p, out) {
130
135
  if (!exec && !once)
131
136
  throw new CliError("usage", 'watch --exec "<command>" [--interval 30] | watch --once (print and exit) | watch --exec ... --service (launchd on macOS, systemd on Linux)');
132
137
  const log = (m) => process.stderr.write(`${new Date().toISOString()} b9s watch[${name}]: ${m}\n`);
138
+ const debugLog = (m) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
139
+ log(`debug poll: ${m}`); };
133
140
  let stopping = false;
134
141
  let stoppingCode = 0;
135
142
  let signalStop = () => { };
@@ -261,7 +268,7 @@ export async function watch(p, out) {
261
268
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
262
269
  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, turn?.coalesceSeconds ?? 0);
263
270
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
264
- }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
271
+ }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
265
272
  else {
266
273
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
267
274
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
@@ -289,7 +296,7 @@ export async function watch(p, out) {
289
296
  }
290
297
  let u;
291
298
  try {
292
- u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch", dryRun: true });
299
+ u = await gatherUpdates(name, { force: true, model: str(p.flags, "model"), delivery: "watch", dryRun: true, watchCursor: true });
293
300
  }
294
301
  catch (e) {
295
302
  if (e.code === "agent_benched") {
@@ -306,6 +313,7 @@ export async function watch(p, out) {
306
313
  }
307
314
  if (stopping)
308
315
  return stoppingCode;
316
+ debugLog(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; decision=${u ? "deliver" : "no updates"}`);
309
317
  if (u) {
310
318
  const recovery = resumeBriefDelivered ? null : await recoveryBriefText(name, log);
311
319
  const update = resumeBriefDelivered ? u : formatUpdates(omitMeasuresAlreadyIn(recovery, u), [recovery ?? recoveryBriefUnavailableText]);
@@ -353,6 +361,8 @@ async function waitIntervalOrStop(ms, stopped) {
353
361
  clearTimeout(timer);
354
362
  }
355
363
  export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
364
+ const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
365
+ log(`debug poll: ${message}`); };
356
366
  const state = readState(name);
357
367
  const pending = state.watch_pending;
358
368
  if (pending) {
@@ -372,6 +382,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
372
382
  }
373
383
  const st = readState(name);
374
384
  if (st.watch_pending) {
385
+ debug(`no inbox fetch; wake-up ${st.watch_pending.seq ?? "(legacy)"} remains unacknowledged`);
375
386
  const waited = Date.now() - st.watch_pending.at;
376
387
  if (waited > unackedAfter * 1000 && Date.now() - (st.watch_dormant_logged_at ?? 0) > 3_600_000) {
377
388
  log(`WAKE-UP ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}NOT ACKNOWLEDGED for ${Math.round(waited / 60_000)} min. Not queueing another. The agent may still be in a long turn; if its session is gone, start one for ${name} and have it run: b9s wake ack`);
@@ -381,17 +392,27 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
381
392
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}queued ${Math.round(waited / 1000)}s ago and not acknowledged; not queueing another`);
382
393
  return { sent: false, recoveryBriefDelivered: false };
383
394
  }
384
- const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true });
395
+ const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true, watchCursor: true });
396
+ const commitWatchCursor = () => {
397
+ if (!u?.watchCursorAfter)
398
+ return;
399
+ const current = readState(name);
400
+ if (!current.watch_inbox_after || current.watch_inbox_after < u.watchCursorAfter)
401
+ writeState(name, { ...current, watch_inbox_after: u.watchCursorAfter });
402
+ };
385
403
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
386
404
  // standing rules, so the watcher compares the version the agent last read with the current one.
387
405
  const lag = await (dependencies.processLag ?? processLag)(name, st, !!u, log);
388
406
  const processNews = !!lag && st.watch_process_woken !== lag.version;
389
407
  const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
408
+ debug(`seen messages=${u?.counts.messages ?? 0} questions=${u?.counts.questions ?? 0} items=${u?.counts.items ?? 0} followed=${u?.counts.followed ?? 0} digest=${u?.counts.digest ?? 0} notices=${u?.counts.notices ?? 0}; tier=${u?.tier ?? "none"}; processNews=${processNews}; operatorNew=${operatorNew}`);
390
409
  // Turn mode is a direct-work runner: role, followed and process-only changes remain available
391
410
  // to the agent's normal inbox/hook, but must not start another headless turn on their own.
392
411
  if (turnSink && u?.tier !== "direct") {
412
+ commitWatchCursor();
393
413
  if (st.watch_turn_coalesce_since !== undefined)
394
414
  writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
415
+ debug(`no wake: ${u ? `${u.tier}-level activity is not direct work` : "no direct work pending"}`);
395
416
  if (once)
396
417
  log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
397
418
  return { sent: false, recoveryBriefDelivered: false };
@@ -404,6 +425,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
404
425
  if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
405
426
  writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
406
427
  const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
428
+ debug(`no wake: direct work is coalescing until ${readyAt}`);
407
429
  log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
408
430
  return { sent: false, recoveryBriefDelivered: false };
409
431
  }
@@ -414,6 +436,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
414
436
  if (st.watch_followed_since)
415
437
  writeState(name, { ...st, watch_followed_since: undefined });
416
438
  if (!processNews) {
439
+ debug("no wake: no updates and no new process version");
417
440
  if (once)
418
441
  log("nothing new");
419
442
  return { sent: false, recoveryBriefDelivered: false };
@@ -422,6 +445,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
422
445
  else if (u.tier === "digest" && !processNews) {
423
446
  // Tiering: things addressed to this agent wake it now; followed-channel chatter waits for the
424
447
  // follow delay so bursts collapse; digest-only channels never wake it on their own.
448
+ debug("no wake: digest-only activity");
449
+ commitWatchCursor();
425
450
  if (once)
426
451
  log("only digest-level unread; not waking");
427
452
  return { sent: false, recoveryBriefDelivered: false };
@@ -432,6 +457,8 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
432
457
  writeState(name, { ...st, watch_followed_since: since });
433
458
  const waited = Date.now() - since;
434
459
  if (waited < followDelay * 1000) {
460
+ commitWatchCursor();
461
+ debug(`no wake: followed-only activity waiting ${Math.round(waited / 1000)}/${followDelay}s`);
435
462
  if (once)
436
463
  log(`followed-channel traffic only; waiting (${Math.round(waited / 1000)}/${followDelay}s) before waking`);
437
464
  return { sent: false, recoveryBriefDelivered: false };
@@ -462,10 +489,14 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
462
489
  // `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
463
490
  // the acknowledgement, operator note, process pointer, read commands, and delivery body.
464
491
  const line = wake;
465
- 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)))
492
+ debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
493
+ 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))) {
494
+ debug("no wake: delivery failed or turn guard denied the launch");
466
495
  return { sent: false, recoveryBriefDelivered: false };
496
+ }
467
497
  writeState(name, {
468
498
  ...readState(name),
499
+ ...(u?.watchCursorAfter ? { watch_inbox_after: u.watchCursorAfter } : {}),
469
500
  watch_seq: seq,
470
501
  ...(processNews ? { watch_process_woken: lag.version } : {}),
471
502
  watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
@@ -563,6 +594,18 @@ function stopBenchedWatcher(name, reason, log) {
563
594
  if (svc)
564
595
  removeService(svc);
565
596
  }
597
+ export function estimatedTurnCostMicros(reservation, tokens) {
598
+ if (reservation.pricing_mode !== "priced" || !reservation.prices)
599
+ return reservation.pricing_mode === "tokens_only" ? 0 : null;
600
+ const rates = new Map(reservation.prices.map((price) => [price.usage_class, price.micros_per_million_tokens]));
601
+ const input = rates.get("input"), cached = rates.get("cached_input"), output = rates.get("output");
602
+ if (![input, cached, output].every((n) => Number.isSafeInteger(n) && Number(n) >= 0))
603
+ return null;
604
+ const uncachedInput = Math.max(0, tokens.input - tokens.cached_input);
605
+ const total = BigInt(uncachedInput) * BigInt(input) + BigInt(tokens.cached_input) * BigInt(cached) + BigInt(tokens.output) * BigInt(output);
606
+ const rounded = (total + 999999n) / 1000000n;
607
+ return rounded <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(rounded) : null;
608
+ }
566
609
  const TURN_RETRY_MS = 5 * 60_000;
567
610
  const KEY_CHECK_MS = 5 * 60_000;
568
611
  /**
@@ -572,7 +615,9 @@ const KEY_CHECK_MS = 5 * 60_000;
572
615
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
573
616
  * broken; one that runs past --turn-timeout is stopped and logged.
574
617
  */
575
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
618
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness) {
619
+ const debug = (message) => { if (env.BSCHAT_WATCH_DEBUG === "1")
620
+ log(`debug poll: ${message}`); };
576
621
  const turn = ctl.turn;
577
622
  if (turn) {
578
623
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -621,12 +666,14 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
621
666
  }
622
667
  ctl.turn = null;
623
668
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
669
+ debug(`no inbox poll: turn #${turn.seq} just ended; checking for next work on the next watcher iteration`);
624
670
  return;
625
671
  }
626
672
  if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
627
673
  log(`turn #${turn.seq} has run ${timeoutMin} min; stopping it`);
628
674
  stopTurn(turn);
629
675
  }
676
+ debug(`no inbox poll: turn #${turn.seq} is still running`);
630
677
  return;
631
678
  }
632
679
  // b9s unpause: the operator switched the harness to an account with quota.
@@ -636,10 +683,14 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
636
683
  ctl.pausedUntil = 0;
637
684
  ctl.failedAt = 0;
638
685
  }
639
- if (Date.now() - ctl.failedAt < TURN_RETRY_MS)
686
+ if (Date.now() - ctl.failedAt < TURN_RETRY_MS) {
687
+ debug(`no inbox poll: failed-turn backoff until ${new Date(ctl.failedAt + TURN_RETRY_MS).toISOString()}`);
640
688
  return;
641
- if (ctl.pausedUntil > Date.now())
689
+ }
690
+ if (ctl.pausedUntil > Date.now()) {
691
+ debug(`no inbox poll: usage-limit pause until ${new Date(ctl.pausedUntil).toISOString()}`);
642
692
  return;
693
+ }
643
694
  // A turn this watcher did not start: an app or a terminal on the same session, or a turn left
644
695
  // running by a watcher that restarted (turns run in their own process group and outlive it).
645
696
  // Never start a second one.
@@ -647,21 +698,27 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
647
698
  const savedGuard = readState(name, env).turn_guard;
648
699
  if (savedGuard?.fault) {
649
700
  log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
701
+ debug("no inbox poll: turn guard is faulted");
650
702
  return;
651
703
  }
652
704
  if ("missing" in ph) {
653
705
  if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
654
706
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
655
- if (readState(name, env).turn_guard?.fault)
707
+ if (readState(name, env).turn_guard?.fault) {
708
+ debug("no inbox poll: completing the prior turn faulted the turn guard");
656
709
  return;
710
+ }
657
711
  }
658
712
  log(ph.missing);
713
+ debug("no inbox poll: configured harness session is missing");
659
714
  return;
660
715
  }
661
716
  if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
662
717
  await completePendingTurnGuard(name, probe, log, undefined, undefined, env);
663
- if (readState(name, env).turn_guard?.fault)
718
+ if (readState(name, env).turn_guard?.fault) {
719
+ debug("no inbox poll: completing the prior turn faulted the turn guard");
664
720
  return;
721
+ }
665
722
  }
666
723
  if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
667
724
  const failedAt = Date.parse(ph.lastErrorAt ?? "");
@@ -671,8 +728,10 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
671
728
  ctl.loggedFailureAt = ph.lastErrorAt;
672
729
  log(`the last DeepSeek Harness turn failed (${ph.lastError}); next turn is eligible at ${new Date(retryAt).toISOString()}`);
673
730
  }
674
- if (Date.now() < retryAt)
731
+ if (Date.now() < retryAt) {
732
+ debug(`no inbox poll: DeepSeek retry backoff until ${new Date(retryAt).toISOString()}`);
675
733
  return;
734
+ }
676
735
  }
677
736
  }
678
737
  // A watcher that restarted after a usage-limit failure reads the pause from the session itself.
@@ -681,6 +740,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
681
740
  ctl.pausedUntil = until;
682
741
  ctl.pausedAt = Date.now();
683
742
  log(`the last turn in ${probe.what} hit the ${probe.label} usage limit; no turns until ${new Date(until).toISOString()}`);
743
+ debug(`no inbox poll: usage-limit pause until ${new Date(until).toISOString()}`);
684
744
  return;
685
745
  }
686
746
  // A turn that started before this machine last booted died with it: no process survives a
@@ -697,6 +757,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
697
757
  if (ctl.loggedRunning !== ph.startedAt)
698
758
  log(`a turn started at ${ph.startedAt} is still running in ${probe.what} (an app or terminal on it, or a turn from before a restart); waiting for it`);
699
759
  ctl.loggedRunning = ph.startedAt;
760
+ debug(`no inbox poll: ${probe.what} is still running`);
700
761
  return;
701
762
  }
702
763
  if (probe.label !== "Codex") {
@@ -704,6 +765,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
704
765
  if (ctl.loggedRunning !== `stuck:${ph.startedAt}`)
705
766
  log(`a process still holds ${probe.what} and has written nothing for ${Math.round(quietMs / 60_000)} min (over the ${timeoutMin}-min limit); starting no turn while it runs. End it to free the session.`);
706
767
  ctl.loggedRunning = `stuck:${ph.startedAt}`;
768
+ debug(`no inbox poll: a process still holds ${probe.what}`);
707
769
  return;
708
770
  }
709
771
  // Codex: the rollout shows a turn that never closed; with nothing written for that long it is dead.
@@ -717,16 +779,18 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
717
779
  if (ctl.loggedRunning !== `maint:${maint.start}`)
718
780
  log(`maintenance on this machine ${maint.start.slice(0, 16)} to ${maint.end.slice(11, 16)} UTC: starting no new turns until it ends`);
719
781
  ctl.loggedRunning = `maint:${maint.start}`;
782
+ debug(`no inbox poll: machine maintenance runs until ${maint.end}`);
720
783
  return;
721
784
  }
722
785
  const st = readState(name, env);
723
786
  if (st.watch_pending) {
787
+ debug(`no inbox poll: wake-up ${st.watch_pending.seq ?? "(legacy)"} is still pending`);
724
788
  // Queued by a queue-mode watcher and never delivered, or failed: no turn is running, so the agent is not going to answer it.
725
789
  log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
726
790
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
727
791
  }
728
792
  await wake((t) => { ctl.turn = t; }, async () => {
729
- return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour);
793
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
730
794
  });
731
795
  }
732
796
  async function turnActivity(name, env) {
@@ -736,15 +800,57 @@ async function turnActivity(name, env) {
736
800
  return snapshot;
737
801
  }
738
802
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
739
- export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
803
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, machineSessionId = env.BSCHAT_MACHINE_SESSION_ID, harness) {
804
+ let current = readState(name, env);
805
+ const creds = loadAgent(name, env);
806
+ const waiting = current.turn_telemetry_completion_pending;
807
+ if (waiting) {
808
+ try {
809
+ const needsMeterReconciliation = !!waiting.settlement_body && waiting.settlement_body.meter_status !== "complete";
810
+ if (needsMeterReconciliation && waiting.settlement_recorded) {
811
+ const state = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${waiting.session_id}/turn-state`);
812
+ if (state.paused) {
813
+ log(`turn meter is unresolved (${state.state ?? "operator review"}); no next turn starts until the operator reconciles usage`);
814
+ return false;
815
+ }
816
+ current = { ...current, turn_telemetry_completion_pending: undefined };
817
+ writeState(name, current, env);
818
+ }
819
+ else {
820
+ const result = waiting.capture_enabled === false ? null : await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/agents/me/sessions/${waiting.session_id}/turns/${waiting.turn_id}/complete`, waiting.body);
821
+ logTurnExcerptDisposition(result, log);
822
+ let settlement;
823
+ if (waiting.settlement_body) {
824
+ settlement = await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/machines/me/sessions/${waiting.session_id}/turn-spend/reservations/${waiting.turn_id}/settle`, waiting.settlement_body);
825
+ }
826
+ if (needsMeterReconciliation && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
827
+ current = { ...current, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } };
828
+ writeState(name, current, env);
829
+ log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
830
+ return false;
831
+ }
832
+ current = { ...current, turn_telemetry_completion_pending: undefined };
833
+ writeState(name, current, env);
834
+ if (result?.pause_before_next_turn) {
835
+ log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
836
+ return false;
837
+ }
838
+ }
839
+ }
840
+ catch (e) {
841
+ log(`turn telemetry is waiting for the API to durably record the prior turn; no new turn starts: ${e.message}`);
842
+ return false;
843
+ }
844
+ }
740
845
  const before = await turnActivity(name, env);
741
- const current = readState(name, env);
846
+ current = readState(name, env);
742
847
  if (current.turn_guard?.fault) {
743
848
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
744
849
  return false;
745
850
  }
746
- const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour);
747
- writeState(name, { ...current, turn_guard: begun.state }, env);
851
+ const pendingStart = current.turn_telemetry_start_pending;
852
+ const turnId = pendingStart && pendingStart.session_id === machineSessionId ? pendingStart.turn_id : crypto.randomUUID();
853
+ const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour, turnId, false);
748
854
  if (!begun.start) {
749
855
  if (begun.state.fault)
750
856
  log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
@@ -752,8 +858,89 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
752
858
  log(`TURN MODE BUSY, NOT LOOPING: ${begun.state.turns.length}/${turnsPerHour} turns in the rolling hour; estimated tokens spent: ${begun.state.turns.reduce((sum, turn) => sum + turn.estimated_tokens, 0)}; resumes at ${new Date(begun.pause_until).toISOString()}`);
753
859
  return false;
754
860
  }
861
+ let telemetryEnabled = false;
862
+ let reservation;
863
+ if (machineSessionId) {
864
+ let intent = { session_id: machineSessionId, turn_id: turnId, ...(pendingStart?.session_id === machineSessionId && pendingStart.turn_id === turnId ? pendingStart : {}) };
865
+ writeState(name, { ...current, turn_telemetry_start_pending: intent }, env);
866
+ try {
867
+ const turnState = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${intent.session_id}/turn-state`);
868
+ if (turnState.paused) {
869
+ log(`TURN JUDGMENT PENDING: no turn starts while ${turnState.state ?? "operator review"} is pending`);
870
+ return false;
871
+ }
872
+ if (turnState.capture_enabled === true && turnState.enabled !== true)
873
+ throw new Error("turn capture cannot be active without a hard budget policy");
874
+ if (turnState.enabled === true) {
875
+ if (!harness || !["codex", "claude-code", "dsh", "antigravity"].includes(harness))
876
+ throw new Error("this session has no supported local token meter; no unattended turn starts");
877
+ const spendClient = Client.forAgent(creds, undefined, { presence: false });
878
+ let exposure = intent.exposure;
879
+ if (!exposure) {
880
+ const response = await spendClient.call("GET", `/machines/me/sessions/${intent.session_id}/turn-spend/exposure`);
881
+ exposure = response.exposure;
882
+ }
883
+ if (!exposure || !Number.isSafeInteger(exposure.max_tokens) || Number(exposure.max_tokens) <= 0 || (exposure.max_cost_micros !== null && exposure.max_cost_micros !== undefined && (!Number.isSafeInteger(exposure.max_cost_micros) || Number(exposure.max_cost_micros) < 0)) || (exposure.pricing_mode === "priced" && (!Number.isSafeInteger(exposure.max_cost_micros) || Number(exposure.max_cost_micros) < 0)) || typeof exposure.price_catalog_version !== "string" || !exposure.price_catalog_version || !["priced", "tokens_only"].includes(String(exposure.pricing_mode))) {
884
+ throw new Error("the API returned an invalid per-turn exposure profile; no unattended turn starts");
885
+ }
886
+ const reservationBody = intent.reservation_body ?? {
887
+ reservation_id: intent.turn_id,
888
+ reserved_tokens: Number(exposure.max_tokens),
889
+ reserved_cost_micros: Number(exposure.max_cost_micros ?? 0),
890
+ price_catalog_version: exposure.price_catalog_version,
891
+ meter_available: true,
892
+ };
893
+ intent = { ...intent, exposure, reservation_body: reservationBody };
894
+ writeState(name, { ...readState(name, env), turn_telemetry_start_pending: intent }, env);
895
+ const reserveResponse = await spendClient.call("POST", `/machines/me/sessions/${intent.session_id}/turn-spend/reservations`, reservationBody);
896
+ if (reserveResponse.reservation?.reservation_id !== intent.turn_id || reserveResponse.reservation.reserved_tokens !== Number(exposure.max_tokens) || reserveResponse.reservation.reserved_cost_micros !== Number(exposure.max_cost_micros ?? 0) || reserveResponse.reservation.price_catalog_version !== exposure.price_catalog_version || reserveResponse.reservation.state !== "reserved") {
897
+ throw new Error("the budget service did not confirm this turn's exact open reservation; no turn starts");
898
+ }
899
+ reservation = {
900
+ price_catalog_version: exposure.price_catalog_version,
901
+ reserved_tokens: Number(exposure.max_tokens),
902
+ reserved_cost_micros: Number(exposure.max_cost_micros ?? 0),
903
+ pricing_mode: String(exposure.pricing_mode),
904
+ ...(exposure.prices ? { prices: exposure.prices } : {}),
905
+ };
906
+ if (turnState.capture_enabled === true) {
907
+ const start = await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/agents/me/sessions/${intent.session_id}/turns/${intent.turn_id}/start`, {});
908
+ if (start.capture_enabled !== true)
909
+ throw new Error("the telemetry service did not acknowledge capture activation; no unattended turn starts");
910
+ telemetryEnabled = true;
911
+ }
912
+ }
913
+ else if (turnState.enabled === false) {
914
+ if (intent.reservation_body) {
915
+ log("turn policy changed while a budget reservation was pending; no turn starts until the reservation is reconciled");
916
+ return false;
917
+ }
918
+ current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
919
+ writeState(name, current, env);
920
+ }
921
+ else {
922
+ throw new Error("the API could not confirm the session's turn policy state; no unattended turn starts");
923
+ }
924
+ current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
925
+ }
926
+ catch (e) {
927
+ log(`turn launch policy is not durably satisfied; no turn starts (retrying the same turn id): ${e.message}`);
928
+ return false;
929
+ }
930
+ }
931
+ const finalGuard = telemetryEnabled || reservation ? { ...begun.state, turns: begun.state.turns.map((t) => t.turn_id === turnId ? { ...t, ...(telemetryEnabled ? { telemetry_enabled: true } : {}), ...(reservation ? { reservation } : {}) } : t) } : begun.state;
932
+ writeState(name, { ...current, turn_guard: finalGuard, turn_telemetry_start_pending: undefined }, env);
755
933
  return true;
756
934
  }
935
+ function logTurnExcerptDisposition(result, log) {
936
+ const receipt = result?.receipts?.find((item) => item.field === "excerpt" && (item.redacted === true || item.discarded === true));
937
+ if (!receipt)
938
+ return;
939
+ if (receipt.discarded)
940
+ log(`turn note excerpt discarded by capture policy (${receipt.bytes_received} bytes received; none stored)`);
941
+ else
942
+ log(`turn note excerpt redacted by server policy (${receipt.bytes_stored} of ${receipt.bytes_received} bytes stored)`);
943
+ }
757
944
  export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
758
945
  const current = readState(name, env);
759
946
  const guard = current.turn_guard;
@@ -798,10 +985,72 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
798
985
  sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
799
986
  }
800
987
  output = (output || error || sampleError || "").slice(-800);
801
- const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
802
- const tokenCount = tokenOverride !== undefined ? tokenOverride : directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null;
803
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount);
804
- writeState(name, { ...current, turn_guard: nextGuard }, env);
988
+ const usage = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()) : null;
989
+ const tokenValue = tokenOverride !== undefined ? tokenOverride : directTokens !== null ? directTokens : usage?.tokens?.total ?? null;
990
+ const tokenCount = tokenValue !== null && Number.isSafeInteger(tokenValue) && tokenValue >= 0 ? tokenValue : null;
991
+ const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount, pending.telemetry_enabled === true);
992
+ let nextState = { ...current, turn_guard: nextGuard, turn_note: undefined };
993
+ if (pending.telemetry_enabled && pending.turn_id && current.turn_telemetry_start_pending)
994
+ nextState.turn_telemetry_start_pending = undefined;
995
+ const rawTokens = usage?.tokens;
996
+ const tokens = rawTokens && [rawTokens.input, rawTokens.cached_input, rawTokens.output, rawTokens.reasoning, rawTokens.total].every((value) => Number.isSafeInteger(value) && value >= 0) ? rawTokens : null;
997
+ const reservation = pending.reservation;
998
+ const pricedBreakdownAvailable = !!tokens;
999
+ let meterStatus = tokenCount === null ? "missing" : reservation?.pricing_mode === "priced" && !pricedBreakdownAvailable ? "partial" : "complete";
1000
+ let actualCostMicros = null;
1001
+ if (reservation && meterStatus === "complete")
1002
+ actualCostMicros = estimatedTurnCostMicros(reservation, tokens ?? { input: 0, cached_input: 0, output: 0 });
1003
+ if (reservation?.pricing_mode === "priced" && actualCostMicros === null && meterStatus === "complete")
1004
+ meterStatus = "partial";
1005
+ const telemetryBody = {
1006
+ meter_status: meterStatus,
1007
+ input_tokens: tokens?.input ?? null,
1008
+ cached_input_tokens: tokens?.cached_input ?? null,
1009
+ output_tokens: tokens?.output ?? null,
1010
+ reasoning_tokens: tokens?.reasoning ?? null,
1011
+ total_tokens: tokenCount,
1012
+ error_code: error ? (probe.isLimit(error) ? "USAGE_LIMIT" : "HARNESS_ERROR") : sampleError ? "NETWORK_ERROR" : null,
1013
+ ...(current.turn_note ? { excerpt: current.turn_note } : {}),
1014
+ };
1015
+ if (pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
1016
+ const settlementBody = reservation ? {
1017
+ meter_status: meterStatus,
1018
+ ...(tokenCount !== null ? { actual_tokens: tokens?.total ?? tokenCount } : {}),
1019
+ ...(meterStatus === "complete" && actualCostMicros !== null ? { actual_cost_micros: actualCostMicros } : {}),
1020
+ price_catalog_version: reservation.price_catalog_version,
1021
+ } : undefined;
1022
+ if (pending.telemetry_enabled || settlementBody) {
1023
+ const waiting = { session_id: env.BSCHAT_MACHINE_SESSION_ID, turn_id: pending.turn_id, body: telemetryBody, capture_enabled: pending.telemetry_enabled === true, ...(settlementBody ? { settlement_body: settlementBody } : {}) };
1024
+ nextState.turn_telemetry_completion_pending = waiting;
1025
+ }
1026
+ }
1027
+ writeState(name, nextState, env);
1028
+ if ((pending.telemetry_enabled || pending.reservation) && pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
1029
+ try {
1030
+ const result = pending.telemetry_enabled
1031
+ ? await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", `/agents/me/sessions/${env.BSCHAT_MACHINE_SESSION_ID}/turns/${pending.turn_id}/complete`, telemetryBody)
1032
+ : null;
1033
+ logTurnExcerptDisposition(result, log);
1034
+ const settlementBody = nextState.turn_telemetry_completion_pending?.settlement_body;
1035
+ let settlement;
1036
+ if (settlementBody) {
1037
+ settlement = await Client.forAgent(loadAgent(name, env), undefined, { presence: false }).call("POST", `/machines/me/sessions/${env.BSCHAT_MACHINE_SESSION_ID}/turn-spend/reservations/${pending.turn_id}/settle`, settlementBody);
1038
+ }
1039
+ if (settlementBody && settlementBody.meter_status !== "complete" && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
1040
+ nextState = { ...readState(name, env), turn_telemetry_completion_pending: { ...nextState.turn_telemetry_completion_pending, settlement_recorded: true } };
1041
+ writeState(name, nextState, env);
1042
+ log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
1043
+ return;
1044
+ }
1045
+ nextState = { ...readState(name, env), turn_telemetry_completion_pending: undefined };
1046
+ writeState(name, nextState, env);
1047
+ if (result?.pause_before_next_turn)
1048
+ log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1049
+ }
1050
+ catch (e) {
1051
+ log(`turn completed, but telemetry is not durable at the API; the next turn will remain blocked until retry succeeds: ${e.message}`);
1052
+ }
1053
+ }
805
1054
  if (!productive)
806
1055
  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)"}`}`);
807
1056
  else if (nextGuard.consecutive_unproductive === 0)
@@ -932,7 +1181,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
932
1181
  bindSession(sess.kind, sess.id, name);
933
1182
  out.print(`Wrote ${path} and (re)loaded it: the watcher is running ${program[0]}.${Object.keys(extraEnv).length ? `\nCaptured env: ${Object.keys(extraEnv).join(", ")} (re-run this command if the harness restarts and these change)` : ""}\nStop it: launchctl bootout gui/$(id -u)/${label}\nLogs: ${logDir}/watch.${slug}.*.log\nCheck it: b9s doctor\nThe watcher runs from ${process.cwd()} so the repo identity file applies.`, { plist: path, label, program: program[0] });
934
1183
  }
935
- export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
1184
+ export const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--unproductive-per-hour", String(t.unproductivePerHour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(t.coalesceSeconds), "--harness", t.harness, "--session", t.session, ...(t.machineSessionId ? ["--machine-session-id", t.machineSessionId] : []), ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
936
1185
  function escapeXml(s) {
937
1186
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
938
1187
  }
@@ -69,6 +69,33 @@ export async function unitWorktrees(creds, project, options = {}) {
69
69
  }
70
70
  return { closed, active };
71
71
  }
72
+ export async function pruneProjectWorktrees(creds, project, cwd, protection, log) {
73
+ const before = await scanProject(creds, project, { cwd });
74
+ const units = await unitWorktrees(creds, project);
75
+ const report = pruneReport(cwd, units.closed, units.active, undefined, protection);
76
+ const dirtyClosed = [...new Set(report.kept.flatMap((item) => {
77
+ const number = item.dirtyClosed ? /WU #(\d+)/.exec(item.dirtyClosed)?.[1] : undefined;
78
+ return number ? [`closed unit #${number} has uncommitted work in ${item.path}`] : [];
79
+ }))];
80
+ const probe = freeSpaceProbe(report.prunable.map((item) => item.path));
81
+ let removed = 0;
82
+ for (const candidate of report.prunable) {
83
+ const result = removePrunable(candidate, cwd, undefined, protection.inUse, true);
84
+ if (result.removed)
85
+ removed++;
86
+ log(result.removed ? `pruned ${candidate.path}${candidate.branch ? ` (${candidate.branch})` : ""}` : `kept ${candidate.path}: ${result.reason}`);
87
+ }
88
+ const freeSpace = probe.after();
89
+ if (removed) {
90
+ try {
91
+ await scanProject(creds, project, { cwd });
92
+ }
93
+ catch (error) {
94
+ log(`post-prune worktree scan failed: ${error.message}`);
95
+ }
96
+ }
97
+ return { project, repo: before.repo, removed, free_space: freeSpace, dirty_closed: dirtyClosed };
98
+ }
72
99
  /**
73
100
  * The project's worktree registry.
74
101
  * b9s worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
@@ -132,7 +159,7 @@ export async function worktrees(p, out, timeouts = {}) {
132
159
  const kept = [];
133
160
  const probe = freeSpaceProbe(candidates.map((c) => c.path));
134
161
  for (const c of candidates) {
135
- const r = removePrunable(c, process.cwd(), statusTimeoutMs);
162
+ const r = removePrunable(c, process.cwd(), statusTimeoutMs, protection.inUse);
136
163
  if (r.removed)
137
164
  removed.push(c.path);
138
165
  else
@@ -165,7 +192,7 @@ export async function worktrees(p, out, timeouts = {}) {
165
192
  }
166
193
  /** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
167
194
  export async function scanProject(creds, project, options = {}) {
168
- const scan = scanWorktrees(process.cwd(), options);
195
+ const scan = scanWorktrees(options.cwd ?? process.cwd(), options);
169
196
  if (!scan)
170
197
  throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
171
198
  const machine = creds.machine || defaultMachine();