benignswarm 0.12.103 → 0.12.105
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/commands/image-admin.js +9 -1
- package/dist/commands/machine-admin.js +87 -11
- package/dist/commands/machine.js +219 -11
- package/dist/commands/watch.js +129 -23
- package/dist/commands/wu.js +130 -9
- package/dist/container.js +46 -1
- package/dist/help.js +15 -10
- package/dist/hosted-registry-ecr.js +55 -0
- package/dist/hosted-registry-push.js +40 -0
- package/dist/hosted-registry-session.js +26 -0
- package/dist/hosted-registry.js +73 -0
- package/dist/usage.js +21 -0
- package/dist/version.js +1 -1
- package/package.json +6 -1
package/dist/commands/watch.js
CHANGED
|
@@ -40,19 +40,9 @@ export async function reportWatcherCapabilities(creds, project, definitions, cwd
|
|
|
40
40
|
const results = await probeCapabilities(definitions, cwd);
|
|
41
41
|
await Client.forAgent(creds, undefined, { presence: false, machineIdentity: true }).call("POST", `/projects/${project}/agents/me/capabilities`, { results });
|
|
42
42
|
}
|
|
43
|
-
|
|
44
|
-
* Event bridge for harnesses that can be woken from outside (Codex: `codex queue --thread <id>`).
|
|
45
|
-
*
|
|
46
|
-
* Default mode queues ONE short wake-up and nothing else until the agent has read (its own
|
|
47
|
-
* `b9s inbox --unread` / `b9s read` advance the shared cursors). Content is never put in
|
|
48
|
-
* the queue, so the agent always reads it fresh and superseded messages collapse naturally.
|
|
49
|
-
* A direct message from a human operator re-wakes immediately even while a wake-up is pending.
|
|
50
|
-
* `--full` restores the old behaviour of queueing the text itself (for harnesses that cannot run
|
|
51
|
-
* b9s themselves when woken).
|
|
52
|
-
*/
|
|
53
|
-
export async function watch(p, out) {
|
|
43
|
+
export async function watch(p, out, dependencies = {}) {
|
|
54
44
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
55
|
-
|
|
45
|
+
let exec = str(p.flags, "exec");
|
|
56
46
|
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
57
47
|
if (!Number.isInteger(interval) || interval < 5)
|
|
58
48
|
throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
|
|
@@ -167,7 +157,7 @@ export async function watch(p, out) {
|
|
|
167
157
|
}
|
|
168
158
|
log(`watching${exec ? `, will run: ${exec}` : ""} every ${interval}s (${full ? "full text" : turnMode ? `turn mode, at most ${turnTimeout} min a turn` : "single wake-up"} mode)`);
|
|
169
159
|
if (!once) {
|
|
170
|
-
await waitForWatcherStartup(startupJitterSeconds, log, (milliseconds) => waitIntervalOrStop(milliseconds, stopped));
|
|
160
|
+
await (dependencies.waitForStartup ?? waitForWatcherStartup)(startupJitterSeconds, log, (milliseconds) => (dependencies.wait ?? waitIntervalOrStop)(milliseconds, stopped));
|
|
171
161
|
if (stopping)
|
|
172
162
|
return stoppingCode;
|
|
173
163
|
}
|
|
@@ -191,9 +181,31 @@ export async function watch(p, out) {
|
|
|
191
181
|
// the key on its own clock.
|
|
192
182
|
let lastKeyCheck = 0;
|
|
193
183
|
const ctl = { turn: null, failedAt: 0, loggedRunning: null, loggedFailureAt: null, pausedUntil: 0, pausedAt: 0 };
|
|
194
|
-
|
|
184
|
+
let probe = turn ? turn.harness === "codex" ? followCurrentCodexProbe(name, turn.session) : probeFor(turn.harness, turn.session, name) : null;
|
|
195
185
|
let resumeBriefDelivered = false;
|
|
196
186
|
while (!stopping) {
|
|
187
|
+
if (turn?.harness === "codex") {
|
|
188
|
+
const current = readState(name);
|
|
189
|
+
const clear = current.pending_context_clear;
|
|
190
|
+
const observedThread = current.harness_session?.session_id;
|
|
191
|
+
const freshThread = clear?.status === "completed" ? clear.new_thread_id
|
|
192
|
+
: clear?.status === "pending" && observedThread && observedThread !== clear.old_thread_id ? observedThread
|
|
193
|
+
: null;
|
|
194
|
+
if (freshThread && freshThread !== turn.session) {
|
|
195
|
+
exec = resumeFreshCodexExecTemplate(exec, freshThread);
|
|
196
|
+
turn.session = freshThread;
|
|
197
|
+
probe = followCurrentCodexProbe(name, freshThread);
|
|
198
|
+
bindSession("codex", freshThread, name);
|
|
199
|
+
}
|
|
200
|
+
if (freshThread && clear?.status === "pending") {
|
|
201
|
+
writeState(name, { ...readState(name), pending_context_clear: { ...clear, new_thread_id: freshThread } });
|
|
202
|
+
log(`context clear opened fresh Codex thread ${freshThread}; the pending unit start will complete its recorded decision`);
|
|
203
|
+
}
|
|
204
|
+
else if (freshThread && clear?.status === "completed") {
|
|
205
|
+
writeState(name, { ...readState(name), pending_context_clear: undefined });
|
|
206
|
+
log(`context clear completed; watcher now follows fresh Codex thread ${freshThread}`);
|
|
207
|
+
}
|
|
208
|
+
}
|
|
197
209
|
if (activity && heartbeatClient)
|
|
198
210
|
lastSample = await heartbeatIfActive(heartbeatClient, activity, lastSample, interval, log);
|
|
199
211
|
if (stopping)
|
|
@@ -209,7 +221,7 @@ export async function watch(p, out) {
|
|
|
209
221
|
if (taken)
|
|
210
222
|
log(`worktree scan: skipped, ${taken}`);
|
|
211
223
|
else {
|
|
212
|
-
const r = await scanProject(scanCreds, scanCreds.project);
|
|
224
|
+
const r = await (dependencies.scanProject ?? scanProject)(scanCreds, scanCreds.project);
|
|
213
225
|
log(`worktree scan: ${r.recorded} in ${r.repo}${r.missing ? `, ${r.missing} gone` : ""}`);
|
|
214
226
|
}
|
|
215
227
|
if (bool(p.flags, "prune")) {
|
|
@@ -241,7 +253,7 @@ export async function watch(p, out) {
|
|
|
241
253
|
const processInfo = await client.call("GET", `/projects/${scanCreds.project}/process`);
|
|
242
254
|
const definitions = (processInfo.process?.definition?.capabilities ?? []);
|
|
243
255
|
if (definitions.length) {
|
|
244
|
-
await reportWatcherCapabilities(scanCreds, scanCreds.project, definitions, process.cwd());
|
|
256
|
+
await (dependencies.reportCapabilities ?? reportWatcherCapabilities)(scanCreds, scanCreds.project, definitions, process.cwd());
|
|
245
257
|
log(`capabilities: probed ${definitions.length} project requirements`);
|
|
246
258
|
}
|
|
247
259
|
lastCapabilities = Date.now();
|
|
@@ -274,13 +286,14 @@ export async function watch(p, out) {
|
|
|
274
286
|
}
|
|
275
287
|
if (!full) {
|
|
276
288
|
try {
|
|
277
|
-
|
|
278
|
-
|
|
279
|
-
|
|
289
|
+
const activeProbe = probe;
|
|
290
|
+
if (activeProbe)
|
|
291
|
+
await (dependencies.turnStep ?? turnStep)(ctl, activeProbe, turnTimeout, log, async (sink, beforeTurn) => {
|
|
292
|
+
const result = await (dependencies.wakeOnce ?? 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", () => activeProbe.beginTurn?.(), beforeTurn, turn?.harness === "claude-code" ? turn.session : undefined, turn?.coalesceSeconds ?? 0, dependencies.wakeOnceDependencies);
|
|
280
293
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
281
294
|
}, name, turn?.turnsPerHour ?? turnsPerHour, process.env, turn?.unproductivePerHour ?? unproductivePerHour, turn?.harness);
|
|
282
295
|
else {
|
|
283
|
-
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
|
|
296
|
+
const result = await (dependencies.wakeOnce ?? wakeOnce)(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered, undefined, false, undefined, undefined, undefined, 0, dependencies.wakeOnceDependencies);
|
|
284
297
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
285
298
|
}
|
|
286
299
|
}
|
|
@@ -301,7 +314,7 @@ export async function watch(p, out) {
|
|
|
301
314
|
return stoppingCode;
|
|
302
315
|
if (once)
|
|
303
316
|
return;
|
|
304
|
-
await waitIntervalOrStop(watchPollMs(interval), stopped);
|
|
317
|
+
await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
|
|
305
318
|
continue;
|
|
306
319
|
}
|
|
307
320
|
let u;
|
|
@@ -356,7 +369,7 @@ export async function watch(p, out) {
|
|
|
356
369
|
}
|
|
357
370
|
if (once)
|
|
358
371
|
return;
|
|
359
|
-
await waitIntervalOrStop(watchPollMs(interval), stopped);
|
|
372
|
+
await (dependencies.wait ?? waitIntervalOrStop)(watchPollMs(interval), stopped);
|
|
360
373
|
}
|
|
361
374
|
return stoppingCode;
|
|
362
375
|
}
|
|
@@ -370,6 +383,87 @@ async function waitIntervalOrStop(ms, stopped) {
|
|
|
370
383
|
if (timer)
|
|
371
384
|
clearTimeout(timer);
|
|
372
385
|
}
|
|
386
|
+
const CODEX_THREAD_ID = /[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/i;
|
|
387
|
+
/** Follow a Codex exec that opens a new thread, as soon as the session hook records its id. */
|
|
388
|
+
export function followCurrentCodexProbe(name, initialThread) {
|
|
389
|
+
const active = () => {
|
|
390
|
+
const session = readState(name).harness_session;
|
|
391
|
+
return session?.harness === "codex" && session.session_id && session.session_id !== initialThread
|
|
392
|
+
? probeFor("codex", session.session_id, name)
|
|
393
|
+
: probeFor("codex", initialThread, name);
|
|
394
|
+
};
|
|
395
|
+
return {
|
|
396
|
+
get label() { return active().label; },
|
|
397
|
+
get what() { return active().what; },
|
|
398
|
+
phase: () => active().phase(),
|
|
399
|
+
startedSince: (ms) => active().startedSince(ms),
|
|
400
|
+
turnError: () => active().turnError(),
|
|
401
|
+
turnOutput: () => active().turnOutput?.() ?? "",
|
|
402
|
+
turnTokens: () => active().turnTokens?.() ?? null,
|
|
403
|
+
limitUntil: (error) => active().limitUntil(error),
|
|
404
|
+
isLimit: (error) => active().isLimit(error),
|
|
405
|
+
beginTurn: () => active().beginTurn?.(),
|
|
406
|
+
};
|
|
407
|
+
}
|
|
408
|
+
/** Convert a Codex resume template into its one-shot new-thread equivalent. */
|
|
409
|
+
export function freshCodexExecTemplate(exec) {
|
|
410
|
+
const thread = threadOfExec(exec);
|
|
411
|
+
if (!thread)
|
|
412
|
+
throw new CliError("context_clear_unsupported", "turn-mode clear requires a Codex exec resume command with a known thread id");
|
|
413
|
+
return exec.replace(/\bcodex\s+exec\s+resume\s+[0-9a-f-]{36}\b/i, "codex exec");
|
|
414
|
+
}
|
|
415
|
+
/** The watcher follows the verified fresh thread for subsequent turns. */
|
|
416
|
+
export function resumeFreshCodexExecTemplate(exec, thread) {
|
|
417
|
+
if (!CODEX_THREAD_ID.test(thread))
|
|
418
|
+
throw new CliError("context_clear_failed", "the fresh Codex thread id is invalid; watcher remains on its previous thread");
|
|
419
|
+
const replacedResume = exec.replace(/\bcodex\s+exec\s+resume\s+[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}\b/i, `codex exec resume ${thread}`);
|
|
420
|
+
if (replacedResume !== exec)
|
|
421
|
+
return replacedResume;
|
|
422
|
+
const resumed = exec.replace(/\bcodex\s+exec\s+(?!resume\b)/i, `codex exec resume ${thread} `);
|
|
423
|
+
if (resumed === exec)
|
|
424
|
+
throw new CliError("context_clear_failed", "could not update the Codex turn command to follow the fresh thread");
|
|
425
|
+
return resumed;
|
|
426
|
+
}
|
|
427
|
+
async function pendingClearTurn(name, exec, clear, st, log, model, turnSink, beforeTurn, allowTurn, dependencies = {}) {
|
|
428
|
+
if (clear.harness !== "codex")
|
|
429
|
+
throw new CliError("context_clear_unsupported", `fresh-thread turn-mode clear is not implemented for ${clear.harness}`);
|
|
430
|
+
const alreadyFresh = !!clear.new_thread_id && st.harness_session?.session_id === clear.new_thread_id;
|
|
431
|
+
const command = alreadyFresh ? exec : freshCodexExecTemplate(exec);
|
|
432
|
+
const creds = loadAgent(name);
|
|
433
|
+
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
434
|
+
const [handoffResponse, unitResponse] = await Promise.all([
|
|
435
|
+
client.call("GET", `/handoffs/${encodeURIComponent(clear.checkpoint_ref)}`),
|
|
436
|
+
client.call("GET", `/projects/${encodeURIComponent(clear.project)}/work-units/${clear.work_unit_number}`),
|
|
437
|
+
]);
|
|
438
|
+
const handoff = handoffResponse.handoff;
|
|
439
|
+
const unit = unitResponse.unit;
|
|
440
|
+
if (handoff?.kind !== "resume" || handoff.agent_name !== creds.agent)
|
|
441
|
+
throw new Error("pending checkpoint is no longer an owner-authored resume note");
|
|
442
|
+
if (!unit || unit.owner_name !== creds.agent || !["assigned", "open", "changes_requested"].includes(unit.status) || unit.context_policy_decision?.outcome !== "pending"
|
|
443
|
+
|| unit.context_policy_decision.checkpoint_ref !== clear.checkpoint_ref
|
|
444
|
+
|| unit.context_policy_decision.old_thread_id !== clear.old_thread_id) {
|
|
445
|
+
throw new Error(`WU #${clear.work_unit_number} no longer has this owner's pending clear decision`);
|
|
446
|
+
}
|
|
447
|
+
const seq = (st.watch_seq ?? 0) + 1;
|
|
448
|
+
const prompt = [
|
|
449
|
+
`[b9s] Turn #${seq}, started by your BenignSwarm watcher for a pending context clear. This is a fresh thread; do not refer to the old conversation.`,
|
|
450
|
+
`First read these durable rules and the resume note, then start WU #${unit.number} before other work.`,
|
|
451
|
+
`Resume note (${clear.checkpoint_ref}):\n${handoff.body ?? "(empty resume note)"}`,
|
|
452
|
+
`Assigned work unit #${unit.number}: ${unit.title}\n\nComplete scope:\n${unit.scope}`,
|
|
453
|
+
`Start it now with: b9s wu start ${unit.number} --context-checkpoint-ref ${clear.checkpoint_ref}`,
|
|
454
|
+
`That command completes the pending clear only after this new thread is locally recorded. If any step fails, report the named failure and leave the unit unstarted.`,
|
|
455
|
+
].join("\n\n");
|
|
456
|
+
const delivered = await deliver(name, command, prompt, `fresh-thread clear for WU #${unit.number}`, "direct", new TextEncoder().encode(prompt).byteLength, log, "context clear; ", seq, turnSink, {}, undefined, model, false, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}) }, allowTurn);
|
|
457
|
+
if (!delivered)
|
|
458
|
+
return { sent: false, recoveryBriefDelivered: false };
|
|
459
|
+
writeState(name, {
|
|
460
|
+
...readState(name),
|
|
461
|
+
watch_seq: seq,
|
|
462
|
+
watch_pending: { seq, at: Date.now(), inbox_after: st.inbox_after, channel_read: st.channel_read ?? {} },
|
|
463
|
+
watch_dormant_logged_at: undefined,
|
|
464
|
+
});
|
|
465
|
+
return { sent: true, recoveryBriefDelivered: false };
|
|
466
|
+
}
|
|
373
467
|
export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn, sessionId, turnCoalesceSeconds = 0, dependencies = {}) {
|
|
374
468
|
const debug = (message) => { if (process.env.BSCHAT_WATCH_DEBUG === "1")
|
|
375
469
|
log(`debug poll: ${message}`); };
|
|
@@ -402,6 +496,18 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
402
496
|
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`);
|
|
403
497
|
return { sent: false, recoveryBriefDelivered: false };
|
|
404
498
|
}
|
|
499
|
+
const clear = st.pending_context_clear;
|
|
500
|
+
if (clear?.status === "pending" && turnSink) {
|
|
501
|
+
try {
|
|
502
|
+
if (!exec || turnStdin)
|
|
503
|
+
throw new CliError("context_clear_unsupported", "the turn watcher has no Codex command template to start a fresh thread");
|
|
504
|
+
return await pendingClearTurn(name, exec, clear, st, log, model, turnSink, beforeTurn, allowTurn, dependencies);
|
|
505
|
+
}
|
|
506
|
+
catch (error) {
|
|
507
|
+
log(`context clear for WU #${clear.work_unit_number} failed before a new turn was started: ${error.message}; the unit remains unstarted`);
|
|
508
|
+
return { sent: false, recoveryBriefDelivered: false };
|
|
509
|
+
}
|
|
510
|
+
}
|
|
405
511
|
const u = await (dependencies.gatherUpdates ?? gatherUpdates)(name, { force: true, model, delivery: "watch", dryRun: true, watchCursor: true });
|
|
406
512
|
const commitWatchCursor = () => {
|
|
407
513
|
if (!u?.watchCursorAfter)
|
|
@@ -500,7 +606,7 @@ export async function wakeOnce(name, exec, unackedAfter, followDelay, log, model
|
|
|
500
606
|
// the acknowledgement, operator note, process pointer, read commands, and delivery body.
|
|
501
607
|
const line = wake;
|
|
502
608
|
debug(`wake: delivering ${u?.tier ?? "process"} activity as wake-up #${seq}`);
|
|
503
|
-
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { sessionId }, allowTurn))) {
|
|
609
|
+
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, { ...(dependencies.startTurn ? { startTurn: dependencies.startTurn } : {}), sessionId }, allowTurn))) {
|
|
504
610
|
debug("no wake: delivery failed or turn guard denied the launch");
|
|
505
611
|
return { sent: false, recoveryBriefDelivered: false };
|
|
506
612
|
}
|
package/dist/commands/wu.js
CHANGED
|
@@ -3,9 +3,9 @@ import { lstatSync, mkdtempSync, readFileSync, rmSync, writeFileSync } from "nod
|
|
|
3
3
|
import { bool, str } from "../args.js";
|
|
4
4
|
import { Client } from "../client.js";
|
|
5
5
|
import { agentRef, loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
6
|
-
import { readState } from "../state.js";
|
|
6
|
+
import { readState, writeState } from "../state.js";
|
|
7
7
|
import { codexRollout, sessionsOf } from "../sessions.js";
|
|
8
|
-
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionUsage } from "../usage.js";
|
|
8
|
+
import { claudeSessionWithHookMetadata, sessionCompactions, sessionContext, sessionStart, sessionUsage } from "../usage.js";
|
|
9
9
|
import { CliError } from "../errors.js";
|
|
10
10
|
import { branchAndHead, commitAtTime, ensureReviewWorktree, ensureWorktree, fetchRef, fetchRemoteBranch, findRemoteCommitBranch, formatRemoteCommitFailure, formatRemoteCommitSuccess, fullSha, isAncestor, isShaBranchName, removeWorktreeIfClean, repoName, repoParent, symbolicBranch, verifyMergedCommit, verifyNoCommitsBeyondTarget, worktreeForBranch } from "../git.js";
|
|
11
11
|
import { join, resolve } from "node:path";
|
|
@@ -81,6 +81,10 @@ async function contextDecisionForStart(client, base, unit, name, p, events = [])
|
|
|
81
81
|
const creds = loadAgent(name);
|
|
82
82
|
const harness = ["codex", "claude-code", "dsh", "antigravity"].includes(creds.vendor) ? creds.vendor : null;
|
|
83
83
|
const state = readState(name);
|
|
84
|
+
const pendingClear = state.pending_context_clear;
|
|
85
|
+
if (pendingClear && (pendingClear.project !== creds.project || pendingClear.work_unit_number !== unit.number)) {
|
|
86
|
+
throw new CliError("context_policy", `a fresh-thread clear is pending for WU #${pendingClear.work_unit_number}; finish that start before starting WU #${unit.number}`);
|
|
87
|
+
}
|
|
84
88
|
const mode = contextModeFromRuntime({
|
|
85
89
|
harness,
|
|
86
90
|
turnMode: !!state.turn_guard,
|
|
@@ -148,6 +152,73 @@ async function contextDecisionForStart(client, base, unit, name, p, events = [])
|
|
|
148
152
|
const checkpointRef = str(p.flags, "context-checkpoint-ref");
|
|
149
153
|
const oldThreadId = str(p.flags, "context-old-thread");
|
|
150
154
|
const newThreadId = str(p.flags, "context-new-thread");
|
|
155
|
+
if (mode === "turn") {
|
|
156
|
+
if (!harness)
|
|
157
|
+
throw new CliError("context_policy", "a verified harness is required to schedule a fresh turn-mode thread");
|
|
158
|
+
if (harness !== "codex") {
|
|
159
|
+
const unsupportedReason = `Fresh-thread clear in turn mode is not implemented for ${harness}; no start was attempted.`;
|
|
160
|
+
await client.call("POST", `${base}/${unit.number}/context-policy/decision`, { ...decision, outcome: "unsupported", reason: unsupportedReason });
|
|
161
|
+
throw new CliError("unsupported", `WU #${unit.number}: ${unsupportedReason} Ask the assigner or operator to choose a supported policy.`);
|
|
162
|
+
}
|
|
163
|
+
if (!creds.project)
|
|
164
|
+
throw new CliError("context_policy", "a project-scoped agent is required for a turn-mode clear");
|
|
165
|
+
const pending = pendingClear;
|
|
166
|
+
if (!pending) {
|
|
167
|
+
const currentThread = state.harness_session?.session_id;
|
|
168
|
+
if (!currentThread || state.harness_session?.harness !== harness || state.harness_session?.last_seen_at === undefined || Date.now() - state.harness_session.last_seen_at >= 60_000) {
|
|
169
|
+
throw new CliError("context_action_required", `the current ${harness ?? "harness"} thread is not locally verified; no clear was scheduled`);
|
|
170
|
+
}
|
|
171
|
+
let ref = checkpointRef;
|
|
172
|
+
if (ref) {
|
|
173
|
+
const checkpoint = await client.call("GET", `/handoffs/${encodeURIComponent(ref)}`);
|
|
174
|
+
if (checkpoint.handoff?.agent_name !== creds.agent || checkpoint.handoff?.kind !== "resume") {
|
|
175
|
+
throw new CliError("context_action_required", "context checkpoint must be an existing resume note saved by this agent");
|
|
176
|
+
}
|
|
177
|
+
}
|
|
178
|
+
else {
|
|
179
|
+
const title = `WU #${unit.number}: ${String(unit.title ?? "work unit")}`.slice(0, 200);
|
|
180
|
+
const body = [
|
|
181
|
+
`Work unit #${unit.number}: ${unit.title ?? "work unit"}`,
|
|
182
|
+
`Scope: ${String(unit.scope ?? "(scope unavailable)").slice(0, 50_000)}`,
|
|
183
|
+
`Current Codex thread: ${currentThread}`,
|
|
184
|
+
`Branch: ${unit.branch ?? "not set"}; head: ${unit.head ?? "not set"}.`,
|
|
185
|
+
`Next: read the current process and this note, then run b9s wu start ${unit.number} --context-checkpoint-ref <this-note-id> in the fresh thread. The watcher will include the unit brief and start that turn on a new Codex thread.`,
|
|
186
|
+
].join("\n\n");
|
|
187
|
+
const saved = await client.call("POST", "/agents/me/checkpoint", { title, body, evidence: [] });
|
|
188
|
+
ref = saved.handoff?.id;
|
|
189
|
+
if (typeof ref !== "string" || !ref)
|
|
190
|
+
throw new CliError("context_action_required", "the resume checkpoint was not saved; no clear was scheduled");
|
|
191
|
+
}
|
|
192
|
+
const pendingDecision = { ...decision, outcome: "pending", reason: "checkpoint saved; the watcher will start the next turn on a fresh thread", checkpoint_ref: ref, old_thread_id: currentThread };
|
|
193
|
+
await client.call("POST", `${base}/${unit.number}/context-policy/decision`, pendingDecision);
|
|
194
|
+
writeState(name, {
|
|
195
|
+
...state,
|
|
196
|
+
pending_context_clear: { project: creds.project, work_unit_number: unit.number, checkpoint_ref: ref, old_thread_id: currentThread, harness, requested_at: new Date().toISOString(), status: "pending" },
|
|
197
|
+
});
|
|
198
|
+
return { pending_clear: true, checkpoint_ref: ref };
|
|
199
|
+
}
|
|
200
|
+
if (!pending.checkpoint_ref || !pending.old_thread_id || pending.harness !== harness) {
|
|
201
|
+
throw new CliError("context_policy", "the pending clear record is incomplete or belongs to a different harness; no start was attempted");
|
|
202
|
+
}
|
|
203
|
+
const currentThread = state.harness_session?.session_id;
|
|
204
|
+
if (pending.status === "completed")
|
|
205
|
+
throw new CliError("context_policy", `WU #${unit.number} clear has completed; the watcher is switching to thread ${pending.new_thread_id ?? "(unknown)"}`);
|
|
206
|
+
const recentlyObserved = state.harness_session?.last_seen_at !== undefined && Date.now() - state.harness_session.last_seen_at < 60_000;
|
|
207
|
+
if (!currentThread || currentThread === pending.old_thread_id || state.harness_session?.harness !== harness || !recentlyObserved) {
|
|
208
|
+
throw new CliError("context_action_required", `WU #${unit.number} is waiting for its watcher to start a new ${harness ?? "harness"} thread; no start was attempted`);
|
|
209
|
+
}
|
|
210
|
+
if (pending.new_thread_id && currentThread !== pending.new_thread_id) {
|
|
211
|
+
throw new CliError("context_action_required", `WU #${unit.number} is waiting for the watcher to bind fresh thread ${pending.new_thread_id}; current thread ${currentThread} does not match`);
|
|
212
|
+
}
|
|
213
|
+
const checkpoint = await client.call("GET", `/handoffs/${encodeURIComponent(pending.checkpoint_ref)}`);
|
|
214
|
+
if (checkpoint.handoff?.agent_name !== creds.agent || checkpoint.handoff?.kind !== "resume") {
|
|
215
|
+
throw new CliError("context_action_required", "pending context checkpoint is not an existing resume note saved by this agent");
|
|
216
|
+
}
|
|
217
|
+
decision.checkpoint_ref = pending.checkpoint_ref;
|
|
218
|
+
decision.old_thread_id = pending.old_thread_id;
|
|
219
|
+
decision.new_thread_id = currentThread;
|
|
220
|
+
return decision;
|
|
221
|
+
}
|
|
151
222
|
if (!bool(p.flags, "context-confirmed") || !checkpointRef || !oldThreadId || !newThreadId) {
|
|
152
223
|
throw new CliError("context_action_required", `WU #${unit.number} requires a checkpointed fresh thread. Save it with b9s checkpoint, open a new thread for this agent, then rerun b9s wu start ${unit.number} --context-confirmed --context-checkpoint-ref <handoff-id> --context-old-thread <old-thread-id> --context-new-thread <new-thread-id>.`);
|
|
153
224
|
}
|
|
@@ -641,6 +712,10 @@ export async function wu(p, out) {
|
|
|
641
712
|
const def = await processDef();
|
|
642
713
|
const target = unit.target ?? def.merge.target_branch;
|
|
643
714
|
const contextDecision = await contextDecisionForStart(client, base, unit, name, p, Array.isArray(unitRecord.events) ? unitRecord.events : []);
|
|
715
|
+
if (contextDecision && "pending_clear" in contextDecision) {
|
|
716
|
+
out.print(`WU #${n}: checkpoint recorded; the watcher will start the next turn on a fresh thread, then start the unit.`, { unit, pending_context_clear: true, checkpoint_ref: contextDecision.checkpoint_ref });
|
|
717
|
+
return;
|
|
718
|
+
}
|
|
644
719
|
const prepared = prepareWorktree(n, unit, def, p, await checkoutExclude());
|
|
645
720
|
const { path, branch, mode } = prepared;
|
|
646
721
|
const where = symbolicBranchAndHead(path);
|
|
@@ -657,6 +732,11 @@ export async function wu(p, out) {
|
|
|
657
732
|
throw error;
|
|
658
733
|
}
|
|
659
734
|
out.print(`${fmt(r.unit)}\nYour worktree: ${path}${mode === "fresh" ? ` (new branch ${branch} from origin/${target}${unit.replay ? " as of the original" : ""})` : mode === "branch" ? ` (branch ${branch})` : " (this checkout)"}\n cd ${path}\nWork there. Submit when ready: b9s wu submit ${n} --evidence <id>`, { ...r, worktree: path, branch, mode });
|
|
735
|
+
if (readState(name).pending_context_clear?.work_unit_number === n) {
|
|
736
|
+
const current = readState(name);
|
|
737
|
+
const clear = current.pending_context_clear;
|
|
738
|
+
writeState(name, { ...current, pending_context_clear: { ...clear, status: "completed", new_thread_id: clear.new_thread_id ?? current.harness_session?.session_id ?? undefined } });
|
|
739
|
+
}
|
|
660
740
|
return;
|
|
661
741
|
}
|
|
662
742
|
case "decline": {
|
|
@@ -710,7 +790,7 @@ export async function wu(p, out) {
|
|
|
710
790
|
}
|
|
711
791
|
}
|
|
712
792
|
const pr = str(p.flags, "pr") ?? null;
|
|
713
|
-
const telemetry = await roundTelemetry(client, base, num(), name);
|
|
793
|
+
const telemetry = await roundTelemetry(client, base, num(), name, project);
|
|
714
794
|
let branchValueIds = [];
|
|
715
795
|
if (where.head) {
|
|
716
796
|
try {
|
|
@@ -763,7 +843,7 @@ export async function wu(p, out) {
|
|
|
763
843
|
const cause = str(p.flags, "cause");
|
|
764
844
|
if (sendBackEvent && (sub !== "rule" || !cause || !text))
|
|
765
845
|
throw new CliError("usage", 'wu rule <n> --send-back-event <event-id> --cause <cause> --ruling "decision"');
|
|
766
|
-
const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
|
|
846
|
+
const r = await client.call("POST", `${base}/${num()}/${sub}`, sub === "ask" ? { question: text, usage: await reviewUsage(client, project, name) } : sendBackEvent ? { send_back_event_id: sendBackEvent, cause, ruling: text } : approve ? { approve: true, ruling: text } : { ruling: text });
|
|
767
847
|
const q = r.unit.question;
|
|
768
848
|
out.print(`${fmt(r.unit)}\n${sendBackEvent ? "Retrospective ruling recorded on the unit; no chat message was added." : sub === "rule" ? "Ruled; the asker, owner and reviewers were told." : q.level === "expert" ? `Asked a ${q.roles.join(" or ")}; it goes to the operator if nobody rules in time.` : "Asked the operator."}`, r);
|
|
769
849
|
return;
|
|
@@ -830,7 +910,7 @@ export async function wu(p, out) {
|
|
|
830
910
|
const cause = str(p.flags, "cause");
|
|
831
911
|
if (sub === "changes" && !cause)
|
|
832
912
|
throw new CliError("usage", 'wu changes <n> --cause <scope_gap|missing_context|worker_error|reviewer_scope_growth|environment|stale_base> --unmet "<cited clause>" --note "what must change"');
|
|
833
|
-
const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
|
|
913
|
+
const r = await client.call("POST", `${base}/${num()}/${sub}`, { note, usage: await reviewUsage(client, project, name), ...(unmet ? { unmet } : {}), ...(cause ? { cause } : {}), ...(sub === "approve" && p.flags["confirm-causes"] !== undefined ? { confirmed_causes: list("confirm-causes") } : {}) });
|
|
834
914
|
out.print(fmt(r.unit), r);
|
|
835
915
|
return;
|
|
836
916
|
}
|
|
@@ -954,7 +1034,7 @@ export async function wu(p, out) {
|
|
|
954
1034
|
}
|
|
955
1035
|
case "note": {
|
|
956
1036
|
const annotation = jsonFlag(p, "annotation", "an annotation object");
|
|
957
|
-
const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), ...(annotation ? { annotation } : {}) });
|
|
1037
|
+
const r = await client.call("POST", `${base}/${num()}/note`, { note: str(p.flags, "note") ?? "", evidence: list("evidence"), usage: await reviewUsage(client, project, name), ...(annotation ? { annotation } : {}) });
|
|
958
1038
|
out.print(fmt(r.unit), r);
|
|
959
1039
|
return;
|
|
960
1040
|
}
|
|
@@ -1541,6 +1621,35 @@ export async function askOperator(p, out) {
|
|
|
1541
1621
|
const r = await client.call("POST", `/projects/${project}/ask-operator`, { text, ...fields, proposal });
|
|
1542
1622
|
out.print(`Asked the operator${proposal ? " with your proposal (they can approve it as written)" : ""}; it is on their console banner and reported to them. You will be @mentioned with the decision. Carry on with what does not depend on it.`, r);
|
|
1543
1623
|
}
|
|
1624
|
+
async function reviewUsage(client, project, name) {
|
|
1625
|
+
const until = new Date().toISOString();
|
|
1626
|
+
const session = measurableSession(name);
|
|
1627
|
+
let since;
|
|
1628
|
+
try {
|
|
1629
|
+
const result = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
|
|
1630
|
+
if (result.since === null)
|
|
1631
|
+
since = sessionStart(session);
|
|
1632
|
+
else {
|
|
1633
|
+
const cursor = typeof result.since === "string" ? Date.parse(result.since) : NaN;
|
|
1634
|
+
if (!Number.isFinite(cursor))
|
|
1635
|
+
throw new Error("invalid session usage cursor");
|
|
1636
|
+
since = new Date(cursor + 1).toISOString();
|
|
1637
|
+
}
|
|
1638
|
+
}
|
|
1639
|
+
catch (error) {
|
|
1640
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: `could not read session usage cursor: ${error.message}` };
|
|
1641
|
+
}
|
|
1642
|
+
if (!since)
|
|
1643
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "no earlier usage boundary or timestamped session is available" };
|
|
1644
|
+
if (Date.parse(since) > Date.parse(until))
|
|
1645
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason: "session usage cursor is later than the measurement time" };
|
|
1646
|
+
try {
|
|
1647
|
+
return sessionUsage(session, since, until);
|
|
1648
|
+
}
|
|
1649
|
+
catch (error) {
|
|
1650
|
+
return { harness: session?.harness ?? "unknown", source: "none", scope: "session", since, until, tokens: null, reason: `could not read session usage: ${error.message}` };
|
|
1651
|
+
}
|
|
1652
|
+
}
|
|
1544
1653
|
function measurableSession(name) {
|
|
1545
1654
|
const sessionId = process.env.BSCHAT_SESSION_ID;
|
|
1546
1655
|
if (sessionId) {
|
|
@@ -1563,14 +1672,26 @@ function startTelemetry(name) {
|
|
|
1563
1672
|
const at = new Date().toISOString();
|
|
1564
1673
|
return { context: sessionContext(measurableSession(name), at), compactions_since_last: 0, compactions_reason: null };
|
|
1565
1674
|
}
|
|
1566
|
-
async function roundTelemetry(client, base, n, name) {
|
|
1675
|
+
async function roundTelemetry(client, base, n, name, project) {
|
|
1567
1676
|
try {
|
|
1568
1677
|
const events = (await client.call("GET", `${base}/${n}`)).events;
|
|
1569
|
-
|
|
1678
|
+
const telemetry = await telemetryFromEvents(name, events);
|
|
1679
|
+
const cursor = await client.call("GET", `/projects/${project}/agents/me/usage-cursor`);
|
|
1680
|
+
if (cursor.since !== null && cursor.since !== undefined) {
|
|
1681
|
+
const previous = Date.parse(cursor.since);
|
|
1682
|
+
const current = Date.parse(telemetry.usage.since);
|
|
1683
|
+
if (!Number.isFinite(previous) || !Number.isFinite(current))
|
|
1684
|
+
throw new Error("invalid session usage cursor");
|
|
1685
|
+
const since = new Date(Math.max(current, previous + 1)).toISOString();
|
|
1686
|
+
if (Date.parse(since) > Date.parse(telemetry.usage.until))
|
|
1687
|
+
throw new Error("session usage cursor is later than the measurement time");
|
|
1688
|
+
telemetry.usage = sessionUsage(measurableSession(name), since, telemetry.usage.until);
|
|
1689
|
+
}
|
|
1690
|
+
return telemetry;
|
|
1570
1691
|
}
|
|
1571
1692
|
catch (e) {
|
|
1572
1693
|
const until = new Date().toISOString();
|
|
1573
|
-
const reason = `could not read the unit
|
|
1694
|
+
const reason = `could not read the unit timeline or usage cursor: ${e.message}`;
|
|
1574
1695
|
const usage = { harness: "unknown", source: "none", scope: "session", since: until, until, tokens: null, reason };
|
|
1575
1696
|
return { usage, context: { pct: null, tokens: null, window: null, source: "unknown", measured_at: null, reason }, compactions: { count: null, reason } };
|
|
1576
1697
|
}
|
package/dist/container.js
CHANGED
|
@@ -15,6 +15,24 @@ const FORBIDDEN_MOUNT_RE = /(\/var\/run\/docker\.sock|\/\.ssh(?:\/|$)|\/\.aws(?:
|
|
|
15
15
|
const FORBIDDEN_FLAG_RE = /(--privileged|--cap-add(?:=|\s+)(?:SYS_ADMIN|ALL)|--net(?:work)?(?:=|\s+)host|--pid(?:=|\s+)host|--userns(?:=|\s+)host)/i;
|
|
16
16
|
const SECRET_KEY_RE = /(AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)/i;
|
|
17
17
|
const SECRET_VALUE_RE = /(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|gh[pousr]_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16})/;
|
|
18
|
+
export const BUILD_SECRET_KEY_NAME_RE = /^(?:_authToken|_auth|password|passwd|token|secret|api[_-]?key|AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)$/i;
|
|
19
|
+
export const BUILD_SECRET_CONTENT_RE = /(?:_authToken|(?:^|\s)_auth|(?:^|\s)(?:password|passwd|token|secret|api[_-]?key)\s*[:=]\s*[^\s#]{4,}|(?:^|[^A-Za-z0-9_])(?:AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)["']?\s*[:=]\s*["']?[^\s"'#},]{4,}|-----BEGIN (?:RSA |EC |OPENSSH )?PRIVATE KEY-----|bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|gh[pousr]_[A-Za-z0-9_]+|sk-[A-Za-z0-9_-]{12,}|AKIA[0-9A-Z]{16})/im;
|
|
20
|
+
const SECRET_BUILD_KEY_RE = /(AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY)/i;
|
|
21
|
+
/** Detect credential material in build contexts and exported image metadata/layers. */
|
|
22
|
+
export function containsBuildSecretMaterial(content) {
|
|
23
|
+
return BUILD_SECRET_CONTENT_RE.test(typeof content === "string" ? content : content.toString("latin1"));
|
|
24
|
+
}
|
|
25
|
+
const SECRET_DIAGNOSTIC_KEYS = "AWS_ACCESS_KEY_ID|AWS_SECRET_ACCESS_KEY|AWS_SESSION_TOKEN|OPENAI_API_KEY|ANTHROPIC_API_KEY|DEEPSEEK_API_KEY|GITHUB_TOKEN|GH_TOKEN|BSCHAT_KEY|B9S_KEY|BOT_TOKEN|PRIVATE_KEY";
|
|
26
|
+
const JSON_SECRET_DIAGNOSTIC_RE = new RegExp(`("(?:${SECRET_DIAGNOSTIC_KEYS})"\\s*:\\s*")[^"\\r\\n]*"`, "gi");
|
|
27
|
+
const BARE_SECRET_DIAGNOSTIC_RE = new RegExp(`\\b(${SECRET_DIAGNOSTIC_KEYS})\\b(\\s*[:=]\\s*)(?:"[^"\\r\\n]*"|'[^'\\r\\n]*'|[^\\s,;}\\]]+)`, "gi");
|
|
28
|
+
/** Redact known credentials before daemon diagnostics are logged, returned, or posted. */
|
|
29
|
+
export function sanitizeBuildDiagnosticText(text) {
|
|
30
|
+
return text
|
|
31
|
+
.replace(JSON_SECRET_DIAGNOSTIC_RE, '$1[REDACTED]"')
|
|
32
|
+
.replace(BARE_SECRET_DIAGNOSTIC_RE, "$1$2[REDACTED]")
|
|
33
|
+
.replace(/(_authToken\s*=\s*)[^\s#]+/gi, "$1[REDACTED]")
|
|
34
|
+
.replace(/(bs_(?:admin|agent|machine|enroll|boot)_[A-Za-z0-9]+|AKIA[0-9A-Z]{16}|sk-[A-Za-z0-9_-]{12,}|gh[pousr]_[A-Za-z0-9_]+)/g, "[REDACTED]");
|
|
35
|
+
}
|
|
18
36
|
function canonicalSort(v) {
|
|
19
37
|
if (Array.isArray(v))
|
|
20
38
|
return v.map(canonicalSort);
|
|
@@ -90,6 +108,21 @@ export function validateDevcontainerSpec(devcontainerRaw, opts = {}) {
|
|
|
90
108
|
const df = opts.dockerfileContent ?? "";
|
|
91
109
|
if (!df.trim())
|
|
92
110
|
return { ok: false, error: "dockerfileContent required to verify pinned FROM digests" };
|
|
111
|
+
if (SECRET_VALUE_RE.test(df))
|
|
112
|
+
return { ok: false, error: "Dockerfile contains token-like material; build-time secrets are not allowed" };
|
|
113
|
+
for (const raw of df.split(/\r?\n/)) {
|
|
114
|
+
const line = raw.trim();
|
|
115
|
+
const declaration = /^(ARG|ENV)\s+(.+)$/i.exec(line);
|
|
116
|
+
const keys = declaration ? (declaration[1].toUpperCase() === "ARG" ? [declaration[2].trim().split(/[=\s]/, 1)[0]] : declaration[2].trim().split(/\s+/).map((entry) => entry.split("=", 1)[0])) : [];
|
|
117
|
+
const secretKey = keys.find((key) => SECRET_BUILD_KEY_RE.test(key));
|
|
118
|
+
if (secretKey)
|
|
119
|
+
return { ok: false, error: `Dockerfile ${declaration?.[1]} references secret key ${secretKey}; build-time secrets are not allowed` };
|
|
120
|
+
if (/--mount\s*=\s*type=secret|(?:^|\s)--secret(?:=|\s)/i.test(line))
|
|
121
|
+
return { ok: false, error: "Dockerfile secret mounts and --secret options are not allowed" };
|
|
122
|
+
const runNetwork = /^RUN\b.*--network(?:=|\s+)(\S+)/i.exec(line);
|
|
123
|
+
if (runNetwork && runNetwork[1].toLowerCase() !== "none")
|
|
124
|
+
return { ok: false, error: "Dockerfile RUN network overrides are forbidden; build steps must use network=none" };
|
|
125
|
+
}
|
|
93
126
|
const fromMatches = [...df.matchAll(/^\s*FROM\s+(?:--platform=\S+\s+)?(\S+)/gim)];
|
|
94
127
|
if (!fromMatches.length)
|
|
95
128
|
return { ok: false, error: "Dockerfile must contain a pinned FROM instruction" };
|
|
@@ -276,6 +309,8 @@ export function isolatedBuildCommand(opts) {
|
|
|
276
309
|
const { imageRef, cacheKey } = isolatedImageMetadata(opts);
|
|
277
310
|
const args = [
|
|
278
311
|
"build",
|
|
312
|
+
"--network",
|
|
313
|
+
"none",
|
|
279
314
|
"--platform",
|
|
280
315
|
opts.arch,
|
|
281
316
|
"--no-cache=false",
|
|
@@ -326,7 +361,7 @@ export function isolatedDevcontainerBuildCommand(opts) {
|
|
|
326
361
|
"--config",
|
|
327
362
|
opts.configPath,
|
|
328
363
|
"--docker-path",
|
|
329
|
-
opts.runtime,
|
|
364
|
+
opts.dockerPath ?? opts.runtime,
|
|
330
365
|
"--platform",
|
|
331
366
|
opts.arch,
|
|
332
367
|
"--image-name",
|
|
@@ -336,6 +371,16 @@ export function isolatedDevcontainerBuildCommand(opts) {
|
|
|
336
371
|
cacheKey,
|
|
337
372
|
};
|
|
338
373
|
}
|
|
374
|
+
/**
|
|
375
|
+
* Dev Container CLI does not expose Docker build's network mode directly. Route its runtime calls
|
|
376
|
+
* through a small wrapper that forces --network=none on every `build`/`buildx build` invocation.
|
|
377
|
+
*/
|
|
378
|
+
export function networklessRuntimeWrapper(runtime, directory) {
|
|
379
|
+
const path = join(directory, `b9s-${runtime}-networkless.cjs`);
|
|
380
|
+
writeFileSync(path, `#!${process.execPath}\nconst { spawnSync } = require("node:child_process");\nconst args = process.argv.slice(2);\nconst isBuild = args[0] === "build" || (args[0] === "buildx" && args[1] === "build");\nif (isBuild) args.splice(Math.max(1, args.length - 1), 0, "--network=none");\nconst result = spawnSync(${JSON.stringify(runtime)}, args, { stdio: "inherit", env: process.env });\nprocess.exit(result.status ?? 1);\n`, { mode: 0o700 });
|
|
381
|
+
chmodSync(path, 0o700);
|
|
382
|
+
return path;
|
|
383
|
+
}
|
|
339
384
|
export function agentContainerName(accountSlug, project, agent) {
|
|
340
385
|
return `b9s-${accountSlug}-${project}-${agent}`.toLowerCase().replace(/[^a-z0-9_.-]/g, "-").slice(0, 60);
|
|
341
386
|
}
|
package/dist/help.js
CHANGED
|
@@ -31,6 +31,7 @@ Environment problems: agents report bounded, redacted observations with b9s envi
|
|
|
31
31
|
|
|
32
32
|
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.
|
|
33
33
|
GET /projects/:p/context-policy/comparison reports descriptive project-scoped policy aggregates by build/review mode, tag, and exact event-stamped class. Reviewer event counts are separate from replay-cluster uncertainty; turn token usage stays unknown. Clear-cohort units need their own server-verified clear event and a later start by the same actor. Results are not causal or paired; the console view is WU #299.
|
|
34
|
+
GET /projects/:p/work-units/:n/cost reports recorded worker, review and rework session tokens across superseded units; GET /projects/:p/stats includes finished-unit model costs. Incomplete or overlapping windows remain explicit, and token-weight prices are estimates. GET /projects/:p/agents/me/usage-cursor gives the caller's session boundary. See packages/skill/references/api.md.
|
|
34
35
|
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.
|
|
35
36
|
Review routing ranks only independent qualified reviewers (excluding owner, prior builders, same-worktree occupants, and forbidden_dependent_roles), preserves trial/expert/mandatory_reviewer blockers, supports paired comparisons and head-to-head verdicts (POST /projects/:p/work-units/:n/compare, closing non-selected units as compared), and exposes GET /projects/:p/review-routing. Console routing controls are WU #244; CLI routing view/controls are WU #242. See packages/skill/references/api.md for field validation and response shapes.
|
|
36
37
|
|
|
@@ -86,11 +87,12 @@ Agent commands
|
|
|
86
87
|
checkout is removed and made again; wu open does the same for your own units;
|
|
87
88
|
--branch continues existing work (never a SHA); always fetches and branches from origin/<target>; --here uses this checkout
|
|
88
89
|
context policy is resolved before worktree creation: keep is recorded automatically;
|
|
89
|
-
compact requires a completed interactive /compact confirmation; clear
|
|
90
|
-
|
|
90
|
+
compact requires a completed interactive /compact confirmation; Codex turn-mode clear saves a resume checkpoint
|
|
91
|
+
automatically (or accepts --context-checkpoint-ref), then the watcher starts a fresh thread with the note and unit scope;
|
|
92
|
+
interactive clear requires a saved checkpoint, a different thread, and a matching locally recorded current-thread id;
|
|
93
|
+
/me.machine_sessions identifies placement:
|
|
91
94
|
managed sessions update their remembered thread atomically on start; an empty list confirms unmanaged; unknown is refused;
|
|
92
|
-
|
|
93
|
-
clear also needs --context-checkpoint-ref, --context-old-thread, and --context-new-thread; unsupported work never starts
|
|
95
|
+
unsupported or failed clear handoffs never start the unit;
|
|
94
96
|
lifecycle events include context-fill metadata and compaction deltas: Claude Code reads assistant usage
|
|
95
97
|
and compact markers, Codex reads token_count and compaction events; Antigravity needs a confirmed window;
|
|
96
98
|
unsupported or unavailable measurements include a reason; compaction intervals include the start and exclude the end
|
|
@@ -216,10 +218,11 @@ Agent commands
|
|
|
216
218
|
Pressured or unknown telemetry holds heavy permits; ordinary turns remain available.
|
|
217
219
|
Claude Code workspace-write defaults to a $1 per-turn cap; configure it with --max-budget-usd
|
|
218
220
|
Account turn-spend caps are set by the account operator separately; token caps support subscriptions,
|
|
219
|
-
missing usage remains reserved.
|
|
221
|
+
missing usage remains reserved. Hard caps alone do not enable judgment capture; the account owner explicitly
|
|
222
|
+
toggles PUT /account/turn-budget/judgment-capture (enabled + reason), surfaced by console WU #238.
|
|
220
223
|
Admin-only account reads: GET /account/turn-spend/reservations and
|
|
221
224
|
GET /account/turn-spend/sessions/:session/reservations list unresolved reservations;
|
|
222
|
-
GET /account/turn-budget/audit lists
|
|
225
|
+
GET /account/turn-budget/audit lists budget and judgment activation changes. All three are paged and account-scoped.
|
|
223
226
|
(b9s codex start is the same with --harness codex)
|
|
224
227
|
b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
|
|
225
228
|
b9s turn note "<short progress summary>" [--as <a>] save a 300-character turn-end excerpt for an enabled managed session; it is labelled unverified
|
|
@@ -350,7 +353,7 @@ the returned object and warning, then exits 3. Inspect the object and do not ret
|
|
|
350
353
|
b9s-admin milestone <project> add|edit <key> --title .. [--exit ..] [--source ..] [--depends-on a,b] [--informs c,d] [--default-tags a,b] one slice in, the rest untouched
|
|
351
354
|
b9s-admin milestone <project> show|review|reopen <key> | decide <key> "ruling" --unit n | close <key> --note .. [--abandon|--defer] | verdict <key> --met|--gaps .. | gap-units <key> --units n,m
|
|
352
355
|
b9s-admin flow [--project <p>] [--from <UTC date/time>] [--to <UTC date/time>] [--json]
|
|
353
|
-
read-only state counts, waits, capacity, critical paths, attention, trends, freshness and coverage
|
|
356
|
+
read-only state counts, waits, qualified worker/reviewer capacity, critical paths, attention, trends, freshness and coverage
|
|
354
357
|
b9s-admin role edit <name> [--project p] --reviews a,b --works c --trials d which tags a role reviews, works and trials ("*" all, "" none)
|
|
355
358
|
--assign-outside-qualifications yes|no allow assigners in this role to make reasoned ownership exceptions; dispatch stays qualified
|
|
356
359
|
b9s-admin needs decisions waiting on you (asks, unit questions, broken wake paths, alert failures)
|
|
@@ -393,7 +396,8 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
|
|
|
393
396
|
[--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
|
|
394
397
|
[--model m] [--effort e] [--wait min] [--force --confirm-force <project>/<agent>]
|
|
395
398
|
creates a move or continues the requested operation from the console; stored options are loaded and explicit options must match
|
|
396
|
-
checks
|
|
399
|
+
checks owned and agent-attributed review worktrees on the source, reports unrelated, remote, and unrecorded work as skipped,
|
|
400
|
+
transfers thread/note plus local agent state over SSH,
|
|
397
401
|
refuses newer destination state and avoids duplicate Codex hooks under managed policy,
|
|
398
402
|
then commits the session only after handoff succeeds; work left on the source requires both flags
|
|
399
403
|
b9s-admin machine label <name> <label...> [--remove a,b] what cannot be measured (lab-lan, builds); pools' --needs match it
|
|
@@ -420,8 +424,9 @@ Project devcontainer images & immutable registry builds (console controls in WU
|
|
|
420
424
|
b9s-admin project image validate --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch linux/amd64|linux/arm64] validate @sha256 pins and reject secrets/host mounts/--privileged
|
|
421
425
|
b9s-admin project image config <project> [--path <path>] [--arch linux/amd64|linux/arm64] [--cache name,...] configure immutable per-account image registry & build cache allowlist
|
|
422
426
|
b9s-admin project image show <project> active digest, rollback target, latest build, and image capability probes
|
|
423
|
-
b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>]
|
|
424
|
-
b9s-admin project image
|
|
427
|
+
b9s-admin project image build <project> --commit <sha> --file <.devcontainer/devcontainer.json> [--dockerfile Dockerfile] [--arch <arch>] build only the reviewed declaration commit; machine validation runs its image probes and project test before ready
|
|
428
|
+
b9s-admin project image activate <project> <sha256:...> explicitly select a ready candidate for future or restarted sessions
|
|
429
|
+
b9s-admin project image rollback <project> (<sha256:...> | clear) select a prior ready digest or clear the active image selection without mutating tags
|
|
425
430
|
|
|
426
431
|
Pools (a role, variants and a count; the server names the agents and places them on machines)
|
|
427
432
|
b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
|