benignswarm 0.12.89 → 0.12.90
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 -1
- package/dist/client.js +1 -1
- package/dist/commands/codex-start.js +47 -20
- package/dist/commands/machine-admin.js +23 -5
- package/dist/commands/machine.js +24 -3
- package/dist/commands/operator.js +6 -3
- package/dist/commands/watch.js +120 -11
- package/dist/commands/worktrees.js +55 -12
- package/dist/commands/wu.js +9 -0
- package/dist/git.js +41 -14
- package/dist/harnesses.js +46 -0
- package/dist/help.js +12 -5
- package/dist/turn-guard.js +69 -0
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -3,7 +3,7 @@ import { CliError } from "./errors.js";
|
|
|
3
3
|
// These options accept comma-separated collections, so repeating them should
|
|
4
4
|
// append another collection instead of discarding earlier values.
|
|
5
5
|
export const LIST_FLAGS = ["tags", "projects", "evidence", "statuses", "depends-on", "default-tags", "units", "waits-on", "needs", "exclude", "remove", "post", "harness", "variant", "requires", "reworks"];
|
|
6
|
-
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
|
|
6
|
+
export const STRING_FLAGS = ["as", "admin", "key", "url", "label", "model", "since", "limit", "after", "topic", "goal", "task", "state", "blocked-on", "tags", "custom", "vendor", "role", "tier", "description", "permissions", "cardinality", "assign-outside-qualifications", "machine", "dir", "confirm", "type", "name", "out", "token", "prefix", "uses", "expires-hours", "skill-dir", "harness", "provider", "reply-to", "event", "project", "projects", "post", "title", "body", "body-file", "handoff-to", "evidence", "agent", "parent", "parent-item", "channel", "statuses", "assign", "if-status", "status", "exec", "interval", "requeue-after", "unacked-after", "category", "command", "command-pattern", "follow-delay", "env", "scope", "scope-file", "scope-from", "append", "pr", "note", "add", "remove", "merged", "tag", "activity", "max-unanswered", "to", "replay-of", "branch", "effort", "by", "target", "milestone", "file", "exit", "depends-on", "default-tags", "source", "on", "partial", "question", "ruling", "gaps", "unit", "units", "blocks", "sla", "takeover", "max-open", "max-in-progress", "require-scope", "require-evidence", "default-approver", "merged-by", "integrator-role", "require-rebased", "require-merge-commit", "require-pushed", "quiet", "summary", "meaning", "expert-role", "reviews", "works", "trials", "email", "repeat", "summary-minutes", "churn", "unmet", "require-cited-changes", "checks-every", "propose", "waits-on", "sandbox", "thread", "turn-timeout", "turns-per-hour", "session", "plain", "if-yes", "if-no", "ssh", "variant", "count", "needs", "min-ram", "exclude", "carry", "from", "to-ssh", "wait", "writable", "dsh", "for", "until", "reason", "at", "requires", "priority", "informs", "amend", "waive-informs", "text", "kind", "claim", "decision", "sha", "value", "expect", "expectations", "reworks"];
|
|
7
7
|
export const BOOL_FLAGS = ["latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels", "read-account-status", "replace-key", "mentions-me", "no-skill", "replace", "template", "scope-only", "unread", "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind", "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive", "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor", "cancel", "rerun", "confirmed", "refuted", "no-source"];
|
|
8
8
|
export function parse(argv) {
|
|
9
9
|
const options = {};
|
package/dist/client.js
CHANGED
|
@@ -51,7 +51,7 @@ export class Client {
|
|
|
51
51
|
for (let attempt = 0;; attempt++) {
|
|
52
52
|
let res;
|
|
53
53
|
try {
|
|
54
|
-
res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body) });
|
|
54
|
+
res = await fetch(this.url + path, { method, headers, body: body === undefined ? undefined : JSON.stringify(body), signal: opts.signal });
|
|
55
55
|
}
|
|
56
56
|
catch (e) {
|
|
57
57
|
if (attempt < retries) {
|
|
@@ -11,10 +11,11 @@ import { codexHooksPath } from "./codex.js";
|
|
|
11
11
|
import { isCodexManagedRequirements } from "../harness.js";
|
|
12
12
|
import { readState, writeState } from "../state.js";
|
|
13
13
|
import { join } from "./join.js";
|
|
14
|
-
import { installWatcherService } from "./watch.js";
|
|
14
|
+
import { beginTurnGuardAttempt, completePendingTurnGuard, installWatcherService } from "./watch.js";
|
|
15
15
|
import { randomUUID } from "node:crypto";
|
|
16
|
-
import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog } from "../harnesses.js";
|
|
16
|
+
import { HARNESS_BIN, HARNESS_LABEL, claudeResultError, claudeResultFile, claudeSettings, claudeTranscript, dshPath, dshResultError, dshSessionFromEvents, dshSettings, dshTurnLog, probeFor } from "../harnesses.js";
|
|
17
17
|
import { claudeTurnEnv } from "../providers.js";
|
|
18
|
+
import { DEFAULT_TURNS_PER_HOUR } from "../turn-guard.js";
|
|
18
19
|
const SANDBOXES = ["read-only", "workspace-write", "danger-full-access"];
|
|
19
20
|
/**
|
|
20
21
|
* `b9s start` (and `b9s codex start`): one command that brings an agent up on this machine
|
|
@@ -43,6 +44,9 @@ export async function harnessStart(p, out, harness) {
|
|
|
43
44
|
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
44
45
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
45
46
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
47
|
+
const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
|
|
48
|
+
if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
|
|
49
|
+
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
|
|
46
50
|
const interval = Number(str(p.flags, "interval") ?? "30");
|
|
47
51
|
if (!Number.isInteger(interval) || interval < 5)
|
|
48
52
|
throw new CliError("usage", "--interval must be an integer number of seconds, at least 5");
|
|
@@ -66,7 +70,6 @@ export async function harnessStart(p, out, harness) {
|
|
|
66
70
|
if (harness === "dsh" && !existsSync(bin))
|
|
67
71
|
throw new CliError("not_found", `DeepSeek Harness CLI ${bin} does not exist; pass --dsh <path> to its runtime/cli/bin/dsh`);
|
|
68
72
|
const effort = str(p.flags, "effort");
|
|
69
|
-
const adopt = str(p.flags, "thread") ?? str(p.flags, "session");
|
|
70
73
|
// The machine's toolchain and job folders a sandboxed agent may also write (b9s-admin machine writable).
|
|
71
74
|
const writable = (str(p.flags, "writable") ?? "").split(",").map((w) => w.trim()).filter(Boolean).map((w) => (w.startsWith("~/") ? joinPath(homedir(), w.slice(2)) : w));
|
|
72
75
|
if (writable.some((w) => !w.startsWith("/")))
|
|
@@ -90,6 +93,14 @@ export async function harnessStart(p, out, harness) {
|
|
|
90
93
|
if (creds.vendor && creds.vendor !== harness)
|
|
91
94
|
throw new CliError("vendor_mismatch", `${agentRef(creds)} is saved as ${creds.vendor}, not ${harness}`);
|
|
92
95
|
const ref = agentRef(creds);
|
|
96
|
+
const priorState = readState(ref);
|
|
97
|
+
if (priorState.turn_guard?.fault) {
|
|
98
|
+
const fault = priorState.turn_guard.fault;
|
|
99
|
+
throw new CliError("turn_mode_fault", `turn mode is stopped after ${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call` : `${fault.turns_last_hour} turns in the rolling hour`}; resume it with b9s-admin machine session resume; last output: ${fault.output_tail || "(empty)"}`);
|
|
100
|
+
}
|
|
101
|
+
const initialTurnPending = priorState.turn_guard?.turns.some((attempt) => attempt.productive === null) ?? false;
|
|
102
|
+
const rememberedSession = initialTurnPending && priorState.harness_session?.harness === harness ? priorState.harness_session.session_id : null;
|
|
103
|
+
const adopt = str(p.flags, "thread") ?? str(p.flags, "session") ?? rememberedSession ?? undefined;
|
|
93
104
|
requireInstall();
|
|
94
105
|
// 2. Its session: adopt one, or start one headless with an onboarding turn.
|
|
95
106
|
let session;
|
|
@@ -123,36 +134,52 @@ export async function harnessStart(p, out, harness) {
|
|
|
123
134
|
else {
|
|
124
135
|
const logDir = joinPath(configRoot(), "logs");
|
|
125
136
|
mkdirSync(logDir, { recursive: true });
|
|
126
|
-
firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn
|
|
137
|
+
firstTurnLog = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeResultFile(ref) : joinPath(logDir, `${harness}.${ref.replace("/", ".")}.first-turn.jsonl`);
|
|
127
138
|
const prompt = [
|
|
128
139
|
`[b9s] You are ${ref}, a BenignSwarm agent, started headless by \`b9s ${cmd}\`; nobody is typing to you.`,
|
|
129
140
|
`Your watcher starts a turn for you whenever something needs you, so end your turn when nothing is left to do.`,
|
|
130
141
|
`Now: run \`b9s me\`, \`b9s process\` and \`b9s inbox --unread\`, then do what your role and inbox ask.`,
|
|
131
142
|
`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).`,
|
|
132
143
|
].join("\n");
|
|
133
|
-
|
|
134
|
-
|
|
135
|
-
|
|
144
|
+
const diagnostic = [];
|
|
145
|
+
if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m)))) {
|
|
146
|
+
throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the onboarding turn");
|
|
136
147
|
}
|
|
137
|
-
|
|
138
|
-
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
148
|
+
try {
|
|
149
|
+
if (harness === "codex") {
|
|
150
|
+
session = await startThread(bin, ["exec", "--json", ...settings, prompt], firstTurnLog, ref);
|
|
151
|
+
lines.push(`Started Codex thread ${session}; its first turn (reading its role and inbox) is running, log: ${firstTurnLog}`);
|
|
152
|
+
}
|
|
153
|
+
else if (harness === "dsh") {
|
|
154
|
+
const started = await startDshSession(bin, dshStartArgs(settings), firstTurnLog, ref, prompt);
|
|
155
|
+
session = started.session;
|
|
156
|
+
initialPid = started.pid;
|
|
157
|
+
lines.push(`Started DeepSeek Harness session ${session}; its first turn (reading its role and inbox) is running, event log: ${firstTurnLog}`);
|
|
158
|
+
}
|
|
159
|
+
else {
|
|
160
|
+
// Claude Code takes the session id from us, so nothing has to be read back from its output.
|
|
161
|
+
session = randomUUID();
|
|
162
|
+
await startClaudeSession(bin, ["-p", prompt, ...settings, "--session-id", session, "--output-format", "json"], firstTurnLog, ref, session, providerEnv);
|
|
163
|
+
lines.push(`Started Claude Code session ${session}; its first turn (reading its role and inbox) is running, result: ${firstTurnLog}`);
|
|
164
|
+
}
|
|
142
165
|
}
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
session
|
|
146
|
-
|
|
147
|
-
|
|
166
|
+
catch (error) {
|
|
167
|
+
const raw = existsSync(firstTurnLog) ? readFileSync(firstTurnLog, "utf8").slice(-800) : "";
|
|
168
|
+
await completePendingTurnGuard(ref, probeFor(harness, session ?? "", ref), (m) => diagnostic.push(m), `${error.message}\n${raw}`.slice(-800));
|
|
169
|
+
const fault = readState(ref).turn_guard?.fault;
|
|
170
|
+
if (fault)
|
|
171
|
+
throw new CliError("turn_mode_fault", `turn mode stopped after ${fault.consecutive_unproductive} consecutive turns without a BenignSwarm call; estimated tokens spent: ${fault.estimated_tokens}; last output: ${fault.output_tail || "(empty)"}`);
|
|
172
|
+
throw error;
|
|
148
173
|
}
|
|
149
174
|
}
|
|
175
|
+
if (!session)
|
|
176
|
+
throw new CliError("harness_failed", "the harness did not provide a session id");
|
|
150
177
|
// 3. Bind it, so the hooks in that session deliver to this agent and nobody else. Claude Code's
|
|
151
178
|
// hook knows the agent from BSCHAT_AGENT (the watcher sets it for every turn), so it needs no map.
|
|
152
179
|
if (harness === "codex")
|
|
153
180
|
bindSession("codex", session, ref);
|
|
154
|
-
|
|
155
|
-
|
|
181
|
+
const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
|
|
182
|
+
writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(initialPid ? { initial_pid: initialPid } : {}) } });
|
|
156
183
|
// A session adopted here may end in a usage-limit error from the machine it came from, written in
|
|
157
184
|
// that machine's local time ("3:32 PM" Central read as UTC on ronald: six hours off). Only errors
|
|
158
185
|
// from turns on this machine pause it; if the account is still limited, the next turn says so here.
|
|
@@ -172,7 +199,7 @@ export async function harnessStart(p, out, harness) {
|
|
|
172
199
|
// volume had 750 GB free, and which empties /tmp at every boot.
|
|
173
200
|
const tmp = sessionTmpDir(process.cwd(), creds.agent);
|
|
174
201
|
mkdirSync(tmp, { recursive: true });
|
|
175
|
-
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, provider, model });
|
|
202
|
+
installWatcherService(ref, exec, interval, Number(str(p.flags, "follow-delay") ?? "300"), { TMPDIR: tmp }, undefined, { json: false, print: (h) => watcherOut.push(h) }, bool(p.flags, "prune"), { harness, session, timeout: turnTimeout, turnsPerHour, provider, model });
|
|
176
203
|
const wl = watcherOut.join("\n").split("\n");
|
|
177
204
|
lines.push(wl[0].replace(/^Wrote /, "Watcher: wrote "), ...wl.filter((l) => l.startsWith("Linger is off")));
|
|
178
205
|
// 5. Hooks.
|
|
@@ -195,13 +195,17 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
195
195
|
const [sub, machineName, ref] = rest;
|
|
196
196
|
const [project, agent] = (ref ?? "").split("/");
|
|
197
197
|
if (!sub || !machineName || !project || !agent)
|
|
198
|
-
throw new CliError("usage", "machine session add|stop|start|remove <machine> <project>/<agent> [...]");
|
|
198
|
+
throw new CliError("usage", "machine session add|stop|start|resume|limit|remove <machine> <project>/<agent> [...]");
|
|
199
199
|
if (sub === "add") {
|
|
200
200
|
const turnTimeout = str(p.flags, "turn-timeout");
|
|
201
|
+
const turnsPerHour = str(p.flags, "turns-per-hour");
|
|
202
|
+
if (turnsPerHour !== undefined && (!/^\d+$/.test(turnsPerHour) || Number(turnsPerHour) < 1 || Number(turnsPerHour) > 20))
|
|
203
|
+
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
|
|
201
204
|
const body = {
|
|
202
205
|
project, agent, harness: str(p.flags, "harness") ?? "codex", provider: str(p.flags, "provider") ?? "anthropic", dir: str(p.flags, "dir"), sandbox: str(p.flags, "sandbox"),
|
|
203
206
|
model: str(p.flags, "model"), effort: str(p.flags, "effort"), thread: str(p.flags, "thread"),
|
|
204
207
|
...(turnTimeout ? { turn_timeout: Number(turnTimeout) } : {}),
|
|
208
|
+
...(turnsPerHour ? { turns_per_hour: Number(turnsPerHour) } : {}),
|
|
205
209
|
create: bool(p.flags, "create"), role: str(p.flags, "role"),
|
|
206
210
|
};
|
|
207
211
|
const r = await c.call("POST", `/machines/${machineName}/sessions`, body);
|
|
@@ -211,6 +215,17 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
211
215
|
const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { desired: sub === "stop" ? "stopped" : "running" });
|
|
212
216
|
return out.print(`${ref} on ${machineName}: desired ${r.session.desired}; its daemon acts within 30 s.`, r);
|
|
213
217
|
}
|
|
218
|
+
if (sub === "resume") {
|
|
219
|
+
const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { resume_turns: true });
|
|
220
|
+
return out.print(`${ref} on ${machineName}: turn mode resumed explicitly; its daemon applies the request within 30 s.`, r);
|
|
221
|
+
}
|
|
222
|
+
if (sub === "limit") {
|
|
223
|
+
const value = str(p.flags, "turns-per-hour");
|
|
224
|
+
if (!value || !/^\d+$/.test(value) || Number(value) < 1 || Number(value) > 20)
|
|
225
|
+
throw new CliError("usage", "machine session limit <machine> <project>/<agent> --turns-per-hour <1..20>");
|
|
226
|
+
const r = await c.call("PATCH", `/machines/${machineName}/sessions/${project}/${agent}`, { turns_per_hour: Number(value) });
|
|
227
|
+
return out.print(`${ref} on ${machineName}: turn limit set to ${value} per hour; the daemon applies it within 30 s.`, r);
|
|
228
|
+
}
|
|
214
229
|
if (sub === "remove") {
|
|
215
230
|
await c.call("DELETE", `/machines/${machineName}/sessions/${project}/${agent}`);
|
|
216
231
|
return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
|
|
@@ -239,13 +254,13 @@ export function repeated(argv, flag) {
|
|
|
239
254
|
return out;
|
|
240
255
|
}
|
|
241
256
|
/**
|
|
242
|
-
* pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min]
|
|
257
|
+
* pool set <project>/<name> --role r --variant spec [--variant ...] --count n --sandbox mode [--needs a,b] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]
|
|
243
258
|
* pool list [project] | show <project>/<name> | remove <project>/<name>
|
|
244
259
|
*/
|
|
245
260
|
export async function poolAdmin(action, rest, p, out, argv) {
|
|
246
261
|
const c = adminClient(p);
|
|
247
262
|
const statusLines = (pool) => [
|
|
248
|
-
`${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
|
|
263
|
+
`${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; max ${pool.turns_per_hour ?? 20} turns/hour; variants ${pool.variants.map((v) => `${v.tag}=${v.harness}:${v.model ?? "default"}${v.effort ? `:${v.effort}` : ""}${v.weight > 1 ? `*${v.weight}` : ""}${v.provider && v.provider !== "anthropic" ? `@${v.provider}` : ""}`).join(", ")}${pool.needs?.labels?.length ? `; needs ${pool.needs.labels.join(", ")}` : ""}${pool.needs?.min_ram_gb ? `; min ${pool.needs.min_ram_gb} GB` : ""}`,
|
|
249
264
|
...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
|
|
250
265
|
...(pool.status?.unplaced ?? []).map((x) => ` ${x.agent.padEnd(32)} NOT PLACED: ${x.reason}`),
|
|
251
266
|
];
|
|
@@ -254,10 +269,13 @@ export async function poolAdmin(action, rest, p, out, argv) {
|
|
|
254
269
|
const variants = repeated(argv, "variant").map(parseVariant);
|
|
255
270
|
const count = Number(str(p.flags, "count"));
|
|
256
271
|
if (!project || !name || !variants.length || !Number.isInteger(count))
|
|
257
|
-
throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min]");
|
|
272
|
+
throw new CliError("usage", "pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...] --count <n> --sandbox <read-only|workspace-write|danger-full-access> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]");
|
|
258
273
|
const needs = { ...(str(p.flags, "needs") ? { labels: str(p.flags, "needs").split(",").map((x) => x.trim()).filter(Boolean) } : {}), ...(str(p.flags, "min-ram") ? { min_ram_gb: Number(str(p.flags, "min-ram")) } : {}) };
|
|
259
274
|
const tt = str(p.flags, "turn-timeout");
|
|
260
|
-
const
|
|
275
|
+
const tph = str(p.flags, "turns-per-hour");
|
|
276
|
+
if (tph !== undefined && (!/^\d+$/.test(tph) || Number(tph) < 1 || Number(tph) > 20))
|
|
277
|
+
throw new CliError("usage", "--turns-per-hour must be a whole number from 1 to 20");
|
|
278
|
+
const r = await c.call("PUT", `/projects/${project}/pools/${name}`, { role: str(p.flags, "role") ?? null, variants, count, sandbox: str(p.flags, "sandbox"), needs, ...(tt ? { turn_timeout: Number(tt) } : {}), ...(tph ? { turns_per_hour: Number(tph) } : {}) });
|
|
261
279
|
return out.print([...statusLines(r.pool), "Their machines' daemons start them within 30 s: b9s-admin machine show <machine>"].join("\n"), r);
|
|
262
280
|
}
|
|
263
281
|
if (action === "list" || action === undefined) {
|
package/dist/commands/machine.js
CHANGED
|
@@ -16,6 +16,7 @@ import { CLI_VERSION } from "../version.js";
|
|
|
16
16
|
import { probeCapabilities } from "../capabilities.js";
|
|
17
17
|
import { diskSpaceNotice } from "../notices.js";
|
|
18
18
|
import { verifyClaudeProvider } from "../providers.js";
|
|
19
|
+
import { resumeTurnGuard } from "../turn-guard.js";
|
|
19
20
|
export const machineFile = () => join(configRoot(), "machine.json");
|
|
20
21
|
export function loadMachine() {
|
|
21
22
|
const f = machineFile();
|
|
@@ -35,8 +36,8 @@ function writeMachineState(s) {
|
|
|
35
36
|
* again once with them. 2: the agent's own worktree git folder is writable under workspace-write.
|
|
36
37
|
* 3: turns get TMPDIR beside the checkout instead of the system's /tmp.
|
|
37
38
|
*/
|
|
38
|
-
const START_REV =
|
|
39
|
-
export const sessionFingerprint = (s, writable = []) => JSON.stringify([s.harness, ...(s.provider && s.provider !== "anthropic" ? [s.provider] : []), s.dir, s.sandbox, s.model, s.effort, s.turn_timeout, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
39
|
+
const START_REV = 4;
|
|
40
|
+
export const sessionFingerprint = (s, writable = []) => 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 ?? 20, ...(writable.length ? [writable] : []), ...(START_REV > 1 ? [`rev${START_REV}`] : [])]);
|
|
40
41
|
export const watchLabelOf = (ref) => `${WATCH_LABEL_PREFIX}${ref.replace("/", ".")}`;
|
|
41
42
|
/**
|
|
42
43
|
* During a maintenance drain or window, a session that would be started fresh (no known thread, so
|
|
@@ -55,7 +56,7 @@ export function maintenanceReport(drain, sessions) {
|
|
|
55
56
|
/** The `b9s start` arguments that bring a session up (adopting its thread or session when known). */
|
|
56
57
|
export function startArgs(s, thread, writable = []) {
|
|
57
58
|
return [
|
|
58
|
-
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--json",
|
|
59
|
+
"start", "--harness", s.harness, "--as", s.agent, "--sandbox", s.sandbox, "--turn-timeout", String(s.turn_timeout), "--turns-per-hour", String(s.turns_per_hour ?? 20), "--json",
|
|
59
60
|
...((s.provider ?? "anthropic") === "deepseek" ? ["--provider", "deepseek"] : []),
|
|
60
61
|
...(s.model ? ["--model", s.model] : []),
|
|
61
62
|
...(s.effort ? ["--effort", s.effort] : []),
|
|
@@ -130,6 +131,26 @@ export async function reconcile(m, log) {
|
|
|
130
131
|
if (!existsSync(s.dir))
|
|
131
132
|
throw new Error(`checkout ${s.dir} does not exist on this machine`);
|
|
132
133
|
const local = state.sessions[s.id];
|
|
134
|
+
let agentState = readState(s.agent);
|
|
135
|
+
if (s.turn_resume_at && agentState.turn_resume_applied_at !== s.turn_resume_at) {
|
|
136
|
+
agentState = { ...agentState, turn_guard: resumeTurnGuard(agentState.turn_guard), turn_resume_applied_at: s.turn_resume_at };
|
|
137
|
+
writeState(s.agent, agentState);
|
|
138
|
+
log(`${s.agent}: operator/assigner resumed turn mode`);
|
|
139
|
+
}
|
|
140
|
+
if (agentState.turn_guard?.fault) {
|
|
141
|
+
const fault = agentState.turn_guard.fault;
|
|
142
|
+
const detail = fault.reason === "unproductive"
|
|
143
|
+
? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call; likely cause: ${fault.likely_cause}`
|
|
144
|
+
: `the ${fault.turns_last_hour}-turn hourly ceiling was reached; likely cause: ${fault.likely_cause}`;
|
|
145
|
+
const error = `turn mode stopped after ${detail}; estimated tokens spent: ${fault.estimated_tokens}; last turn output: ${fault.output_tail || "(empty)"}`.slice(0, 1000);
|
|
146
|
+
const w = svc();
|
|
147
|
+
if (w) {
|
|
148
|
+
removeService(w);
|
|
149
|
+
log(`${s.agent}: turn mode fault; watcher service stopped`);
|
|
150
|
+
}
|
|
151
|
+
out.push({ id: s.id, state: "error", dir: s.dir, thread: local?.thread ?? s.thread, watcher: "inactive", error });
|
|
152
|
+
continue;
|
|
153
|
+
}
|
|
133
154
|
if (local) {
|
|
134
155
|
const conflict = existingSessionDirectoryConflict(s.id, s.dir, local.thread, s.agent);
|
|
135
156
|
if (conflict) {
|
|
@@ -137,7 +137,9 @@ function describeProcess(r) {
|
|
|
137
137
|
}
|
|
138
138
|
export async function processAdmin(action, rest, p, out) {
|
|
139
139
|
const c = adminClient(p);
|
|
140
|
-
const
|
|
140
|
+
const tagProjectFlag = action === "tag" ? str(p.flags, "project") : undefined;
|
|
141
|
+
const tagOperationFirst = action === "tag" && (["add", "edit", "remove"].includes(rest[0]) && (!(["add", "edit", "remove"].includes(rest[1])) || tagProjectFlag !== undefined));
|
|
142
|
+
const proj = tagProjectFlag ?? (tagOperationFirst ? rest[1] : rest[0]);
|
|
141
143
|
if (!proj && action !== undefined)
|
|
142
144
|
throw new CliError("usage", "admin process <show|export|set|tag|timing|merge|assigners|agreements|charter|steward> <project> ...");
|
|
143
145
|
const base = `/projects/${proj}/process`;
|
|
@@ -184,9 +186,10 @@ export async function processAdmin(action, rest, p, out) {
|
|
|
184
186
|
return publish(doc, `from ${file}`);
|
|
185
187
|
}
|
|
186
188
|
case "tag": {
|
|
187
|
-
const
|
|
189
|
+
const op = tagOperationFirst ? rest[0] : rest[1];
|
|
190
|
+
const tag = tagProjectFlag ? (rest[2] ?? rest[1]) : rest[2];
|
|
188
191
|
if (!["add", "edit", "remove"].includes(op) || !tag)
|
|
189
|
-
throw new CliError("usage", 'admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role
|
|
192
|
+
throw new CliError("usage", 'b9s-admin process tag add|edit|remove <project> <tag> [--meaning ".."] [--tier routine|careful|expert] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name] (legacy project-first order also accepted; for operation-first with project add, edit, or remove, use: process tag <op> <tag> --project <project>)');
|
|
190
193
|
const r = await get();
|
|
191
194
|
const tier = str(p.flags, "tier");
|
|
192
195
|
if (tier !== undefined && !["routine", "careful", "expert"].includes(tier))
|
package/dist/commands/watch.js
CHANGED
|
@@ -22,6 +22,8 @@ import { formatUpdates, gatherUpdates, reportDelivery } from "./hook.js";
|
|
|
22
22
|
import { readState, writeState } from "../state.js";
|
|
23
23
|
import { probeCapabilities } from "../capabilities.js";
|
|
24
24
|
import { fetchRecoveryBrief, formatRecoveryBrief, recoveryBriefUnavailableText, recoveryBriefWasDelivered } from "../brief.js";
|
|
25
|
+
import { beginGuardedTurn, completeGuardedTurn, DEFAULT_TURNS_PER_HOUR, MAX_UNPRODUCTIVE_TURNS } from "../turn-guard.js";
|
|
26
|
+
import { sessionUsage } from "../usage.js";
|
|
25
27
|
function omitMeasuresAlreadyIn(text, updates) {
|
|
26
28
|
if (!text)
|
|
27
29
|
return updates;
|
|
@@ -66,6 +68,11 @@ export async function watch(p, out) {
|
|
|
66
68
|
const turnTimeout = Number(str(p.flags, "turn-timeout") ?? "180");
|
|
67
69
|
if (!Number.isInteger(turnTimeout) || turnTimeout < 5)
|
|
68
70
|
throw new CliError("usage", "--turn-timeout must be a whole number of minutes, at least 5");
|
|
71
|
+
const turnsPerHour = Number(str(p.flags, "turns-per-hour") ?? String(DEFAULT_TURNS_PER_HOUR));
|
|
72
|
+
if (!Number.isInteger(turnsPerHour) || turnsPerHour < 1 || turnsPerHour > DEFAULT_TURNS_PER_HOUR)
|
|
73
|
+
throw new CliError("usage", `--turns-per-hour must be a whole number between 1 and ${DEFAULT_TURNS_PER_HOUR}`);
|
|
74
|
+
if (!turnMode && p.flags["turns-per-hour"] !== undefined)
|
|
75
|
+
throw new CliError("usage", "--turns-per-hour is only used with --turn");
|
|
69
76
|
const thread = exec ? threadOfExec(exec) : null;
|
|
70
77
|
// Which harness runs the turns and the session they continue. Codex watchers installed before
|
|
71
78
|
// 0.12.66 carry neither flag: their thread is in the exec command.
|
|
@@ -89,7 +96,7 @@ export async function watch(p, out) {
|
|
|
89
96
|
throw new CliError("usage", "--provider must be anthropic or deepseek");
|
|
90
97
|
if (providerName === "deepseek" && harness !== "claude-code")
|
|
91
98
|
throw new CliError("usage", "--provider deepseek requires --harness claude-code");
|
|
92
|
-
turn = { harness, session, timeout: turnTimeout, provider: providerName, model: str(p.flags, "model") };
|
|
99
|
+
turn = { harness, session, timeout: turnTimeout, turnsPerHour, provider: providerName, model: str(p.flags, "model") };
|
|
93
100
|
}
|
|
94
101
|
else if (p.flags.provider !== undefined) {
|
|
95
102
|
throw new CliError("usage", "--provider is only used with --turn --harness claude-code");
|
|
@@ -237,10 +244,10 @@ export async function watch(p, out) {
|
|
|
237
244
|
if (!full) {
|
|
238
245
|
try {
|
|
239
246
|
if (probe)
|
|
240
|
-
await turnStep(ctl, probe, turnTimeout, log, async (sink) => {
|
|
241
|
-
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" && turn.provider === "deepseek" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.());
|
|
247
|
+
await turnStep(ctl, probe, turnTimeout, log, async (sink, beforeTurn) => {
|
|
248
|
+
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, turn?.model ?? str(p.flags, "model"), once, sink, !resumeBriefDelivered, turn?.harness === "claude-code" && turn.provider === "deepseek" ? turn.provider : undefined, turn?.harness === "dsh", () => probe.beginTurn?.(), beforeTurn);
|
|
242
249
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
243
|
-
}, name);
|
|
250
|
+
}, name, turn?.turnsPerHour ?? turnsPerHour);
|
|
244
251
|
else {
|
|
245
252
|
const result = await wakeOnce(name, exec, unackedAfter, followDelay, log, str(p.flags, "model"), once, undefined, !resumeBriefDelivered);
|
|
246
253
|
resumeBriefDelivered = resumeBriefDelivered || result.recoveryBriefDelivered;
|
|
@@ -327,7 +334,7 @@ async function waitIntervalOrStop(ms, stopped) {
|
|
|
327
334
|
if (timer)
|
|
328
335
|
clearTimeout(timer);
|
|
329
336
|
}
|
|
330
|
-
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn) {
|
|
337
|
+
async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once, turnSink, includeResumeBrief = false, provider, turnStdin = false, beforeTurn, allowTurn) {
|
|
331
338
|
const state = readState(name);
|
|
332
339
|
const pending = state.watch_pending;
|
|
333
340
|
if (pending) {
|
|
@@ -414,7 +421,7 @@ async function wakeOnce(name, exec, unackedAfter, followDelay, log, model, once,
|
|
|
414
421
|
// `{summary}` commands get the same bounded prompt as `{text}`: this wrapper itself contains
|
|
415
422
|
// the acknowledgement, operator note, process pointer, read commands, and delivery body.
|
|
416
423
|
const line = wake;
|
|
417
|
-
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)))
|
|
424
|
+
if (!(await deliver(name, exec, wake, line, u ? u.tier : "process", total, log, operatorNew ? "operator message; " : "", seq, turnSink, payload?.delivery.by_kind ?? u?.delivery.by_kind, provider, model, turnStdin, beforeTurn, undefined, allowTurn)))
|
|
418
425
|
return { sent: false, recoveryBriefDelivered: false };
|
|
419
426
|
writeState(name, {
|
|
420
427
|
...readState(name),
|
|
@@ -439,7 +446,7 @@ async function recoveryBriefText(name, log) {
|
|
|
439
446
|
}
|
|
440
447
|
}
|
|
441
448
|
/** Runs the wake command (or prints the wake-up without one). False when the command failed: nothing was delivered. */
|
|
442
|
-
export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}) {
|
|
449
|
+
export async function deliver(name, exec, wake, summary, tier, total, log, prefix, seq, turnSink, kinds = {}, provider, model, turnStdin = false, beforeTurn, dependencies = {}, allowTurn) {
|
|
443
450
|
if (!exec) {
|
|
444
451
|
process.stdout.write(wake + "\n");
|
|
445
452
|
return true;
|
|
@@ -454,6 +461,8 @@ export async function deliver(name, exec, wake, summary, tier, total, log, prefi
|
|
|
454
461
|
// Provider credentials are read only when spawning the turn and are never persisted in the
|
|
455
462
|
// launchd/systemd service or its command line.
|
|
456
463
|
const providerEnv = claudeTurnEnv(provider, model, dependencies.providerRoot);
|
|
464
|
+
if (allowTurn && !(await allowTurn()))
|
|
465
|
+
return false;
|
|
457
466
|
beforeTurn?.();
|
|
458
467
|
turnSink((dependencies.startTurn ?? startTurn)(cmd, { ...env, BSCHAT_AGENT: name, ...providerEnv }, seq, turnStdin ? wake : undefined));
|
|
459
468
|
}
|
|
@@ -513,7 +522,7 @@ const KEY_CHECK_MS = 5 * 60_000;
|
|
|
513
522
|
* leaves the wake-up unacknowledged on the server, so a wake path that keeps failing shows as
|
|
514
523
|
* broken; one that runs past --turn-timeout is stopped and logged.
|
|
515
524
|
*/
|
|
516
|
-
export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
525
|
+
export async function turnStep(ctl, probe, timeoutMin, log, wake, name, turnsPerHour = DEFAULT_TURNS_PER_HOUR) {
|
|
517
526
|
const turn = ctl.turn;
|
|
518
527
|
if (turn) {
|
|
519
528
|
if (!turn.confirmed && probe.startedSince(turn.startedMs)) {
|
|
@@ -525,7 +534,15 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
525
534
|
const mins = Math.round((Date.now() - turn.startedMs) / 60_000);
|
|
526
535
|
const how = turn.exit.code !== null ? `exit ${turn.exit.code}` : `signal ${turn.exit.signal}`;
|
|
527
536
|
// A harness may exit 0 with an error in its result (Claude Code's is_error), so both count.
|
|
528
|
-
|
|
537
|
+
let error = null;
|
|
538
|
+
if (!turn.killedForTimeout) {
|
|
539
|
+
try {
|
|
540
|
+
error = probe.turnError();
|
|
541
|
+
}
|
|
542
|
+
catch (e) {
|
|
543
|
+
error = `could not read the harness result: ${e.message}`;
|
|
544
|
+
}
|
|
545
|
+
}
|
|
529
546
|
if (turn.exit.code === 0 && !error) {
|
|
530
547
|
if (!turn.confirmed)
|
|
531
548
|
await ackTurn(name, turn.seq, log);
|
|
@@ -551,6 +568,7 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
551
568
|
ctl.failedAt = Date.now();
|
|
552
569
|
}
|
|
553
570
|
ctl.turn = null;
|
|
571
|
+
await completePendingTurnGuard(name, probe, log);
|
|
554
572
|
return;
|
|
555
573
|
}
|
|
556
574
|
if (!turn.killedForTimeout && Date.now() - turn.startedMs > timeoutMin * 60_000) {
|
|
@@ -574,10 +592,25 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
574
592
|
// running by a watcher that restarted (turns run in their own process group and outlive it).
|
|
575
593
|
// Never start a second one.
|
|
576
594
|
const ph = probe.phase();
|
|
595
|
+
const savedGuard = readState(name).turn_guard;
|
|
596
|
+
if (savedGuard?.fault) {
|
|
597
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(savedGuard.fault)}; operator/assigner must resume this session before turns can continue`);
|
|
598
|
+
return;
|
|
599
|
+
}
|
|
577
600
|
if ("missing" in ph) {
|
|
601
|
+
if (savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
602
|
+
await completePendingTurnGuard(name, probe, log);
|
|
603
|
+
if (readState(name).turn_guard?.fault)
|
|
604
|
+
return;
|
|
605
|
+
}
|
|
578
606
|
log(ph.missing);
|
|
579
607
|
return;
|
|
580
608
|
}
|
|
609
|
+
if (!ph.running && savedGuard?.turns.some((attempt) => attempt.productive === null)) {
|
|
610
|
+
await completePendingTurnGuard(name, probe, log);
|
|
611
|
+
if (readState(name).turn_guard?.fault)
|
|
612
|
+
return;
|
|
613
|
+
}
|
|
581
614
|
if (probe.label === "DeepSeek Harness" && !ph.running && ph.lastError) {
|
|
582
615
|
const failedAt = Date.parse(ph.lastErrorAt ?? "");
|
|
583
616
|
if (Number.isFinite(failedAt)) {
|
|
@@ -640,7 +673,83 @@ export async function turnStep(ctl, probe, timeoutMin, log, wake, name) {
|
|
|
640
673
|
log(`wake-up ${st.watch_pending.seq !== undefined ? `#${st.watch_pending.seq} ` : ""}was never answered and no turn is running; a turn replaces it`);
|
|
641
674
|
writeState(name, { ...st, watch_pending: undefined, watch_dormant_logged_at: undefined });
|
|
642
675
|
}
|
|
643
|
-
await wake((t) => { ctl.turn = t; })
|
|
676
|
+
await wake((t) => { ctl.turn = t; }, async () => {
|
|
677
|
+
return beginTurnGuardAttempt(name, turnsPerHour, log);
|
|
678
|
+
});
|
|
679
|
+
}
|
|
680
|
+
async function turnActivity(name) {
|
|
681
|
+
const snapshot = await Client.forAgent(loadAgent(name), undefined, { presence: false }).call("GET", "/agents/me/turn-activity");
|
|
682
|
+
if (!Number.isInteger(snapshot.activity_seq) || snapshot.activity_seq < 0)
|
|
683
|
+
throw new Error("server returned an invalid turn activity sequence");
|
|
684
|
+
return snapshot;
|
|
685
|
+
}
|
|
686
|
+
/** Reserve every actual harness launch, including b9s start's onboarding turn. */
|
|
687
|
+
export async function beginTurnGuardAttempt(name, turnsPerHour, log) {
|
|
688
|
+
const before = await turnActivity(name);
|
|
689
|
+
const current = readState(name);
|
|
690
|
+
if (current.turn_guard?.fault) {
|
|
691
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(current.turn_guard.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
692
|
+
return false;
|
|
693
|
+
}
|
|
694
|
+
const begun = beginGuardedTurn(current.turn_guard, turnsPerHour, Date.now(), before.activity_seq);
|
|
695
|
+
writeState(name, { ...current, turn_guard: begun.state });
|
|
696
|
+
if (!begun.start) {
|
|
697
|
+
log(`TURN MODE FAULT: ${turnFaultSummary(begun.state.fault)}; no further turns until an operator or assigner resumes this session`);
|
|
698
|
+
return false;
|
|
699
|
+
}
|
|
700
|
+
return true;
|
|
701
|
+
}
|
|
702
|
+
export async function completePendingTurnGuard(name, probe, log, outputOverride) {
|
|
703
|
+
const current = readState(name);
|
|
704
|
+
const guard = current.turn_guard;
|
|
705
|
+
const pending = guard?.turns.slice().reverse().find((attempt) => attempt.productive === null);
|
|
706
|
+
if (!guard || !pending || pending.activity_seq_before === undefined)
|
|
707
|
+
return;
|
|
708
|
+
let activitySeq = pending.activity_seq_before;
|
|
709
|
+
let sampleError = null;
|
|
710
|
+
try {
|
|
711
|
+
activitySeq = (await turnActivity(name)).activity_seq;
|
|
712
|
+
}
|
|
713
|
+
catch (e) {
|
|
714
|
+
sampleError = `could not verify the agent's BenignSwarm activity: ${e.message}`;
|
|
715
|
+
}
|
|
716
|
+
const productive = activitySeq > pending.activity_seq_before;
|
|
717
|
+
let error = null;
|
|
718
|
+
let output = "";
|
|
719
|
+
let directTokens = null;
|
|
720
|
+
if (outputOverride === undefined) {
|
|
721
|
+
try {
|
|
722
|
+
error = probe.turnError();
|
|
723
|
+
}
|
|
724
|
+
catch (e) {
|
|
725
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read the harness result: ${e.message}`;
|
|
726
|
+
}
|
|
727
|
+
try {
|
|
728
|
+
output = probe.turnOutput?.() ?? "";
|
|
729
|
+
}
|
|
730
|
+
catch (e) {
|
|
731
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read the harness output: ${e.message}`;
|
|
732
|
+
}
|
|
733
|
+
}
|
|
734
|
+
else
|
|
735
|
+
output = outputOverride;
|
|
736
|
+
try {
|
|
737
|
+
directTokens = probe.turnTokens?.() ?? null;
|
|
738
|
+
}
|
|
739
|
+
catch (e) {
|
|
740
|
+
sampleError = `${sampleError ? `${sampleError}; ` : ""}could not read harness token usage: ${e.message}`;
|
|
741
|
+
}
|
|
742
|
+
output = (output || error || sampleError || "").slice(-800);
|
|
743
|
+
const measured = current.harness_session ? sessionUsage(current.harness_session, new Date(pending.at).toISOString(), new Date().toISOString()).tokens?.total ?? 0 : 0;
|
|
744
|
+
const nextGuard = completeGuardedTurn(guard, Date.now(), productive, output, directTokens !== null && directTokens > 0 ? directTokens : measured > 0 ? measured : null);
|
|
745
|
+
writeState(name, { ...current, turn_guard: nextGuard });
|
|
746
|
+
if (!productive)
|
|
747
|
+
log(`turn made no agent-key call to BenignSwarm (${nextGuard.consecutive_unproductive}/${MAX_UNPRODUCTIVE_TURNS} consecutive); ${nextGuard.fault ? `FAULT: ${turnFaultSummary(nextGuard.fault)}` : `last output: ${output || "(empty)"}`}`);
|
|
748
|
+
else if (nextGuard.consecutive_unproductive === 0)
|
|
749
|
+
log("turn was productive: an agent-key call reached BenignSwarm");
|
|
750
|
+
}
|
|
751
|
+
function turnFaultSummary(fault) {
|
|
752
|
+
return `${fault.reason === "unproductive" ? `${fault.consecutive_unproductive} consecutive turns made no BenignSwarm call` : `hourly ceiling reached (${fault.turns_last_hour} turns in the last hour)`}; likely cause: ${fault.likely_cause}; estimated tokens spent: ${fault.estimated_tokens}`;
|
|
644
753
|
}
|
|
645
754
|
/** The watcher acknowledges a turn it started: the session shows the agent has the prompt. */
|
|
646
755
|
async function ackTurn(name, seq, log) {
|
|
@@ -764,7 +873,7 @@ function installLaunchd(name, exec, interval, followDelay, extraEnv, activity, o
|
|
|
764
873
|
bindSession(sess.kind, sess.id, name);
|
|
765
874
|
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] });
|
|
766
875
|
}
|
|
767
|
-
const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
|
|
876
|
+
const turnArgs = (t) => (t ? ["--turn", "--turn-timeout", String(t.timeout), "--turns-per-hour", String(t.turnsPerHour), "--harness", t.harness, "--session", t.session, ...(t.provider === "deepseek" ? ["--provider", t.provider] : []), ...(t.model ? ["--model", t.model] : [])] : []);
|
|
768
877
|
function escapeXml(s) {
|
|
769
878
|
return s.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
|
|
770
879
|
}
|
|
@@ -4,9 +4,27 @@ import { Client } from "../client.js";
|
|
|
4
4
|
import { loadAgent, resolveAgentName } from "../config.js";
|
|
5
5
|
import { CliError } from "../errors.js";
|
|
6
6
|
import { spawnSync } from "node:child_process";
|
|
7
|
-
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable } from "../git.js";
|
|
7
|
+
import { archiveWorktreeChanges, defaultMachine, formatBytes, freeSpaceProbe, scanWorktrees, pruneReport, removePrunable, PRUNE_STATUS_TIMEOUT_MS } from "../git.js";
|
|
8
8
|
import { table } from "../output.js";
|
|
9
9
|
const CLOSED = ["done", "abandoned", "superseded"];
|
|
10
|
+
const PRUNE_UNIT_STATES_TIMEOUT_MS = 30_000;
|
|
11
|
+
const WORKTREE_SCAN_TIMEOUT_MS = 30_000;
|
|
12
|
+
async function timedClientCall(client, method, path, body, timeoutMs, operation) {
|
|
13
|
+
const controller = new AbortController();
|
|
14
|
+
let timedOut = false;
|
|
15
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
16
|
+
try {
|
|
17
|
+
return await client.call(method, path, body, { signal: controller.signal });
|
|
18
|
+
}
|
|
19
|
+
catch (error) {
|
|
20
|
+
if (timedOut)
|
|
21
|
+
throw new CliError("timeout", `timed out waiting for ${operation} after ${timeoutMs} ms`);
|
|
22
|
+
throw error;
|
|
23
|
+
}
|
|
24
|
+
finally {
|
|
25
|
+
clearTimeout(timer);
|
|
26
|
+
}
|
|
27
|
+
}
|
|
10
28
|
/**
|
|
11
29
|
* What the project's units say about worktrees on this machine: worktrees of units not yet
|
|
12
30
|
* closed (by path, and by branch for a path recorded elsewhere) are never pruned; clean
|
|
@@ -15,8 +33,24 @@ const CLOSED = ["done", "abandoned", "superseded"];
|
|
|
15
33
|
* disk and are skipped one by one; a failure to read the units is an error, never a quieter
|
|
16
34
|
* prune (before, one missing path threw and silently discarded every closed unit).
|
|
17
35
|
*/
|
|
18
|
-
export async function unitWorktrees(creds, project) {
|
|
19
|
-
const
|
|
36
|
+
export async function unitWorktrees(creds, project, options = {}) {
|
|
37
|
+
const timeoutMs = options.timeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
|
|
38
|
+
options.onProgress?.(`Fetching unit states for project ${project} (timeout ${timeoutMs} ms)`);
|
|
39
|
+
const controller = new AbortController();
|
|
40
|
+
let timedOut = false;
|
|
41
|
+
const timer = setTimeout(() => { timedOut = true; controller.abort(); }, timeoutMs);
|
|
42
|
+
let all;
|
|
43
|
+
try {
|
|
44
|
+
all = await Client.forAgent(creds, undefined, { presence: false }).call("GET", `/projects/${project}/work-units?all=1`, undefined, { signal: controller.signal });
|
|
45
|
+
}
|
|
46
|
+
catch (error) {
|
|
47
|
+
if (timedOut)
|
|
48
|
+
throw new CliError("timeout", `timed out waiting for unit states from server for project ${project} after ${timeoutMs} ms`);
|
|
49
|
+
throw error;
|
|
50
|
+
}
|
|
51
|
+
finally {
|
|
52
|
+
clearTimeout(timer);
|
|
53
|
+
}
|
|
20
54
|
const closed = new Map();
|
|
21
55
|
const active = { paths: new Map(), branches: new Map() };
|
|
22
56
|
for (const u of all.units) {
|
|
@@ -39,7 +73,7 @@ export async function unitWorktrees(creds, project) {
|
|
|
39
73
|
* b9s worktrees every worktree the project knows about: machine, path, branch, dirty, merged, who, suggestion
|
|
40
74
|
* b9s worktrees scan report every linked worktree of the repository you are in (run on each machine)
|
|
41
75
|
*/
|
|
42
|
-
export async function worktrees(p, out) {
|
|
76
|
+
export async function worktrees(p, out, timeouts = {}) {
|
|
43
77
|
const sub = p.positionals[1];
|
|
44
78
|
const name = resolveAgentName(str(p.flags, "as"));
|
|
45
79
|
const creds = loadAgent(name);
|
|
@@ -50,8 +84,11 @@ export async function worktrees(p, out) {
|
|
|
50
84
|
// Space back: delete linked worktrees that are clean and merged into the base branch. Dry run
|
|
51
85
|
// unless --yes. Branches are kept (deleting a worktree never deletes its branch).
|
|
52
86
|
// Worktrees recorded on units that are done or abandoned: clean ones go even if their branch never merged.
|
|
53
|
-
const
|
|
54
|
-
const
|
|
87
|
+
const progress = (line) => process.stderr.write(`b9s: ${line}\n`);
|
|
88
|
+
const requestTimeoutMs = timeouts.requestTimeoutMs ?? PRUNE_UNIT_STATES_TIMEOUT_MS;
|
|
89
|
+
const statusTimeoutMs = timeouts.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS;
|
|
90
|
+
const units = await unitWorktrees(creds, project, { timeoutMs: requestTimeoutMs, onProgress: progress });
|
|
91
|
+
const rep = pruneReport(process.cwd(), units.closed, units.active, undefined, { onProgress: progress, statusTimeoutMs });
|
|
55
92
|
// --archive: a closed unit's worktree with uncommitted files is saved to archive/wu<n>-leftovers
|
|
56
93
|
// and then removed. Never for a unit still open, never for a worktree whose status is unreadable.
|
|
57
94
|
const archive = bool(p.flags, "archive") ? rep.kept.filter((k) => k.archivable) : [];
|
|
@@ -93,16 +130,20 @@ export async function worktrees(p, out) {
|
|
|
93
130
|
const kept = [];
|
|
94
131
|
const probe = freeSpaceProbe(candidates.map((c) => c.path));
|
|
95
132
|
for (const c of candidates) {
|
|
96
|
-
const r = removePrunable(c);
|
|
133
|
+
const r = removePrunable(c, process.cwd(), statusTimeoutMs);
|
|
97
134
|
if (r.removed)
|
|
98
135
|
removed.push(c.path);
|
|
99
136
|
else
|
|
100
137
|
kept.push({ path: c.path, reason: r.reason ?? "git refused" });
|
|
101
138
|
}
|
|
102
139
|
try {
|
|
103
|
-
await scanProject(creds, project);
|
|
140
|
+
await scanProject(creds, project, { statusTimeoutMs, onProgress: progress, requestTimeoutMs });
|
|
141
|
+
}
|
|
142
|
+
catch (error) {
|
|
143
|
+
if (error instanceof CliError && error.code === "timeout")
|
|
144
|
+
throw error;
|
|
145
|
+
/* the registry catches up on the next scan */
|
|
104
146
|
}
|
|
105
|
-
catch { /* the registry catches up on the next scan */ }
|
|
106
147
|
out.print(`Removed ${removed.length} worktree(s)${removed.length ? `:\n${removed.map((r) => ` ${r}`).join("\n")}` : ""}${kept.length ? `\nKept ${kept.length}: ${kept.map((k) => `${k.path} (${k.reason})`).join("; ")}` : ""}${removed.length ? freedText(probe) : ""}`, { removed, kept, candidates, free_space: probe.after() });
|
|
107
148
|
return;
|
|
108
149
|
}
|
|
@@ -121,12 +162,14 @@ export async function worktrees(p, out) {
|
|
|
121
162
|
out.print(rows.length ? table(rows, ["suggestion", "machine", "path", "branch", "state", "idle", "who", "unit"]) : "(no worktrees recorded; agents register them by working, or run: b9s worktrees scan)", r);
|
|
122
163
|
}
|
|
123
164
|
/** Scan the repository at cwd and report it. Shared with the watcher, which runs it periodically. */
|
|
124
|
-
export async function scanProject(creds, project) {
|
|
125
|
-
const scan = scanWorktrees();
|
|
165
|
+
export async function scanProject(creds, project, options = {}) {
|
|
166
|
+
const scan = scanWorktrees(process.cwd(), options);
|
|
126
167
|
if (!scan)
|
|
127
168
|
throw new CliError("not_a_repo", "the current directory is not inside a git repository", "Run b9s worktrees scan from a checkout of the project's repository.");
|
|
128
169
|
const machine = creds.machine || defaultMachine();
|
|
129
170
|
const client = Client.forAgent(creds, undefined, { presence: false });
|
|
130
|
-
const
|
|
171
|
+
const timeoutMs = options.requestTimeoutMs ?? WORKTREE_SCAN_TIMEOUT_MS;
|
|
172
|
+
options.onProgress?.(`Reporting worktrees for project ${project} (timeout ${timeoutMs} ms)`);
|
|
173
|
+
const r = await timedClientCall(client, "POST", `/projects/${project}/worktrees/scan`, { machine, repo: scan.repo, worktrees: scan.worktrees }, timeoutMs, `worktree registry scan for project ${project}`);
|
|
131
174
|
return { machine, repo: scan.repo, recorded: r.recorded, missing: r.missing };
|
|
132
175
|
}
|
package/dist/commands/wu.js
CHANGED
|
@@ -1030,6 +1030,15 @@ export async function askOperator(p, out) {
|
|
|
1030
1030
|
const project = creds.project ?? str(p.flags, "project") ?? process.env.BSCHAT_PROJECT;
|
|
1031
1031
|
if (!project)
|
|
1032
1032
|
throw new CliError("no_project", `${creds.agent} is an account-scoped agent; pass --project <name>`);
|
|
1033
|
+
if (p.positionals[1] === "withdraw") {
|
|
1034
|
+
const id = p.positionals[2];
|
|
1035
|
+
const note = str(p.flags, "note")?.trim();
|
|
1036
|
+
if (!id || !note)
|
|
1037
|
+
throw new CliError("usage", 'ask-operator withdraw <key> --note "why this no longer needs an operator answer"');
|
|
1038
|
+
const result = await client.call("POST", `/projects/${project}/asks/${id}/withdraw`, { note });
|
|
1039
|
+
out.print(`Withdrew ask ${id}; it is no longer waiting on the operator.`, result);
|
|
1040
|
+
return;
|
|
1041
|
+
}
|
|
1033
1042
|
const amend = str(p.flags, "amend");
|
|
1034
1043
|
if (amend) {
|
|
1035
1044
|
const text = (p.positionals.slice(1).join(" ") || str(p.flags, "question") || "").trim();
|
package/dist/git.js
CHANGED
|
@@ -2,6 +2,18 @@ import { copyFileSync, existsSync, readdirSync, realpathSync, rmSync, statSync,
|
|
|
2
2
|
import { spawnSync } from "node:child_process";
|
|
3
3
|
import { hostname } from "node:os";
|
|
4
4
|
import { dirname, join } from "node:path";
|
|
5
|
+
import { CliError } from "./errors.js";
|
|
6
|
+
export const PRUNE_STATUS_TIMEOUT_MS = 30_000;
|
|
7
|
+
function status(cwd, timeoutMs) {
|
|
8
|
+
const r = spawnSync("git", ["status", "--porcelain"], { cwd, encoding: "utf8", stdio: ["ignore", "pipe", "ignore"], maxBuffer: 512 * 1024 * 1024, ...(timeoutMs === undefined ? {} : { timeout: timeoutMs }) });
|
|
9
|
+
const errorCode = r.error?.code;
|
|
10
|
+
if (errorCode === "ETIMEDOUT" || (r.error && /timed out/i.test(r.error.message))) {
|
|
11
|
+
throw new CliError("timeout", `git status timed out after ${timeoutMs} ms in worktree ${cwd}`);
|
|
12
|
+
}
|
|
13
|
+
if (r.status !== 0)
|
|
14
|
+
return null;
|
|
15
|
+
return r.stdout.trim();
|
|
16
|
+
}
|
|
5
17
|
function git(args, cwd) {
|
|
6
18
|
// Large enough for `git status` on a big repo with every file changed (ester: 226k files, 25 MB);
|
|
7
19
|
// the 1 MB default made such a worktree unreadable rather than dirty.
|
|
@@ -42,7 +54,7 @@ export function mergeFacts(cwd, worktree) {
|
|
|
42
54
|
return { repo, base, merged, ahead: count === null ? null : Number(count) };
|
|
43
55
|
}
|
|
44
56
|
/** Every linked worktree of the repository at cwd, with the same facts an agent call reports. */
|
|
45
|
-
export function scanWorktrees(cwd = process.cwd()) {
|
|
57
|
+
export function scanWorktrees(cwd = process.cwd(), options = {}) {
|
|
46
58
|
const list = git(["worktree", "list", "--porcelain"], cwd);
|
|
47
59
|
if (list === null)
|
|
48
60
|
return null;
|
|
@@ -50,13 +62,15 @@ export function scanWorktrees(cwd = process.cwd()) {
|
|
|
50
62
|
if (!paths.length)
|
|
51
63
|
return null;
|
|
52
64
|
const repo = paths[0];
|
|
65
|
+
options.onProgress?.(`Scanning repository ${repo}`);
|
|
53
66
|
const worktrees = paths.map((p) => {
|
|
67
|
+
options.onProgress?.(`Scanning worktree ${p}`);
|
|
54
68
|
const branch = git(["symbolic-ref", "--short", "-q", "HEAD"], p) ?? git(["rev-parse", "--short", "HEAD"], p);
|
|
55
69
|
const head = git(["rev-parse", "--short", "HEAD"], p);
|
|
56
|
-
const
|
|
70
|
+
const worktreeStatus = status(p, options.statusTimeoutMs);
|
|
57
71
|
const f = head ? mergeFacts(p, p) : { base: null, merged: null, ahead: null };
|
|
58
72
|
const empty = existsSync(p) && readdirSync(p).every((e) => e === ".git");
|
|
59
|
-
return { path: p, branch, head, dirty:
|
|
73
|
+
return { path: p, branch, head, dirty: worktreeStatus === null ? null : worktreeStatus.length > 0, base: f.base, merged: f.merged, ahead: f.ahead, empty };
|
|
60
74
|
});
|
|
61
75
|
return { repo, worktrees };
|
|
62
76
|
}
|
|
@@ -137,12 +151,16 @@ export function commitAtTime(ref, iso, cwd = process.cwd()) {
|
|
|
137
151
|
export function createWorktree(path, branch, base, cwd = process.cwd(), exclude = []) {
|
|
138
152
|
const exists = git(["rev-parse", "--verify", "-q", `refs/heads/${branch}`], cwd) !== null;
|
|
139
153
|
const sparse = exclude.length > 0;
|
|
140
|
-
|
|
154
|
+
// Always defer checkout until we have explicitly applied this project's policy. Otherwise Git
|
|
155
|
+
// may inherit the source worktree's shared sparse-checkout settings.
|
|
156
|
+
const args = ["worktree", "add", "--no-checkout", ...(exists ? [path, branch] : ["-b", branch, path, base])];
|
|
141
157
|
const r = spawnSync("git", args, { cwd, encoding: "utf8" });
|
|
142
158
|
if (r.status !== 0)
|
|
143
159
|
throw new Error(`git ${args.join(" ")}: ${(r.stderr || r.stdout).trim()}`);
|
|
144
160
|
if (sparse)
|
|
145
161
|
applySparse(path, exclude);
|
|
162
|
+
else
|
|
163
|
+
applyFullCheckout(path);
|
|
146
164
|
}
|
|
147
165
|
/**
|
|
148
166
|
* Non-cone sparse checkout patterns that keep everything except `exclude` (repository paths such as
|
|
@@ -157,6 +175,14 @@ export function applySparse(path, exclude) {
|
|
|
157
175
|
throw new Error(`git ${args.join(" ")} in ${path}: ${(r.stderr || r.stdout).trim()}`);
|
|
158
176
|
}
|
|
159
177
|
}
|
|
178
|
+
/** Disables any inherited sparse-checkout configuration and checks out every tracked path. */
|
|
179
|
+
export function applyFullCheckout(path) {
|
|
180
|
+
for (const args of [["sparse-checkout", "disable"], ["reset", "-q", "--hard", "HEAD"]]) {
|
|
181
|
+
const r = spawnSync("git", args, { cwd: path, encoding: "utf8", maxBuffer: 64 * 1024 * 1024 });
|
|
182
|
+
if (r.status !== 0)
|
|
183
|
+
throw new Error(`git ${args.join(" ")} in ${path}: ${(r.stderr || r.stdout).trim()}`);
|
|
184
|
+
}
|
|
185
|
+
}
|
|
160
186
|
/** What git says about the worktree at `path`, from `git worktree list` plus a status probe. */
|
|
161
187
|
export function worktreeState(path, cwd = process.cwd()) {
|
|
162
188
|
const list = git(["worktree", "list", "--porcelain"], cwd) ?? "";
|
|
@@ -222,8 +248,9 @@ export function ensureWorktree(path, branch, base, cwd = process.cwd(), log = ()
|
|
|
222
248
|
repaired = true;
|
|
223
249
|
}
|
|
224
250
|
const files = (git(["ls-files"], cwd) ?? "").split("\n").length;
|
|
225
|
-
|
|
226
|
-
|
|
251
|
+
log(exclude.length
|
|
252
|
+
? `creating ${path} with project checkout exclusions: ${exclude.join(", ")}${files > 20_000 ? ` (${files.toLocaleString()} tracked files)` : ""}`
|
|
253
|
+
: `creating ${path} with a full checkout (no project exclusions)${files > 20_000 ? `; ${files.toLocaleString()} tracked files, this can take a minute or more` : ""}`);
|
|
227
254
|
createWorktree(path, branch, base, cwd, exclude);
|
|
228
255
|
return { created: true, repaired };
|
|
229
256
|
}
|
|
@@ -258,8 +285,8 @@ export function landedByContent(head, base, cwd) {
|
|
|
258
285
|
* machine whose local main is behind does not keep work that already landed, or that its
|
|
259
286
|
* changes are already there by content (rebased or squashed landings).
|
|
260
287
|
*/
|
|
261
|
-
export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }, minAgeMs = 24 * 3600_000) {
|
|
262
|
-
const scan = scanWorktrees(cwd);
|
|
288
|
+
export function pruneReport(cwd = process.cwd(), closedUnitPaths = new Map(), activeUnits = { paths: new Map(), branches: new Map() }, minAgeMs = 24 * 3600_000, options = {}) {
|
|
289
|
+
const scan = scanWorktrees(cwd, { ...options, statusTimeoutMs: options.statusTimeoutMs ?? PRUNE_STATUS_TIMEOUT_MS });
|
|
263
290
|
if (!scan)
|
|
264
291
|
return { prunable: [], kept: [], base: null };
|
|
265
292
|
const here = realpathOrSelf(cwd);
|
|
@@ -458,19 +485,19 @@ export function formatBytes(n) {
|
|
|
458
485
|
return n < 0 ? `-${s}` : s;
|
|
459
486
|
}
|
|
460
487
|
/** Removes a prune candidate: an empty checkout (re-checked here) by force, anything else only when clean. */
|
|
461
|
-
export function removePrunable(c, cwd = process.cwd()) {
|
|
488
|
+
export function removePrunable(c, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
|
|
462
489
|
if (!c.empty)
|
|
463
|
-
return removeWorktreeIfClean(c.path, cwd);
|
|
490
|
+
return removeWorktreeIfClean(c.path, cwd, statusTimeoutMs);
|
|
464
491
|
if (!existsSync(c.path) || !readdirSync(c.path).every((e) => e === ".git"))
|
|
465
492
|
return { removed: false, reason: "no longer an empty checkout" };
|
|
466
493
|
const r = spawnSync("git", ["worktree", "remove", "--force", c.path], { cwd, encoding: "utf8" });
|
|
467
494
|
return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
|
|
468
495
|
}
|
|
469
|
-
export function removeWorktreeIfClean(path, cwd = process.cwd()) {
|
|
470
|
-
const
|
|
471
|
-
if (
|
|
496
|
+
export function removeWorktreeIfClean(path, cwd = process.cwd(), statusTimeoutMs = PRUNE_STATUS_TIMEOUT_MS) {
|
|
497
|
+
const worktreeStatus = status(path, statusTimeoutMs);
|
|
498
|
+
if (worktreeStatus === null)
|
|
472
499
|
return { removed: false, reason: "not a worktree" };
|
|
473
|
-
if (
|
|
500
|
+
if (worktreeStatus.length > 0)
|
|
474
501
|
return { removed: false, reason: "uncommitted changes" };
|
|
475
502
|
const r = spawnSync("git", ["worktree", "remove", path], { cwd, encoding: "utf8" });
|
|
476
503
|
return r.status === 0 ? { removed: true } : { removed: false, reason: (r.stderr || r.stdout).trim() };
|
package/dist/harnesses.js
CHANGED
|
@@ -226,6 +226,11 @@ export function dshProbe(session, ref, path = dshTurnLog(ref), processes) {
|
|
|
226
226
|
},
|
|
227
227
|
startedSince() { return dshEvents(readInvocation(invocationOffset)).some((e) => e.type === "status" && e.phase === "turn_start"); },
|
|
228
228
|
turnError: () => dshResultError(readInvocation(invocationOffset)),
|
|
229
|
+
turnOutput: () => readInvocation(invocationOffset).slice(-800),
|
|
230
|
+
turnTokens: () => {
|
|
231
|
+
const events = dshEvents(readInvocation(invocationOffset));
|
|
232
|
+
return events.reduce((sum, event) => sum + (event.usage?.inputTokens ?? 0) + (event.usage?.cacheReadTokens ?? 0) + (event.usage?.cacheWriteTokens ?? 0) + (event.usage?.outputTokens ?? 0), 0);
|
|
233
|
+
},
|
|
229
234
|
limitUntil: () => null,
|
|
230
235
|
isLimit: () => false,
|
|
231
236
|
};
|
|
@@ -247,6 +252,24 @@ function codexProbe(thread) {
|
|
|
247
252
|
},
|
|
248
253
|
startedSince(ms) { const ph = read(); return !!ph?.startedAt && Date.parse(ph.startedAt) >= ms - 5_000; },
|
|
249
254
|
turnError() { return read()?.lastError ?? null; },
|
|
255
|
+
turnOutput() {
|
|
256
|
+
const path = codexRollout(thread);
|
|
257
|
+
if (!path)
|
|
258
|
+
return "";
|
|
259
|
+
const messages = readFileSync(path, "utf8").split("\n").flatMap((line) => {
|
|
260
|
+
try {
|
|
261
|
+
const event = JSON.parse(line);
|
|
262
|
+
if (event.type !== "response_item" || event.payload?.type !== "message" || event.payload.message?.role !== "assistant")
|
|
263
|
+
return [];
|
|
264
|
+
const content = event.payload.message.content;
|
|
265
|
+
return typeof content === "string" ? [content] : Array.isArray(content) ? content.flatMap((part) => typeof part.text === "string" ? [part.text] : []) : [];
|
|
266
|
+
}
|
|
267
|
+
catch {
|
|
268
|
+
return [];
|
|
269
|
+
}
|
|
270
|
+
});
|
|
271
|
+
return messages.join("\n").slice(-800);
|
|
272
|
+
},
|
|
250
273
|
limitUntil: usageLimitUntil,
|
|
251
274
|
isLimit: (e) => !!e && /usage limit/i.test(e),
|
|
252
275
|
};
|
|
@@ -378,6 +401,29 @@ function claudeProbe(session, ref) {
|
|
|
378
401
|
return !!p && Date.parse(p) >= ms - 5_000;
|
|
379
402
|
},
|
|
380
403
|
turnError: () => lastResult()?.error ?? null,
|
|
404
|
+
turnOutput: () => {
|
|
405
|
+
if (!existsSync(resultFile))
|
|
406
|
+
return "";
|
|
407
|
+
try {
|
|
408
|
+
const result = JSON.parse(readFileSync(resultFile, "utf8").trim().split("\n").filter((line) => line.startsWith("{")).pop() ?? "");
|
|
409
|
+
return typeof result.result === "string" ? result.result.slice(-800) : "";
|
|
410
|
+
}
|
|
411
|
+
catch {
|
|
412
|
+
return readFileSync(resultFile, "utf8").slice(-800);
|
|
413
|
+
}
|
|
414
|
+
},
|
|
415
|
+
turnTokens: () => {
|
|
416
|
+
if (!existsSync(resultFile))
|
|
417
|
+
return null;
|
|
418
|
+
try {
|
|
419
|
+
const result = JSON.parse(readFileSync(resultFile, "utf8").trim().split("\n").filter((line) => line.startsWith("{")).pop() ?? "");
|
|
420
|
+
const u = result.usage;
|
|
421
|
+
return u ? (u.input_tokens ?? 0) + (u.output_tokens ?? 0) + (u.cache_read_input_tokens ?? 0) + (u.cache_creation_input_tokens ?? 0) : null;
|
|
422
|
+
}
|
|
423
|
+
catch {
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
},
|
|
381
427
|
limitUntil: (e) => claudeLimitUntil(e),
|
|
382
428
|
isLimit: claudeIsLimit,
|
|
383
429
|
};
|
package/dist/help.js
CHANGED
|
@@ -115,6 +115,7 @@ Agent commands
|
|
|
115
115
|
b9s wu scope <n> --append ".." --note ".." add a dated scope amendment (up to 2000 chars); the base scope stays capped at 4000
|
|
116
116
|
b9s ask-operator "what you need from them" --plain ".." --blocks ".." --if-yes ".." --if-no ".." [--propose ".."]
|
|
117
117
|
b9s ask-operator --amend <id> ["new question"] [--plain ".."] [--blocks ".."] [--if-yes ".."] [--if-no ".."] [--propose ".."] amend your own open ask
|
|
118
|
+
b9s ask-operator withdraw <key> --note "why it no longer needs an operator answer" withdraw your own ask, a steward-raised declared-wait ask, or an ask if you are a project assigner
|
|
118
119
|
b9s ask-operator refuses a second ask naming the same WU; use --amend <id>. Account needs group asks/questions by unit and can answer several together.
|
|
119
120
|
a decision only the operator can make, on their console banner and reported to them; never
|
|
120
121
|
ask in chat. --plain: one or two sentences for someone who has not read the thread; --propose: your recommended answer, phrased so they can approve it as written; --blocks: what's stuck; --if-yes/--if-no: what happens on each answer
|
|
@@ -144,7 +145,10 @@ Agent commands
|
|
|
144
145
|
--env A,B copies those variables from this shell into the LaunchAgent (Antigravity needs
|
|
145
146
|
ANTIGRAVITY_LS_ADDRESS,ANTIGRAVITY_CSRF_TOKEN). --full queues the text itself. --once /
|
|
146
147
|
--service (launchd on macOS, systemd on Linux; --launchd is the same). --turn runs each turn
|
|
147
|
-
itself (--harness codex|claude-code|dsh --session <id>);
|
|
148
|
+
itself (--harness codex|claude-code|dsh --session <id>); 3 consecutive turns without an
|
|
149
|
+
agent-key call stop it and report a machine error; max 20 turns/hour (lower with
|
|
150
|
+
--turns-per-hour 1..20). A fault persists across watcher restarts; an operator or
|
|
151
|
+
assigner resumes it with b9s-admin machine session resume.
|
|
148
152
|
Codex: b9s watch --exec "codex queue --thread <id> --message {summary}" --service
|
|
149
153
|
b9s update the same as install --latest: upgrade this machine's b9s, repair PATH aliases,
|
|
150
154
|
restart services on that install without waiting on one stop, and report failures
|
|
@@ -153,7 +157,7 @@ Agent commands
|
|
|
153
157
|
b9s doctor every b9s on this machine and who runs which (PATH, npx caches, this repo's
|
|
154
158
|
hook and instructions, each watcher's plist versus what launchd runs), with fixes
|
|
155
159
|
b9s codex hooks | bind <thread-id> | sync install b9s's Codex hooks (~/.codex/hooks.json) and say which thread is you
|
|
156
|
-
b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--dsh path]
|
|
160
|
+
b9s start --harness codex|claude-code|dsh --as <a> --sandbox <mode> [--provider anthropic|deepseek] [--token t] [--thread id] [--model m] [--effort e] [--turns-per-hour 1..20] [--dsh path]
|
|
157
161
|
run an agent headless: enroll, start or adopt its session, turn-mode watcher
|
|
158
162
|
(b9s codex start is the same with --harness codex)
|
|
159
163
|
b9s unpause [--as <a>] lift a usage-limit pause now (the harness was switched to an account with quota)
|
|
@@ -244,6 +248,8 @@ b9s-admin login (approve it in your signed-in browser); the session lasts 30 day
|
|
|
244
248
|
b9s-admin process show|export <project> [--out f] the process as agents are told it, or as an editable file
|
|
245
249
|
b9s-admin process set <project> --file process.json publish definition, vocabulary and agreements in one version (including capabilities, review_rules and tag focus)
|
|
246
250
|
b9s-admin process tag add|edit|remove <project> <tag> [--meaning ..] [--tier routine|careful|expert] [--require-evidence yes|no] [--require-rebased yes|no] [--expert-role r|none] [--requires name,name]
|
|
251
|
+
legacy project-first order also accepted; for operation-first with a project named add, edit, or remove:
|
|
252
|
+
b9s-admin process tag <op> <tag> --project <project>
|
|
247
253
|
b9s-admin process timing <project> [--sla m] [--takeover m] [--max-open n] [--max-in-progress n] [--require-scope yes|no] [--require-evidence yes|no] [--require-cited-changes yes|no] [--default-approver r|none]
|
|
248
254
|
b9s-admin process merge <project> [--target b] [--merged-by owner|approver|integrator] [--integrator-role r] [--require-rebased|--require-merge-commit|--require-pushed yes|no]
|
|
249
255
|
b9s-admin process assigners <project> role1,role2 | agreements <project> --file agreements.md
|
|
@@ -276,8 +282,9 @@ Machines (provisioned over your own ssh; a daemon on each runs the agent session
|
|
|
276
282
|
b9s-admin machine maintenance <name> --at <ISO | HH:MM> --for <30m | 2h> | --cancel a window: no new turns from
|
|
277
283
|
15 min before, its agents away until the machine reports back after booting
|
|
278
284
|
b9s-admin machine session add <machine> <project>/<agent> --dir <checkout> --sandbox <read-only|workspace-write|danger-full-access> [--harness codex|claude-code] [--provider anthropic|deepseek]
|
|
279
|
-
[--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min]
|
|
280
|
-
b9s-admin machine session stop|start|remove <machine> <project>/<agent>
|
|
285
|
+
[--create --role <role>] [--model m] [--effort e] [--thread <id>] [--turn-timeout min] [--turns-per-hour 1..20]
|
|
286
|
+
b9s-admin machine session stop|start|resume|limit|remove <machine> <project>/<agent> resume a latched turn fault or set a lower per-session hourly limit
|
|
287
|
+
(change its count/settings, pause scaling, pin, or bench the agent)
|
|
281
288
|
b9s-admin agent move <project>/<agent> --to <machine> --sandbox <mode> [--dir <path>|auto] [--harness codex|claude-code] [--provider anthropic|deepseek] [--carry note|thread]
|
|
282
289
|
[--from local|<ssh host>] [--model m] [--effort e] [--wait min] [--force]
|
|
283
290
|
run an existing agent on a provisioned machine: refuses unpushed unit work (checked on
|
|
@@ -291,7 +298,7 @@ Pools (a role, variants and a count; the server names the agents and places them
|
|
|
291
298
|
b9s-admin project repo <project> <git url | none> what machines clone for the project's pool sessions
|
|
292
299
|
b9s-admin project checkout <project> --exclude <path,path | none> paths new worktrees leave out (sparse checkout), e.g. logs/
|
|
293
300
|
b9s-admin pool set <project>/<name> --role <role> --variant [tag=]harness:model[:effort][*weight][@anthropic|deepseek] [--variant ...]
|
|
294
|
-
--count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min]
|
|
301
|
+
--count <n> --sandbox <mode> [--needs label,label] [--min-ram GB] [--turn-timeout min] [--turns-per-hour 1..20]
|
|
295
302
|
slots are agents named <name>-<tag>-<n>; fewer retires the extra ones
|
|
296
303
|
b9s-admin pool list [project] | show <project>/<name> | remove <project>/<name>
|
|
297
304
|
b9s-admin delete-account --confirm "delete everything"
|
|
@@ -0,0 +1,69 @@
|
|
|
1
|
+
export const DEFAULT_TURNS_PER_HOUR = 20;
|
|
2
|
+
export const MAX_UNPRODUCTIVE_TURNS = 3;
|
|
3
|
+
const HOUR_MS = 60 * 60_000;
|
|
4
|
+
const OUTPUT_TAIL_LIMIT = 800;
|
|
5
|
+
export function emptyTurnGuard() {
|
|
6
|
+
return { turns: [], consecutive_unproductive: 0, fault: null };
|
|
7
|
+
}
|
|
8
|
+
function recentTurns(state, now) {
|
|
9
|
+
return state.turns.filter((turn) => turn.at > now - HOUR_MS);
|
|
10
|
+
}
|
|
11
|
+
function estimatedTokens(turns) {
|
|
12
|
+
return turns.reduce((sum, turn) => sum + Math.max(0, Math.floor(turn.estimated_tokens)), 0);
|
|
13
|
+
}
|
|
14
|
+
function faultFor(state, reason, now, turns, output) {
|
|
15
|
+
return {
|
|
16
|
+
at: now,
|
|
17
|
+
reason,
|
|
18
|
+
consecutive_unproductive: state.consecutive_unproductive,
|
|
19
|
+
turns_last_hour: turns.length,
|
|
20
|
+
estimated_tokens: estimatedTokens(turns),
|
|
21
|
+
likely_cause: output.trim() || "no BenignSwarm call reached the server; possible network or sandbox restriction",
|
|
22
|
+
output_tail: output.slice(-OUTPUT_TAIL_LIMIT),
|
|
23
|
+
};
|
|
24
|
+
}
|
|
25
|
+
export function beginGuardedTurn(state, maxTurnsPerHour, now, activitySeqBefore) {
|
|
26
|
+
const current = state ?? emptyTurnGuard();
|
|
27
|
+
const turns = recentTurns(current, now);
|
|
28
|
+
const next = { ...current, turns };
|
|
29
|
+
if (current.fault)
|
|
30
|
+
return { state: current, start: false };
|
|
31
|
+
if (turns.length >= maxTurnsPerHour) {
|
|
32
|
+
const lastOutput = [...turns].reverse().find((turn) => turn.output_tail)?.output_tail ?? "";
|
|
33
|
+
next.fault = faultFor(next, "hourly_limit", now, turns, lastOutput || `the configured ceiling of ${maxTurnsPerHour} turns per hour was reached`);
|
|
34
|
+
return { state: next, start: false };
|
|
35
|
+
}
|
|
36
|
+
next.turns = [...turns, { at: now, productive: null, estimated_tokens: 0, ...(activitySeqBefore === undefined ? {} : { activity_seq_before: activitySeqBefore }) }];
|
|
37
|
+
return { state: next, start: true };
|
|
38
|
+
}
|
|
39
|
+
export function completeGuardedTurn(state, now, productive, output, tokens) {
|
|
40
|
+
if (state.fault)
|
|
41
|
+
return state;
|
|
42
|
+
const turns = state.turns;
|
|
43
|
+
let index = -1;
|
|
44
|
+
for (let i = turns.length - 1; i >= 0; i--) {
|
|
45
|
+
if (turns[i].productive === null) {
|
|
46
|
+
index = i;
|
|
47
|
+
break;
|
|
48
|
+
}
|
|
49
|
+
}
|
|
50
|
+
if (index < 0)
|
|
51
|
+
throw new Error("cannot complete a turn that was not started");
|
|
52
|
+
const completed = turns.map((turn, i) => i === index
|
|
53
|
+
? { ...turn, productive, estimated_tokens: tokens ?? Math.ceil(output.length / 4), output_tail: output.slice(-OUTPUT_TAIL_LIMIT) }
|
|
54
|
+
: turn);
|
|
55
|
+
const currentHour = recentTurns({ ...state, turns: completed }, now);
|
|
56
|
+
const consecutive = productive ? 0 : state.consecutive_unproductive + 1;
|
|
57
|
+
const next = { turns: currentHour, consecutive_unproductive: consecutive, fault: null };
|
|
58
|
+
if (!productive && consecutive >= MAX_UNPRODUCTIVE_TURNS) {
|
|
59
|
+
const fault = faultFor(next, "unproductive", now, currentHour, output);
|
|
60
|
+
fault.estimated_tokens = estimatedTokens(completed.slice(-MAX_UNPRODUCTIVE_TURNS));
|
|
61
|
+
next.fault = fault;
|
|
62
|
+
}
|
|
63
|
+
return next;
|
|
64
|
+
}
|
|
65
|
+
/** Resume clears the latched fault and unproductive streak, but keeps hourly starts. */
|
|
66
|
+
export function resumeTurnGuard(state) {
|
|
67
|
+
const current = state ?? emptyTurnGuard();
|
|
68
|
+
return { ...current, consecutive_unproductive: 0, fault: null };
|
|
69
|
+
}
|
package/dist/version.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
export const CLI_VERSION = "0.12.
|
|
1
|
+
export const CLI_VERSION = "0.12.90";
|