benignswarm 0.12.97 → 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.
- package/dist/args.js +1 -0
- package/dist/client.js +50 -8
- package/dist/commands/codex-start.js +10 -5
- package/dist/commands/machine.js +6 -5
- package/dist/commands/turn.js +21 -0
- package/dist/commands/watch.js +215 -13
- package/dist/help.js +10 -4
- package/dist/index.js +2 -0
- package/dist/output.js +2 -0
- package/dist/turn-guard.js +5 -5
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -32,6 +32,7 @@ export const STRING_FLAGS = [
|
|
|
32
32
|
"root", "signing-key", "catalog", "context", "source-commit", "component", "normalized-key",
|
|
33
33
|
"drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
|
|
34
34
|
"stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
|
|
35
|
+
"machine-session-id",
|
|
35
36
|
];
|
|
36
37
|
export const BOOL_FLAGS = [
|
|
37
38
|
"latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
|
package/dist/client.js
CHANGED
|
@@ -25,10 +25,29 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
25
25
|
return strings("detail");
|
|
26
26
|
if (verb === "POST" && /^\/machine-operations\/[^/]+\/finish$/.test(route))
|
|
27
27
|
return strings("result");
|
|
28
|
+
if (verb === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete$/.test(route))
|
|
29
|
+
return strings("excerpt");
|
|
28
30
|
if (verb === "PATCH" && /^\/projects\/[^/]+\/agents\/[^/]+\/moves\/[^/]+$/.test(route))
|
|
29
31
|
return strings("detail");
|
|
30
|
-
if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route))
|
|
31
|
-
|
|
32
|
+
if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route)) {
|
|
33
|
+
if (fields.dry_run === true)
|
|
34
|
+
return [];
|
|
35
|
+
const expected = strings("agreements", "charter", "reason");
|
|
36
|
+
if (Array.isArray(fields.vocabulary)) {
|
|
37
|
+
for (const [index, tag] of fields.vocabulary.entries()) {
|
|
38
|
+
if (!tag || typeof tag !== "object" || Array.isArray(tag))
|
|
39
|
+
continue;
|
|
40
|
+
const t = tag;
|
|
41
|
+
if (typeof t.required_class_clear_reason === "string")
|
|
42
|
+
expected.push(`vocabulary.${index}.required_class_clear_reason`);
|
|
43
|
+
const req = t.required_class;
|
|
44
|
+
if (req && typeof req === "object" && !Array.isArray(req) && typeof req.reason === "string") {
|
|
45
|
+
expected.push(`vocabulary.${index}.required_class.reason`);
|
|
46
|
+
}
|
|
47
|
+
}
|
|
48
|
+
}
|
|
49
|
+
return expected;
|
|
50
|
+
}
|
|
32
51
|
if (verb === "PUT" && /^\/projects\/[^/]+\/context-policy$/.test(route))
|
|
33
52
|
return strings("note");
|
|
34
53
|
if (verb === "POST" && route === "/account/needs/answer")
|
|
@@ -49,10 +68,13 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
49
68
|
});
|
|
50
69
|
return required;
|
|
51
70
|
}
|
|
71
|
+
const reqClassReason = fields.required_class && typeof fields.required_class === "object" && !Array.isArray(fields.required_class) && typeof fields.required_class.reason === "string"
|
|
72
|
+
? ["required_class.reason"]
|
|
73
|
+
: [];
|
|
52
74
|
if (verb === "POST" && /^\/projects\/[^/]+\/work-units$/.test(route))
|
|
53
|
-
return strings("title", "scope");
|
|
75
|
+
return [...strings("title", "scope"), ...reqClassReason];
|
|
54
76
|
if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/assign$/.test(route))
|
|
55
|
-
return strings("title", "scope", "reason");
|
|
77
|
+
return [...strings("title", "scope", "reason"), ...reqClassReason];
|
|
56
78
|
const wu = workUnits.exec(route);
|
|
57
79
|
if (wu?.[1] && wu[2]) {
|
|
58
80
|
const action = wu[2];
|
|
@@ -66,7 +88,7 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
66
88
|
? ["context_decision.reason"]
|
|
67
89
|
: [];
|
|
68
90
|
}
|
|
69
|
-
if (action === "assign" || action === "kind")
|
|
91
|
+
if (action === "assign" || action === "kind" || action === "required-class")
|
|
70
92
|
return strings("reason");
|
|
71
93
|
if (action === "ask")
|
|
72
94
|
return strings("question");
|
|
@@ -153,7 +175,7 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
153
175
|
return ["secret_name"];
|
|
154
176
|
return [];
|
|
155
177
|
}
|
|
156
|
-
export function verifyTextReceipts(response, body, requiredFields = []) {
|
|
178
|
+
export function verifyTextReceipts(response, body, requiredFields = [], allowedRedactedFields = [], allowedDiscardedFields = []) {
|
|
157
179
|
const receipts = Array.isArray(response?.receipts)
|
|
158
180
|
? response.receipts
|
|
159
181
|
: response?.receipt ? [response.receipt] : [];
|
|
@@ -174,9 +196,28 @@ export function verifyTextReceipts(response, body, requiredFields = []) {
|
|
|
174
196
|
const bytes = new TextEncoder().encode(expected).byteLength;
|
|
175
197
|
if (receipt.bytes_received !== bytes)
|
|
176
198
|
throw new CliError("text_receipt_mismatch", `${field}: server received ${receipt.bytes_received} bytes; CLI sent ${bytes}`);
|
|
199
|
+
const sha256 = createHash("sha256").update(expected, "utf8").digest("hex");
|
|
200
|
+
if (receipt.discarded === true) {
|
|
201
|
+
if (!allowedDiscardedFields.includes(field))
|
|
202
|
+
throw new CliError("text_receipt_mismatch", `${field}: server reported an unexpected policy discard`);
|
|
203
|
+
if (receipt.sha256_received !== sha256)
|
|
204
|
+
throw new CliError("text_receipt_mismatch", `${field}: received text SHA-256 does not match the sent text`);
|
|
205
|
+
if (receipt.bytes_stored !== 0 || receipt.sha256 !== undefined)
|
|
206
|
+
throw new CliError("text_receipt_mismatch", `${field}: discarded receipt must confirm that no text was stored`);
|
|
207
|
+
continue;
|
|
208
|
+
}
|
|
209
|
+
if (receipt.redacted === true) {
|
|
210
|
+
if (!allowedRedactedFields.includes(field))
|
|
211
|
+
throw new CliError("text_receipt_mismatch", `${field}: server reported an unexpected policy transformation`);
|
|
212
|
+
if (receipt.sha256_received !== sha256)
|
|
213
|
+
throw new CliError("text_receipt_mismatch", `${field}: received text SHA-256 does not match the sent text`);
|
|
214
|
+
if (!Number.isSafeInteger(receipt.bytes_stored) || receipt.bytes_stored < 0 || typeof receipt.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(receipt.sha256)) {
|
|
215
|
+
throw new CliError("text_receipt_mismatch", `${field}: redacted receipt is missing the stored text size or SHA-256`);
|
|
216
|
+
}
|
|
217
|
+
continue;
|
|
218
|
+
}
|
|
177
219
|
if (receipt.bytes_stored !== bytes)
|
|
178
220
|
throw new CliError("text_receipt_mismatch", `${field}: server stored ${receipt.bytes_stored} of ${bytes} sent bytes`);
|
|
179
|
-
const sha256 = createHash("sha256").update(expected, "utf8").digest("hex");
|
|
180
221
|
if (receipt.sha256 !== sha256)
|
|
181
222
|
throw new CliError("text_receipt_mismatch", `${field}: stored text SHA-256 does not match the sent text`);
|
|
182
223
|
}
|
|
@@ -279,7 +320,8 @@ export class Client {
|
|
|
279
320
|
: undefined;
|
|
280
321
|
throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint);
|
|
281
322
|
}
|
|
282
|
-
|
|
323
|
+
const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
|
|
324
|
+
verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : []);
|
|
283
325
|
return json;
|
|
284
326
|
}
|
|
285
327
|
}
|
|
@@ -68,6 +68,11 @@ export async function harnessStart(p, out, harness) {
|
|
|
68
68
|
const name = str(p.flags, "as");
|
|
69
69
|
if (!name)
|
|
70
70
|
throw new CliError("usage", `${cmd} needs --as <agent-name>`);
|
|
71
|
+
const machineSessionId = str(p.flags, "machine-session-id");
|
|
72
|
+
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))
|
|
73
|
+
throw new CliError("usage", "--machine-session-id must be a UUID");
|
|
74
|
+
if (machineSessionId)
|
|
75
|
+
process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
|
|
71
76
|
const inContainer = bool(p.flags, "in-container");
|
|
72
77
|
let errorSlug = name;
|
|
73
78
|
let watchArgv = null;
|
|
@@ -232,7 +237,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
232
237
|
`If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
|
|
233
238
|
].join("\n");
|
|
234
239
|
const diagnostic = [];
|
|
235
|
-
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour))) {
|
|
240
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, harness))) {
|
|
236
241
|
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the onboarding turn");
|
|
237
242
|
}
|
|
238
243
|
try {
|
|
@@ -303,8 +308,8 @@ export async function harnessStart(p, out, harness) {
|
|
|
303
308
|
mkdirSync(tmp, { recursive: true });
|
|
304
309
|
const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
|
|
305
310
|
const prune = bool(p.flags, "prune");
|
|
306
|
-
watcherEnv = { TMPDIR: tmp, ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
307
|
-
const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model };
|
|
311
|
+
watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
|
|
312
|
+
const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model, ...(machineSessionId ? { machineSessionId } : {}) };
|
|
308
313
|
if (inContainer) {
|
|
309
314
|
const sess = sessionOfExec(exec);
|
|
310
315
|
if (sess)
|
|
@@ -552,7 +557,7 @@ export function runClaudeSandboxSelfCheck(bin, settings, maxBudgetUsd, env, cwd,
|
|
|
552
557
|
/** Guard a model-spending connectivity preflight independently from the agent's real turn. */
|
|
553
558
|
export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
554
559
|
const diagnostic = [];
|
|
555
|
-
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
|
|
560
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "claude-code"))) {
|
|
556
561
|
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the sandbox self-check");
|
|
557
562
|
}
|
|
558
563
|
const probe = probeFor("claude-code", session, ref);
|
|
@@ -603,7 +608,7 @@ export function assertAntigravitySelfCheck(output) {
|
|
|
603
608
|
/** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
|
|
604
609
|
export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
|
|
605
610
|
const diagnostic = [];
|
|
606
|
-
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
|
|
611
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "antigravity"))) {
|
|
607
612
|
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the Antigravity sandbox self-check");
|
|
608
613
|
}
|
|
609
614
|
const prompt = [
|
package/dist/commands/machine.js
CHANGED
|
@@ -44,8 +44,8 @@ function writeMachineState(s) {
|
|
|
44
44
|
* again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
|
|
45
45
|
* 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
|
|
46
46
|
*/
|
|
47
|
-
const START_REV =
|
|
48
|
-
export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
47
|
+
const START_REV = 7;
|
|
48
|
+
export const sessionFingerprint = (s, writable = [], imageDigest = null) => JSON.stringify([s.id, s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR, s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR, s.turn_coalesce_seconds ?? 180, s.thread, ...(writable.length ? [writable] : []), ...(imageDigest ? [imageDigest] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
49
49
|
/** A clear is distinct from a thread that the server has not received from the machine yet. */
|
|
50
50
|
export function reconcileThread(s, local) {
|
|
51
51
|
const clearing = s.thread === null && !!s.thread_override_at && s.thread_override_at !== local?.thread_override_at;
|
|
@@ -69,7 +69,7 @@ export function maintenanceReport(drain, sessions) {
|
|
|
69
69
|
/** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
|
|
70
70
|
export function startArgs(s, thread, writable = []) {
|
|
71
71
|
return [
|
|
72
|
-
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--json",
|
|
72
|
+
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR), "--unproductive-per-hour", String(s.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR), "--turn-coalesce-seconds", String(s.turn_coalesce_seconds ?? 180), "--machine-session-id", s.id, "--json",
|
|
73
73
|
...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
|
|
74
74
|
...(s.model ? ["--model", s.model] : []),
|
|
75
75
|
...(s.effort ? ["--effort", s.effort] : []),
|
|
@@ -708,7 +708,7 @@ export async function reconcile(m, log, reportIntervalSeconds = 30, deps) {
|
|
|
708
708
|
state.sessions[s.id].unpause_applied = s.unpause_at;
|
|
709
709
|
log(`${s.agent}: usage-limit pause lifted by the operator`);
|
|
710
710
|
}
|
|
711
|
-
out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
|
|
711
|
+
out.push({ id: s.id, state: "running", dir: s.dir, thread: th, watcher: watcherState, last_turn: lastTurnLine(s.agent), turn_judgment: s.turn_judgment ?? null, ...turnFacts(s.agent, s.harness, th, s.turns_per_hour ?? DEFAULT_TURNS_PER_HOUR) });
|
|
712
712
|
}
|
|
713
713
|
catch (e) {
|
|
714
714
|
const error = e.message.slice(0, 1000);
|
|
@@ -1794,7 +1794,8 @@ export async function machine(p, out) {
|
|
|
1794
1794
|
const state = readMachineState();
|
|
1795
1795
|
const rows = desired.map((s) => {
|
|
1796
1796
|
const w = watcherServices().find((x) => x.label === watchLabelOf(s.agent));
|
|
1797
|
-
|
|
1797
|
+
const judgment = s.turn_judgment ? ` judgment ${s.turn_judgment.state}: ${s.turn_judgment.trigger_reasons.join(", ")}` : "";
|
|
1798
|
+
return `${s.agent.padEnd(32)} desired ${s.desired.padEnd(8)} watcher ${w ? (serviceActive(w) ? "active" : "inactive") : "none"} ${s.harness}/${s.provider ?? "anthropic"} thread ${state.sessions[s.id]?.thread ?? s.thread ?? "-"}${judgment} ${s.dir}`;
|
|
1798
1799
|
});
|
|
1799
1800
|
return out.print([`machine ${m.name} (${m.url})`, ...rows, rows.length ? "" : "no sessions declared"].join("\n"), { machine: m.name, sessions: desired, local: state });
|
|
1800
1801
|
}
|
|
@@ -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
|
+
}
|
package/dist/commands/watch.js
CHANGED
|
@@ -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
|
-
|
|
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");
|
|
@@ -261,7 +266,7 @@ export async function watch(p, out) {
|
|
|
261
266
|
await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
|
|
262
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);
|
|
263
268
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
264
|
-
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour);
|
|
269
|
+
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
|
|
265
270
|
else {
|
|
266
271
|
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
|
|
267
272
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
@@ -563,6 +568,18 @@ function stopBenchedWatcher(name, reason, log) {
|
|
|
563
568
|
if (svc)
|
|
564
569
|
removeService(svc);
|
|
565
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
|
+
}
|
|
566
583
|
const TURN_RETRY_MS = 5 * 60_000;
|
|
567
584
|
const KEY_CHECK_MS = 5 * 60_000;
|
|
568
585
|
/**
|
|
@@ -572,7 +589,7 @@ const KEY_CHECK_MS = 5 * 60_000;
|
|
|
572
589
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
573
590
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
574
591
|
*/
|
|
575
|
-
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) {
|
|
576
593
|
const turn = ctl.turn;
|
|
577
594
|
if (turn) {
|
|
578
595
|
if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
|
|
@@ -726,7 +743,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPer
|
|
|
726
743
|
writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined }, env);
|
|
727
744
|
}
|
|
728
745
|
await wake((t) => { ctl.turn = t; }, async () => {
|
|
729
|
-
return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour);
|
|
746
|
+
return beginTurnGuardAttempt(name, turnsPerHour, log, env, unproductivePerHour, env.BSCHAT_MACHINE_SESSION_ID, harness);
|
|
730
747
|
});
|
|
731
748
|
}
|
|
732
749
|
async function turnActivity(name, env) {
|
|
@@ -736,15 +753,57 @@ async function turnActivity(name, env) {
|
|
|
736
753
|
return snapshot;
|
|
737
754
|
}
|
|
738
755
|
/** 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) {
|
|
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
|
+
}
|
|
740
798
|
const before = await turnActivity(name, env);
|
|
741
|
-
|
|
799
|
+
current = readState(name, env);
|
|
742
800
|
if (current.turn_guard?.fault) {
|
|
743
801
|
log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
744
802
|
return false;
|
|
745
803
|
}
|
|
746
|
-
const
|
|
747
|
-
|
|
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);
|
|
748
807
|
if (!begun.start) {
|
|
749
808
|
if (begun.state.fault)
|
|
750
809
|
log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
@@ -752,8 +811,89 @@ export async function beginTurnGuardAttempt(name, turnsPerHour, log, env = proce
|
|
|
752
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()}`);
|
|
753
812
|
return false;
|
|
754
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);
|
|
755
886
|
return true;
|
|
756
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
|
+
}
|
|
757
897
|
export async function completePendingTurnGuard(name, probe, log, outputOverride, tokenOverride, env = process.env) {
|
|
758
898
|
const current = readState(name, env);
|
|
759
899
|
const guard = current.turn_guard;
|
|
@@ -798,10 +938,72 @@ export async function completePendingTurnGuard(name, probe, log, outputOverride,
|
|
|
798
938
|
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
|
|
799
939
|
}
|
|
800
940
|
output = (output || error || sampleError || "").slice(-800);
|
|
801
|
-
const
|
|
802
|
-
const
|
|
803
|
-
const
|
|
804
|
-
|
|
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
|
+
}
|
|
805
1007
|
if (!productive)
|
|
806
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)"}`}`);
|
|
807
1009
|
else if (nextGuard.consecutive_unproductive === 0)
|
|
@@ -932,7 +1134,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
932
1134
|
bindSession(sess.kind, sess.id, name);
|
|
933
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] });
|
|
934
1136
|
}
|
|
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] : [])] : []);
|
|
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] : [])] : []);
|
|
936
1138
|
function escapeXml(s) {
|
|
937
1139
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
938
1140
|
}
|
package/dist/help.js
CHANGED
|
@@ -28,6 +28,7 @@ GitHub connection and repository status are available in the console and through
|
|
|
28
28
|
Environment problems: agents report bounded, redacted observations with b9s environment report; reports use scoped project or machine access, account-scoped evidence, and only the agent's own blocked units. Agents can append observations but cannot claim, diagnose, or resolve issues. Operators and agents whose role has own_environment_problems can manage visible issues. Operators use Account → Environment in the console to filter and inspect issues, claim/assign/reassign, record diagnoses, and resolve with a note and verification. Manual diagnoses use source agent; doctor/daemon provenance is for actual check results. Banner links open the same issue detail with impact context. Issue detail links active notices in the same scope and current machine-session faults related to its machine or explicitly linked unit owner. The read-only steward summary lists active linked issues and currently waiting linked units, without publishing notices or creating work. Machine issue views respect linked-project access. Spending impact is unknown and creates no banner until unit-attributed telemetry lands in WU #236; see packages/skill/references/api.md.
|
|
29
29
|
|
|
30
30
|
Work-unit open, start, submit and close endpoints accept context fill and compaction metadata on lifecycle events. Report explicit unknown reasons when unavailable; never send prompt or response text as context. Context aggregation is grouped by the event owner and its stamped model/effort. Context policies (keep | compact | clear | agent-decides) resolve unit > role > project > system default keep, freeze on assignment/open, audit settings and action-metadata decisions via GET/PUT /projects/:p/context-policy, POST /projects/:p/work-units/:n/context-policy, and POST /projects/:p/work-units/:n/context-policy/decision, and fail closed until an assigner or operator updates a blocked unit. See packages/skill/references/api.md for field validation and response shapes.
|
|
31
|
+
Build dispatch checks role qualifications, capabilities, holds, reservations and operator-only required_class first, then ranks eligible workers by routing_policy weights, build quality guardrail, weakest-tag tie-break and build exploration budget, falling back when the preferred class is busy and recording route_decision / dispatch_reasons on units and events. Operators set/clear hard required_class with an audited reason via POST /projects/:p/work-units/:n/required-class (or tag definitions) and inspect cleared legacy min_tier rows via GET /projects/:p/routing/tier-migration (never guessing class mappings). Console routing controls are WU #244; CLI routing view/controls are WU #242.
|
|
31
32
|
|
|
32
33
|
Agent commands
|
|
33
34
|
b9s login --as <name> --key <bs_agent_...> [--url <api>] [--label <machine-label>]
|
|
@@ -172,8 +173,11 @@ Agent commands
|
|
|
172
173
|
--env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
|
|
173
174
|
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
|
|
174
175
|
--service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
|
|
175
|
-
itself (--harness codex|claude-code|dsh|antigravity --session <id>);
|
|
176
|
-
agent-key call
|
|
176
|
+
itself (--harness codex|claude-code|dsh|antigravity --session <id> [--machine-session-id uuid]); without activated judgment capture,
|
|
177
|
+
3 consecutive turns without an agent-key call fault it and six unproductive turns in a rolling hour also fault.
|
|
178
|
+
With judgment capture activated, these become triggers and the watcher pauses before the next turn;
|
|
179
|
+
hard-budget caps still reserve each launch independently. Capture defaults off; hard caps alone do not activate it.
|
|
180
|
+
The 60-turn
|
|
177
181
|
hourly cap pauses a busy agent until a turn rolls out, then resumes automatically. Set
|
|
178
182
|
--turns-per-hour 1..60, --unproductive-per-hour 1..60, and --turn-coalesce-seconds 0..3600;
|
|
179
183
|
direct wake-ups coalesce for 180s by default; 0 disables it. Operators and urgent-marked items
|
|
@@ -190,16 +194,18 @@ Agent commands
|
|
|
190
194
|
b9s environment report --project <p> | --machine <m> --title <text> --category <name> --component <name> --description <what failed> [--normalized-key <key>] [--evidence <id,...>] [--units <id,...>]
|
|
191
195
|
submit a bounded observation; evidence is account-scoped, and agents may link only their own units
|
|
192
196
|
b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
|
|
193
|
-
b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--dsh path] [--agy path]
|
|
197
|
+
b9s start --harness codex|claude-code|dsh|antigravity --as <project>/<name> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--writable-root path]... [--max-budget-usd n] [--turns-per-hour 1..60] [--unproductive-per-hour 1..60] [--turn-coalesce-seconds 0..3600] [--machine-session-id uuid] [--dsh path] [--agy path]
|
|
194
198
|
run an agent headless: enroll, start or adopt its session, turn-mode watcher
|
|
199
|
+
--machine-session-id is normally supplied by b9s-admin for a managed machine session
|
|
195
200
|
Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
|
|
196
201
|
Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
|
|
197
|
-
missing usage remains reserved
|
|
202
|
+
missing usage remains reserved. Judgment capture has a separate default-off activation in console WU #238.
|
|
198
203
|
Admin-only account reads: GET /account/turn-spend/reservations and
|
|
199
204
|
GET /account/turn-spend/sessions/:session/reservations list unresolved reservations;
|
|
200
205
|
GET /account/turn-budget/audit lists policy changes. All three are paged and account-scoped.
|
|
201
206
|
(b9s codex start is the same with --harness codex)
|
|
202
207
|
b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
|
|
208
|
+
b9s turn note "<short progress summary>" [--as <a>] save a 300-character turn-end excerpt for an enabled managed session; it is labelled unverified
|
|
203
209
|
b9s machine bootstrap --url <api> [--retrieve-ec2 | --token-file <path> | --token <bs_boot_...>] [--name <m>] retrieve (over TLS+IMDSv2/STS) and exchange a single-use cloud bootstrap token once, scrub it, and write mode-0600 credentials
|
|
204
210
|
b9s machine run [--interval seconds] | once | build-images | status | prepare | service default 30s, 1..3600; prepare checks dsh availability/version (Linux has no DSH build)
|
|
205
211
|
b9s checkpoint "<title>" --body "..." a resume note without retiring: what you are doing, open threads, next steps;
|
package/dist/index.js
CHANGED
|
@@ -10,6 +10,7 @@ import { watch } from "./commands/watch.js";
|
|
|
10
10
|
import { feedback } from "./commands/feedback.js";
|
|
11
11
|
import { goal } from "./commands/goal.js";
|
|
12
12
|
import { wake } from "./commands/wake.js";
|
|
13
|
+
import { turn } from "./commands/turn.js";
|
|
13
14
|
import { antigravity } from "./commands/antigravity.js";
|
|
14
15
|
import { codex, unpause } from "./commands/codex.js";
|
|
15
16
|
import { harnessStart } from "./commands/codex-start.js";
|
|
@@ -72,6 +73,7 @@ const COMMANDS = {
|
|
|
72
73
|
feedback,
|
|
73
74
|
goal,
|
|
74
75
|
wake,
|
|
76
|
+
turn,
|
|
75
77
|
antigravity,
|
|
76
78
|
codex,
|
|
77
79
|
start: async (p, out) => {
|
package/dist/output.js
CHANGED
|
@@ -4,6 +4,8 @@ function receiptLine(data) {
|
|
|
4
4
|
return null;
|
|
5
5
|
return receipts.map((r) => {
|
|
6
6
|
const label = receipts.length > 1 && typeof r.field === "string" ? ` ${r.field}` : "";
|
|
7
|
+
if (r.redacted === true)
|
|
8
|
+
return `${typeof r.field === "string" ? r.field : "text"} redacted by policy: stored ${r.bytes_stored} of ${r.bytes_received} bytes, sha256 ${(String(r.sha256 ?? "")).slice(0, 12)}`;
|
|
7
9
|
return `stored${label} ${r.bytes_stored} bytes, sha256 ${(String(r.sha256 ?? "")).slice(0, 12)}`;
|
|
8
10
|
}).join("; ");
|
|
9
11
|
}
|
package/dist/turn-guard.js
CHANGED
|
@@ -39,7 +39,7 @@ function faultFor(state, reason, now, turns, output, tokenTurns = turns) {
|
|
|
39
39
|
output_tail: output.slice(-OUTPUT_TAIL_LIMIT),
|
|
40
40
|
};
|
|
41
41
|
}
|
|
42
|
-
export function beginGuardedTurn(state, maxTurnsPerHour, now, activitySeqBefore, unproductivePerHour) {
|
|
42
|
+
export function beginGuardedTurn(state, maxTurnsPerHour, now, activitySeqBefore, unproductivePerHour, turnId, telemetryEnabled = false) {
|
|
43
43
|
const current = state ?? emptyTurnGuard();
|
|
44
44
|
const turns = recentTurns(current, now);
|
|
45
45
|
const next = { ...current, turns, unproductive_per_hour: unproductivePerHour ?? current.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR };
|
|
@@ -48,10 +48,10 @@ export function beginGuardedTurn(state, maxTurnsPerHour, now, activitySeqBefore,
|
|
|
48
48
|
if (turns.length >= maxTurnsPerHour) {
|
|
49
49
|
return { state: next, start: false, pause_until: turns[0].at + HOUR_MS };
|
|
50
50
|
}
|
|
51
|
-
next.turns = [...turns, { at: now, productive: null, estimated_tokens: 0, ...(activitySeqBefore === undefined ? {} : { activity_seq_before: activitySeqBefore }) }];
|
|
51
|
+
next.turns = [...turns, { at: now, productive: null, estimated_tokens: 0, ...(turnId ? { turn_id: turnId, telemetry_enabled: telemetryEnabled } : {}), ...(activitySeqBefore === undefined ? {} : { activity_seq_before: activitySeqBefore }) }];
|
|
52
52
|
return { state: next, start: true };
|
|
53
53
|
}
|
|
54
|
-
export function completeGuardedTurn(state, now, productive, output, tokens) {
|
|
54
|
+
export function completeGuardedTurn(state, now, productive, output, tokens, softTriggers = false) {
|
|
55
55
|
if (state.fault)
|
|
56
56
|
return state;
|
|
57
57
|
const turns = state.turns;
|
|
@@ -70,11 +70,11 @@ export function completeGuardedTurn(state, now, productive, output, tokens) {
|
|
|
70
70
|
const currentHour = recentTurns({ ...state, turns: completed }, now);
|
|
71
71
|
const consecutive = productive ? 0 : state.consecutive_unproductive + 1;
|
|
72
72
|
const next = { turns: currentHour, consecutive_unproductive: consecutive, unproductive_per_hour: state.unproductive_per_hour, fault: null };
|
|
73
|
-
if (!productive && consecutive >= MAX_UNPRODUCTIVE_TURNS) {
|
|
73
|
+
if (!softTriggers && !productive && consecutive >= MAX_UNPRODUCTIVE_TURNS) {
|
|
74
74
|
const fault = faultFor(next, "unproductive", now, currentHour, output, completed.slice(-MAX_UNPRODUCTIVE_TURNS));
|
|
75
75
|
next.fault = fault;
|
|
76
76
|
}
|
|
77
|
-
else if (!productive) {
|
|
77
|
+
else if (!softTriggers && !productive) {
|
|
78
78
|
const unproductive = currentHour.filter((turn) => turn.productive === false);
|
|
79
79
|
const limit = state.unproductive_per_hour ?? DEFAULT_UNPRODUCTIVE_PER_HOUR;
|
|
80
80
|
if (unproductive.length >= limit) {
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.98";
|