benignswarm 0.12.96 → 0.12.98

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.
Files changed (41) hide show
  1. package/dist/admin-index.js +0 -0
  2. package/dist/args.js +40 -3
  3. package/dist/brief.js +5 -1
  4. package/dist/client.js +248 -0
  5. package/dist/commands/admin.js +84 -22
  6. package/dist/commands/agent.js +15 -2
  7. package/dist/commands/cloud-admin.js +56 -3
  8. package/dist/commands/codex-start.js +340 -241
  9. package/dist/commands/environment-admin.js +130 -0
  10. package/dist/commands/environment.js +53 -0
  11. package/dist/commands/evidence.js +6 -3
  12. package/dist/commands/feedback.js +12 -1
  13. package/dist/commands/flow.js +153 -0
  14. package/dist/commands/hook.js +29 -9
  15. package/dist/commands/image-admin.js +77 -0
  16. package/dist/commands/install.js +81 -3
  17. package/dist/commands/lists.js +4 -0
  18. package/dist/commands/machine-admin.js +444 -111
  19. package/dist/commands/machine-resize.js +234 -0
  20. package/dist/commands/machine.js +960 -41
  21. package/dist/commands/operator.js +5 -8
  22. package/dist/commands/retire.js +4 -0
  23. package/dist/commands/templates.js +27 -0
  24. package/dist/commands/turn.js +21 -0
  25. package/dist/commands/watch.js +256 -21
  26. package/dist/commands/wu.js +131 -81
  27. package/dist/container.js +480 -0
  28. package/dist/environment-checks.js +79 -0
  29. package/dist/git.js +28 -0
  30. package/dist/help.js +94 -37
  31. package/dist/index.js +7 -1
  32. package/dist/install.js +43 -1
  33. package/dist/macos-readiness.js +173 -0
  34. package/dist/output.js +17 -4
  35. package/dist/templates.js +218 -0
  36. package/dist/test-workers.js +17 -0
  37. package/dist/turn-guard.js +5 -5
  38. package/dist/turn.js +6 -0
  39. package/dist/usage.js +117 -0
  40. package/dist/version.js +1 -1
  41. package/package.json +1 -1
@@ -47,7 +47,7 @@ export function editVocabulary(vocab, op, tag, f) {
47
47
  throw new CliError("not_found", `#${name} is not in the vocabulary`);
48
48
  if (op === "remove")
49
49
  return vocab.filter((t) => t.name !== name);
50
- const base = i >= 0 ? vocab[i] : { name, meaning: "", require_evidence: false, require_rebased: false, expert_role: null, min_tier: "routine" };
50
+ const { min_tier: _legacyMinTier, ...base } = i >= 0 ? vocab[i] : { name, meaning: "", require_evidence: false, require_rebased: false, expert_role: null };
51
51
  const next = {
52
52
  ...base,
53
53
  ...(f.meaning !== undefined ? { meaning: f.meaning } : {}),
@@ -55,7 +55,6 @@ export function editVocabulary(vocab, op, tag, f) {
55
55
  ...(f.rebased !== undefined ? { require_rebased: f.rebased } : {}),
56
56
  ...(f.expert !== undefined ? { expert_role: f.expert === "none" || f.expert === "" ? null : f.expert } : {}),
57
57
  ...(f.requires !== undefined ? { requires: f.requires.length ? f.requires : undefined } : {}),
58
- ...(f.tier !== undefined ? { min_tier: f.tier } : {}),
59
58
  };
60
59
  if (op === "add" && !next.meaning.trim())
61
60
  throw new CliError("usage", `a tag needs a meaning, the sentence workers decide by: --meaning ".."`);
@@ -129,10 +128,11 @@ function describeProcess(r) {
129
128
  ` requires: scope ${d.require_scope ? "yes" : "no"}, evidence to submit ${d.require_evidence_to_submit ? "yes" : "no"}; default approver ${d.default_approver_role ?? "none"}; assigners ${d.assigners.join(", ") || "none"}`,
130
129
  ` merging: into ${m.target_branch} by ${m.merged_by === "integrator" ? `a ${m.integrator_role}` : `the ${m.merged_by}`}; merge commit ${m.require_merge_commit ? "yes" : "no"}, rebased ${m.require_rebased ? "yes" : "no"}, pushed ${m.require_pushed ? "yes" : "no"}`,
131
130
  ` capabilities: ${(d.capabilities ?? []).map((c) => `${c.name} (${c.scope}${c.min_version ? ` >= ${c.min_version}` : ""})`).join(", ") || "none"}`,
131
+ ` heavy jobs: ${Object.entries(d.heavy_jobs ?? {}).map(([name, job]) => `${name} (${job.memory_gib} GiB; ${job.purpose}; workflows ${job.workflows.join(", ")})`).join("; ") || "none"}`,
132
132
  ` steward: ${d.steward.enabled ? "on" : "off"}, quiet ${d.steward.quiet_minutes} min, summary every ${d.steward.summary_minutes} min, ask the operator after ${d.steward.churn_rounds ? `${d.steward.churn_rounds} rounds on one goal` : "(never)"}`,
133
133
  ` agreements: ${r.process.agreements.length} of 8000 characters; charter: ${(r.process.charter ?? "").length ? `${r.process.charter.length} of 4000 characters` : "none (b9s-admin process charter <project> --file charter.md)"}; send-backs ${d.require_cited_changes === false ? "free-form" : "must cite the clause they fail"}`,
134
134
  v.length ? `Tags:` : `No tag vocabulary: every unit goes to the default approver.`,
135
- ...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.min_tier && t.min_tier !== "routine" ? ` · minimum tier ${t.min_tier}` : ""}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
135
+ ...v.map((t) => ` #${t.name}: ${t.meaning || "(NO MEANING: workers cannot decide by it)"}${t.require_evidence ? " · evidence" : ""}${t.require_rebased ? " · rebased" : ""}${t.expert_role ? ` · expert ${t.expert_role}` : ""}${t.requires?.length ? ` · requires ${t.requires.join(", ")}` : ""}`),
136
136
  ].join("\n");
137
137
  }
138
138
  export async function processAdmin(action, rest, p, out) {
@@ -189,12 +189,9 @@ export async function processAdmin(action, rest, p, out) {
189
189
  const op = tagOperationFirst ? rest[0] : rest[1];
190
190
  const tag = tagProjectFlag ? (rest[2] ?? rest[1]) : rest[2];
191
191
  if (!["add", "edit", "remove"].includes(op) || !tag)
192
- throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--tier routine|careful|expert] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
192
+ throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
193
193
  const r = await get();
194
- const tier = str(p.flags, "tier");
195
- if (tier !== undefined && !["routine", "careful", "expert"].includes(tier))
196
- throw new CliError("usage", "--tier must be routine, careful, or expert");
197
- const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role"), requires: tagList(str(p.flags, "requires")), tier });
194
+ const vocabulary = editVocabulary(r.vocabulary, op, tag, { meaning: str(p.flags, "meaning"), evidence: yesNo(str(p.flags, "require-evidence"), "require-evidence"), rebased: yesNo(str(p.flags, "require-rebased"), "require-rebased"), expert: str(p.flags, "expert-role"), requires: tagList(str(p.flags, "requires")) });
198
195
  return publish({ vocabulary }, `tag #${tag.replace(/^#/, "")} ${op === "add" ? "added" : op === "edit" ? "edited" : "removed"}`);
199
196
  }
200
197
  case "timing":
@@ -21,6 +21,8 @@ export async function retire(p, out) {
21
21
  throw new CliError("usage", 'retire --title "..." (--body "..." | --body-file notes.md) [--handoff-to @agent|@role:x] [--evidence id,id] [--project p]');
22
22
  let body = str(p.flags, "body");
23
23
  const file = str(p.flags, "body-file");
24
+ if (file && body !== undefined)
25
+ throw new CliError("usage", "retire accepts --body or --body-file, not both");
24
26
  if (file) {
25
27
  try {
26
28
  body = readFileSync(file, "utf8");
@@ -87,6 +89,8 @@ export async function checkpoint(p, out) {
87
89
  const title = str(p.flags, "title") ?? p.positionals.slice(1).join(" ").trim();
88
90
  let body = str(p.flags, "body");
89
91
  const file = str(p.flags, "body-file");
92
+ if (file && body !== undefined)
93
+ throw new CliError("usage", "checkpoint accepts --body or --body-file, not both");
90
94
  if (file) {
91
95
  try {
92
96
  body = readFileSync(file, "utf8");
@@ -0,0 +1,27 @@
1
+ import { str } from "../args.js";
2
+ import { CliError } from "../errors.js";
3
+ import { packTemplateCatalog, validateTemplateCatalog } from "../templates.js";
4
+ export async function templates(p, out) {
5
+ const action = p.positionals[1];
6
+ if (action !== "validate" && action !== "pack")
7
+ throw new CliError("usage", "templates needs validate or pack", "Run: b9s templates validate [--root <repo>] | b9s templates pack --signing-key <pem> [--root <repo>] [--out <dir>]");
8
+ const root = str(p.flags, "root") ?? process.cwd();
9
+ try {
10
+ if (action === "validate") {
11
+ const catalog = validateTemplateCatalog(root);
12
+ const result = { release: catalog.release, templates: catalog.entries.map(t => `${t.family}/${t.version}`) };
13
+ out.print(`Catalog ${result.release}: ${result.templates.length} validated templates\n${result.templates.join("\n")}`, result);
14
+ return;
15
+ }
16
+ const key = str(p.flags, "signing-key");
17
+ if (!key)
18
+ throw new CliError("usage", "templates pack requires --signing-key <pem>");
19
+ const result = packTemplateCatalog(root, str(p.flags, "out") ?? "dist/template-releases", key);
20
+ out.print(`Created ${result.archive}\nSHA-256 ${result.sha256}\nSignature ${result.signature}\nSource ${result.sourceRevision}`, result);
21
+ }
22
+ catch (error) {
23
+ if (error instanceof CliError)
24
+ throw error;
25
+ throw new CliError("template_catalog", error.message);
26
+ }
27
+ }
@@ -0,0 +1,21 @@
1
+ import { str } from "../args.js";
2
+ import { resolveAgentName } from "../config.js";
3
+ import { readState, writeState } from "../state.js";
4
+ import { CliError } from "../errors.js";
5
+ /** Explicit, local turn-end note; the watcher sends it only as a bounded unverified excerpt. */
6
+ export async function turn(p, out) {
7
+ const name = resolveAgentName(str(p.flags, "as"));
8
+ const sub = p.positionals[1];
9
+ if (sub !== "note")
10
+ throw new CliError("usage", 'turn note "short progress summary"');
11
+ const state = readState(name);
12
+ const attempt = state.turn_guard?.turns.slice().reverse().find((item) => item.productive === null);
13
+ if (!attempt?.telemetry_enabled || !attempt.turn_id || !process.env.BSCHAT_MACHINE_SESSION_ID) {
14
+ throw new CliError("turn_telemetry_disabled", "turn notes are available only for a machine-managed session with account turn policy enabled");
15
+ }
16
+ const note = p.positionals.slice(2).join(" ").trim();
17
+ if (!note || [...note].length > 300)
18
+ throw new CliError("usage", "turn note needs 1 to 300 characters");
19
+ writeState(name, { ...state, turn_note: note });
20
+ out.print("saved a turn-end note; it will be shown as unverified context in the account-scoped judgment packet", { saved: true });
21
+ }
@@ -1,6 +1,6 @@
1
1
  import { spawn, spawnSync } from "node:child_process";
2
2
  import { bindSession, sessionOfExec, threadOfExec } from "../sessions.js";
3
- import { startTurn, stopTurn } from "../turn.js";
3
+ import { DEFAULT_TURN_COALESCE_SECONDS, MAX_TURN_COALESCE_SECONDS, shouldDeferTurn, startTurn, stopTurn } from "../turn.js";
4
4
  import { drainingUntil } from "../maintenance.js";
5
5
  import { probeFor, turnHarness } from "../harnesses.js";
6
6
  import { applyAck } from "./wake.js";
@@ -70,6 +70,9 @@ export async function watch(p, out) {
70
70
  const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
71
71
  if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
72
72
  throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
73
+ const turnCoalesceSeconds = Number(str(p.flags, "turn-coalesce-seconds") ?? String(DEFAULT_TURN_COALESCE_SECONDS));
74
+ if (!Number.isInteger(turnCoalesceSeconds) || turnCoalesceSeconds < 0 || turnCoalesceSeconds > MAX_TURN_COALESCE_SECONDS)
75
+ throw new CliError("usage", `--turn-coalesce-seconds must be a whole number between 0 and ${MAX_TURN_COALESCE_SECONDS}`);
73
76
  const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
74
77
  if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > MAX_TURNS_PER_HOUR)
75
78
  throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${MAX_TURNS_PER_HOUR}`);
@@ -80,6 +83,8 @@ export async function watch(p, out) {
80
83
  throw new CliError("usage", "--turns-per-hour is only used with --turn");
81
84
  if (!turnMode && p.flags["unproductive-per-hour"] !== undefined)
82
85
  throw new CliError("usage", "--unproductive-per-hour is only used with --turn");
86
+ if (!turnMode && p.flags["turn-coalesce-seconds"] !== undefined)
87
+ throw new CliError("usage", "--turn-coalesce-seconds is only used with --turn");
83
88
  const thread = exec ? threadOfExec(exec) : null;
84
89
  // Which harness runs the turns and the session they continue. Codex watchers installed before
85
90
  // 0.12.66 carry neither flag: their thread is in the exec command.
@@ -104,7 +109,12 @@ export async function watch(p, out) {
104
109
  if (providerName === "deepseek" && harness !== "claude-code")
105
110
  throw new CliError("usage", "--provider deepseek requires --harness claude-code");
106
111
  const model = str(p.flags, "model") ?? (providerName === "deepseek" ? "deepseek-flash" : undefined);
107
- turn = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, 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 } : {}) };
108
118
  }
109
119
  else if (p.flags.provider !== undefined) {
110
120
  throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
@@ -254,9 +264,9 @@ export async function watch(p, out) {
254
264
  try {
255
265
  if (probe)
256
266
  await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
257
- 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);
267
+ 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);
258
268
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
259
- }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
269
+ }, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
260
270
  else {
261
271
  const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
262
272
  resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
@@ -279,7 +289,7 @@ export async function watch(p, out) {
279
289
  return stoppingCode;
280
290
  if (once)
281
291
  return;
282
- await waitIntervalOrStop(interval * 1000, stopped);
292
+ await waitIntervalOrStop(watchPollMs(interval), stopped);
283
293
  continue;
284
294
  }
285
295
  let u;
@@ -333,17 +343,21 @@ export async function watch(p, out) {
333
343
  }
334
344
  if (once)
335
345
  return;
336
- await waitIntervalOrStop(interval * 1000, stopped);
346
+ await waitIntervalOrStop(watchPollMs(interval), stopped);
337
347
  }
338
348
  return stoppingCode;
339
349
  }
350
+ function watchPollMs(intervalSeconds) {
351
+ const override = Number(process.env.B9S_WATCH_INTERVAL_MS);
352
+ return Number.isFinite(override) && override > 0 ? Math.max(50, Math.floor(override)) : intervalSeconds * 1000;
353
+ }
340
354
  async function waitIntervalOrStop(ms, stopped) {
341
355
  let timer;
342
356
  await Promise.race([new Promise((resolve) => { timer = setTimeout(resolve, ms); }), stopped]);
343
357
  if (timer)
344
358
  clearTimeout(timer);
345
359
  }
346
- async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId) {
360
+ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
347
361
  const state = readState(name);
348
362
  const pending = state.watch_pending;
349
363
  if (pending) {
@@ -372,11 +386,35 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
372
386
  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`);
373
387
  return { sent: false, recoveryBriefDelivered: false };
374
388
  }
375
- const u = await gatherUpdates(name, { force: true, model, delivery: "watch", dryRun: true });
389
+ const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true });
376
390
  // A process change is news too. Watched harnesses never see the Claude Code hook re-deliver the
377
391
  // standing rules, so the watcher compares the version the agent last read with the current one.
378
- const lag = await processLag(name, st, !!u, log);
392
+ const lag = await (dependencies.processLag ?? processLag)(name, st, !!u, log);
379
393
  const processNews = !!lag && st.watch_process_woken !== lag.version;
394
+ const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
395
+ // Turn mode is a direct-work runner: role, followed and process-only changes remain available
396
+ // to the agent's normal inbox/hook, but must not start another headless turn on their own.
397
+ if (turnSink && u?.tier !== "direct") {
398
+ if (st.watch_turn_coalesce_since !== undefined)
399
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
400
+ if (once)
401
+ log(u ? `only ${u.tier}-level unread; not starting a turn` : "no direct work pending; not starting a turn");
402
+ return { sent: false, recoveryBriefDelivered: false };
403
+ }
404
+ if (turnSink && turnCoalesceSeconds > 0 && u?.tier === "direct") {
405
+ const updateAt = u.firstDirectAt ? Date.parse(u.firstDirectAt) : Number.NaN;
406
+ const firstPendingAt = Number.isFinite(updateAt)
407
+ ? Math.min(updateAt, st.watch_turn_coalesce_since ?? updateAt)
408
+ : st.watch_turn_coalesce_since ?? Date.now();
409
+ if (shouldDeferTurn({ pending: true, firstPendingAt, now: Date.now(), seconds: turnCoalesceSeconds, operator: operatorNew, urgent: u.urgent })) {
410
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: firstPendingAt });
411
+ const readyAt = new Date(firstPendingAt + turnCoalesceSeconds * 1000).toISOString();
412
+ log(`direct wake-up is coalescing until ${readyAt}; later direct items will join it`);
413
+ return { sent: false, recoveryBriefDelivered: false };
414
+ }
415
+ }
416
+ if (turnSink && st.watch_turn_coalesce_since !== undefined)
417
+ writeState(name, { ...readState(name), watch_turn_coalesce_since: undefined });
380
418
  if (!u) {
381
419
  if (st.watch_followed_since)
382
420
  writeState(name, { ...st, watch_followed_since: undefined });
@@ -405,7 +443,6 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
405
443
  }
406
444
  }
407
445
  const seq = (st.watch_seq ?? 0) + 1;
408
- const operatorNew = !!u && u.latestOperatorAt !== null && u.latestOperatorAt !== (st.watch_operator_at ?? null);
409
446
  const recovery = includeResumeBrief ? await recoveryBriefText(name, log) : null;
410
447
  const recoveryPrompt = includeResumeBrief ? recovery ?? recoveryBriefUnavailableText : null;
411
448
  const wakePrefix = [
@@ -441,6 +478,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
441
478
  ...(u ? { notice_state: u.noticeNext } : {}),
442
479
  ...(u?.measureSnapshot ? { measure_state: u.measureSnapshot } : {}),
443
480
  watch_followed_since: undefined,
481
+ watch_turn_coalesce_since: undefined,
444
482
  watch_dormant_logged_at: undefined,
445
483
  });
446
484
  return { sent: true, recoveryBriefDelivered: recoveryBriefWasDelivered(recovery, true) };
@@ -530,6 +568,18 @@ function stopBenchedWatcher(name, reason, log) {
530
568
  if (svc)
531
569
  removeService(svc);
532
570
  }
571
+ export function estimatedTurnCostMicros(reservation, tokens) {
572
+ if (reservation.pricing_mode !== "priced" || !reservation.prices)
573
+ return reservation.pricing_mode === "tokens_only" ? 0 : null;
574
+ const rates = new Map(reservation.prices.map((price) => [price.usage_class, price.micros_per_million_tokens]));
575
+ const input = rates.get("input"), cached = rates.get("cached_input"), output = rates.get("output");
576
+ if (![input, cached, output].every((n) => Number.isSafeInteger(n) && Number(n) >= 0))
577
+ return null;
578
+ const uncachedInput = Math.max(0, tokens.input - tokens.cached_input);
579
+ const total = BigInt(uncachedInput) * BigInt(input) + BigInt(tokens.cached_input) * BigInt(cached) + BigInt(tokens.output) * BigInt(output);
580
+ const rounded = (total + 999999n) / 1000000n;
581
+ return rounded <= BigInt(Number.MAX_SAFE_INTEGER) ? Number(rounded) : null;
582
+ }
533
583
  const TURN_RETRY_MS = 5 * 60_000;
534
584
  const KEY_CHECK_MS = 5 * 60_000;
535
585
  /**
@@ -539,7 +589,7 @@ const KEY_CHECK_MS = 5 * 60_000;
539
589
  * leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
540
590
  * broken; one that runs past --turn-timeout is stopped and logged.
541
591
  */
542
- export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
592
+ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, harness) {
543
593
  const turn = ctl.turn;
544
594
  if (turn) {
545
595
  if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
@@ -693,7 +743,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
693
743
  writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
694
744
  }
695
745
  await wake((t) => { ctl.turn = t; }, async () => {
696
- return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour);
746
+ return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
697
747
  });
698
748
  }
699
749
  async function turnActivity(name, env) {
@@ -703,15 +753,57 @@ async function turnActivity(name, env) {
703
753
  return snapshot;
704
754
  }
705
755
  /** Reserve every actual harness launch, including b9s start's onboarding turn. */
706
- export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
756
+ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = process.env, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR, machineSessionId = env.BSCHAT_MACHINE_SESSION_ID, harness) {
757
+ let current = readState(name, env);
758
+ const creds = loadAgent(name, env);
759
+ const waiting = current.turn_telemetry_completion_pending;
760
+ if (waiting) {
761
+ try {
762
+ const needsMeterReconciliation = !!waiting.settlement_body && waiting.settlement_body.meter_status !== "complete";
763
+ if (needsMeterReconciliation && waiting.settlement_recorded) {
764
+ const state = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${waiting.session_id}/turn-state`);
765
+ if (state.paused) {
766
+ log(`turn meter is unresolved (${state.state ?? "operator review"}); no next turn starts until the operator reconciles usage`);
767
+ return false;
768
+ }
769
+ current = { ...current, turn_telemetry_completion_pending: undefined };
770
+ writeState(name, current, env);
771
+ }
772
+ else {
773
+ 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);
774
+ logTurnExcerptDisposition(result, log);
775
+ let settlement;
776
+ if (waiting.settlement_body) {
777
+ 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);
778
+ }
779
+ if (needsMeterReconciliation && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
780
+ current = { ...current, turn_telemetry_completion_pending: { ...waiting, settlement_recorded: true } };
781
+ writeState(name, current, env);
782
+ log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
783
+ return false;
784
+ }
785
+ current = { ...current, turn_telemetry_completion_pending: undefined };
786
+ writeState(name, current, env);
787
+ if (result?.pause_before_next_turn) {
788
+ log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
789
+ return false;
790
+ }
791
+ }
792
+ }
793
+ catch (e) {
794
+ log(`turn telemetry is waiting for the API to durably record the prior turn; no new turn starts: ${e.message}`);
795
+ return false;
796
+ }
797
+ }
707
798
  const before = await turnActivity(name, env);
708
- const current = readState(name, env);
799
+ current = readState(name, env);
709
800
  if (current.turn_guard?.fault) {
710
801
  log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
711
802
  return false;
712
803
  }
713
- const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour);
714
- writeState(name, { ...current, turn_guard: begun.state }, env);
804
+ const pendingStart = current.turn_telemetry_start_pending;
805
+ const turnId = pendingStart && pendingStart.session_id === machineSessionId ? pendingStart.turn_id : crypto.randomUUID();
806
+ const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq, unproductivePerHour, turnId, false);
715
807
  if (!begun.start) {
716
808
  if (begun.state.fault)
717
809
  log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
@@ -719,8 +811,89 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
719
811
  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()}`);
720
812
  return false;
721
813
  }
814
+ let telemetryEnabled = false;
815
+ let reservation;
816
+ if (machineSessionId) {
817
+ let intent = { session_id: machineSessionId, turn_id: turnId, ...(pendingStart?.session_id === machineSessionId && pendingStart.turn_id === turnId ? pendingStart : {}) };
818
+ writeState(name, { ...current, turn_telemetry_start_pending: intent }, env);
819
+ try {
820
+ const turnState = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/agents/me/sessions/${intent.session_id}/turn-state`);
821
+ if (turnState.paused) {
822
+ log(`TURN JUDGMENT PENDING: no turn starts while ${turnState.state ?? "operator review"} is pending`);
823
+ return false;
824
+ }
825
+ if (turnState.capture_enabled === true && turnState.enabled !== true)
826
+ throw new Error("turn capture cannot be active without a hard budget policy");
827
+ if (turnState.enabled === true) {
828
+ if (!harness || !["codex", "claude-code", "dsh", "antigravity"].includes(harness))
829
+ throw new Error("this session has no supported local token meter; no unattended turn starts");
830
+ const spendClient = Client.forAgent(creds, undefined, { presence: false });
831
+ let exposure = intent.exposure;
832
+ if (!exposure) {
833
+ const response = await spendClient.call("GET", `/machines/me/sessions/${intent.session_id}/turn-spend/exposure`);
834
+ exposure = response.exposure;
835
+ }
836
+ 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))) {
837
+ throw new Error("the API returned an invalid per-turn exposure profile; no unattended turn starts");
838
+ }
839
+ const reservationBody = intent.reservation_body ?? {
840
+ reservation_id: intent.turn_id,
841
+ reserved_tokens: Number(exposure.max_tokens),
842
+ reserved_cost_micros: Number(exposure.max_cost_micros ?? 0),
843
+ price_catalog_version: exposure.price_catalog_version,
844
+ meter_available: true,
845
+ };
846
+ intent = { ...intent, exposure, reservation_body: reservationBody };
847
+ writeState(name, { ...readState(name, env), turn_telemetry_start_pending: intent }, env);
848
+ const reserveResponse = await spendClient.call("POST", `/machines/me/sessions/${intent.session_id}/turn-spend/reservations`, reservationBody);
849
+ 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") {
850
+ throw new Error("the budget service did not confirm this turn's exact open reservation; no turn starts");
851
+ }
852
+ reservation = {
853
+ price_catalog_version: exposure.price_catalog_version,
854
+ reserved_tokens: Number(exposure.max_tokens),
855
+ reserved_cost_micros: Number(exposure.max_cost_micros ?? 0),
856
+ pricing_mode: String(exposure.pricing_mode),
857
+ ...(exposure.prices ? { prices: exposure.prices } : {}),
858
+ };
859
+ if (turnState.capture_enabled === true) {
860
+ const start = await Client.forAgent(creds, undefined, { presence: false }).call("POST", `/agents/me/sessions/${intent.session_id}/turns/${intent.turn_id}/start`, {});
861
+ if (start.capture_enabled !== true)
862
+ throw new Error("the telemetry service did not acknowledge capture activation; no unattended turn starts");
863
+ telemetryEnabled = true;
864
+ }
865
+ }
866
+ else if (turnState.enabled === false) {
867
+ if (intent.reservation_body) {
868
+ log("turn policy changed while a budget reservation was pending; no turn starts until the reservation is reconciled");
869
+ return false;
870
+ }
871
+ current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
872
+ writeState(name, current, env);
873
+ }
874
+ else {
875
+ throw new Error("the API could not confirm the session's turn policy state; no unattended turn starts");
876
+ }
877
+ current = { ...readState(name, env), turn_telemetry_start_pending: undefined };
878
+ }
879
+ catch (e) {
880
+ log(`turn launch policy is not durably satisfied; no turn starts (retrying the same turn id): ${e.message}`);
881
+ return false;
882
+ }
883
+ }
884
+ 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;
885
+ writeState(name, { ...current, turn_guard: finalGuard, turn_telemetry_start_pending: undefined }, env);
722
886
  return true;
723
887
  }
888
+ function logTurnExcerptDisposition(result, log) {
889
+ const receipt = result?.receipts?.find((item) => item.field === "excerpt" && (item.redacted === true || item.discarded === true));
890
+ if (!receipt)
891
+ return;
892
+ if (receipt.discarded)
893
+ log(`turn note excerpt discarded by capture policy (${receipt.bytes_received} bytes received; none stored)`);
894
+ else
895
+ log(`turn note excerpt redacted by server policy (${receipt.bytes_stored} of ${receipt.bytes_received} bytes stored)`);
896
+ }
724
897
  export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
725
898
  const current = readState(name, env);
726
899
  const guard = current.turn_guard;
@@ -765,10 +938,72 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
765
938
  sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
766
939
  }
767
940
  output = (output || error || sampleError || "").slice(-800);
768
- const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
769
- const tokenCount = tokenOverride !== undefined ? tokenOverride : directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null;
770
- const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount);
771
- writeState(name, { ...current, turn_guard: nextGuard }, env);
941
+ const usage = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()) : null;
942
+ const tokenValue = tokenOverride !== undefined ? tokenOverride : directTokens !== null ? directTokens : usage?.tokens?.total ?? null;
943
+ const tokenCount = tokenValue !== null && Number.isSafeInteger(tokenValue) && tokenValue >= 0 ? tokenValue : null;
944
+ const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, tokenCount, pending.telemetry_enabled === true);
945
+ let nextState = { ...current, turn_guard: nextGuard, turn_note: undefined };
946
+ if (pending.telemetry_enabled && pending.turn_id && current.turn_telemetry_start_pending)
947
+ nextState.turn_telemetry_start_pending = undefined;
948
+ const rawTokens = usage?.tokens;
949
+ const tokens = rawTokens && [rawTokens.input, rawTokens.cached_input, rawTokens.output, rawTokens.reasoning, rawTokens.total].every((value) => Number.isSafeInteger(value) && value >= 0) ? rawTokens : null;
950
+ const reservation = pending.reservation;
951
+ const pricedBreakdownAvailable = !!tokens;
952
+ let meterStatus = tokenCount === null ? "missing" : reservation?.pricing_mode === "priced" && !pricedBreakdownAvailable ? "partial" : "complete";
953
+ let actualCostMicros = null;
954
+ if (reservation && meterStatus === "complete")
955
+ actualCostMicros = estimatedTurnCostMicros(reservation, tokens ?? { input: 0, cached_input: 0, output: 0 });
956
+ if (reservation?.pricing_mode === "priced" && actualCostMicros === null && meterStatus === "complete")
957
+ meterStatus = "partial";
958
+ const telemetryBody = {
959
+ meter_status: meterStatus,
960
+ input_tokens: tokens?.input ?? null,
961
+ cached_input_tokens: tokens?.cached_input ?? null,
962
+ output_tokens: tokens?.output ?? null,
963
+ reasoning_tokens: tokens?.reasoning ?? null,
964
+ total_tokens: tokenCount,
965
+ error_code: error ? (probe.isLimit(error) ? "USAGE_LIMIT" : "HARNESS_ERROR") : sampleError ? "NETWORK_ERROR" : null,
966
+ ...(current.turn_note ? { excerpt: current.turn_note } : {}),
967
+ };
968
+ if (pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
969
+ const settlementBody = reservation ? {
970
+ meter_status: meterStatus,
971
+ ...(tokenCount !== null ? { actual_tokens: tokens?.total ?? tokenCount } : {}),
972
+ ...(meterStatus === "complete" && actualCostMicros !== null ? { actual_cost_micros: actualCostMicros } : {}),
973
+ price_catalog_version: reservation.price_catalog_version,
974
+ } : undefined;
975
+ if (pending.telemetry_enabled || settlementBody) {
976
+ 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 } : {}) };
977
+ nextState.turn_telemetry_completion_pending = waiting;
978
+ }
979
+ }
980
+ writeState(name, nextState, env);
981
+ if ((pending.telemetry_enabled || pending.reservation) && pending.turn_id && env.BSCHAT_MACHINE_SESSION_ID) {
982
+ try {
983
+ const result = pending.telemetry_enabled
984
+ ? 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)
985
+ : null;
986
+ logTurnExcerptDisposition(result, log);
987
+ const settlementBody = nextState.turn_telemetry_completion_pending?.settlement_body;
988
+ let settlement;
989
+ if (settlementBody) {
990
+ 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);
991
+ }
992
+ if (settlementBody && settlementBody.meter_status !== "complete" && !(settlement?.reservation?.state === "settled" && settlement.reservation.meter_status === "complete")) {
993
+ nextState = { ...readState(name, env), turn_telemetry_completion_pending: { ...nextState.turn_telemetry_completion_pending, settlement_recorded: true } };
994
+ writeState(name, nextState, env);
995
+ log("turn meter is unresolved; no next turn starts until the operator reconciles usage");
996
+ return;
997
+ }
998
+ nextState = { ...readState(name, env), turn_telemetry_completion_pending: undefined };
999
+ writeState(name, nextState, env);
1000
+ if (result?.pause_before_next_turn)
1001
+ log(`TURN JUDGMENT PENDING: ${result.pending?.trigger_reasons?.join(", ") ?? "operator review required"}; session stays paused before its next turn`);
1002
+ }
1003
+ catch (e) {
1004
+ log(`turn completed, but telemetry is not durable at the API; the next turn will remain blocked until retry succeeds: ${e.message}`);
1005
+ }
1006
+ }
772
1007
  if (!productive)
773
1008
  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)"}`}`);
774
1009
  else if (nextGuard.consecutive_unproductive === 0)
@@ -899,7 +1134,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
899
1134
  bindSession(sess.kind, sess.id, name);
900
1135
  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] });
901
1136
  }
902
- 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), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
1137
+ 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] : [])] : []);
903
1138
  function escapeXml(s) {
904
1139
  return s.replace(/&/g, "&amp;").replace(/</g, "&lt;").replace(/>/g, "&gt;");
905
1140
  }