benignswarm 0.12.105 → 0.12.107
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/capabilities.js +70 -15
- package/dist/client.js +7 -2
- package/dist/command-runner.js +1 -1
- package/dist/commands/claude.js +26 -0
- package/dist/commands/codex-start.js +4 -2
- package/dist/commands/hook.js +52 -4
- package/dist/commands/image-admin.js +16 -3
- package/dist/commands/install.js +9 -0
- package/dist/commands/machine-admin.js +14 -2
- package/dist/commands/machine.js +335 -29
- package/dist/commands/measures.js +1 -1
- package/dist/commands/watch.js +25 -6
- package/dist/commands/wu.js +58 -16
- package/dist/container.js +565 -33
- package/dist/errors.js +1 -0
- package/dist/help.js +13 -6
- package/dist/index.js +3 -1
- package/dist/machine-telemetry.js +36 -3
- package/dist/output.js +9 -7
- package/dist/sessions.js +27 -3
- package/dist/turn-guard.js +30 -1
- package/dist/version.js +1 -1
- package/package.json +1 -1
package/dist/args.js
CHANGED
|
@@ -32,7 +32,7 @@ export const STRING_FLAGS = [
|
|
|
32
32
|
"root", "signing-key", "catalog", "context", "context-action", "context-checkpoint-ref", "context-old-thread", "context-new-thread", "source-commit", "component", "normalized-key",
|
|
33
33
|
"drain-timeout", "on-running-turn", "extend", "ssh-config", "poll-ms",
|
|
34
34
|
"stage", "machines", "resolved-retention-days", "wont-fix-retention-days", "alert-cooldown-minutes", "alerts", "confirm-force",
|
|
35
|
-
"machine-session-id", "detail", "worktree",
|
|
35
|
+
"machine-session-id", "pool-sessions", "registry", "detail", "worktree",
|
|
36
36
|
"purpose", "storage-mode", "hosts", "arn", "version-id",
|
|
37
37
|
"mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
|
|
38
38
|
];
|
package/dist/capabilities.js
CHANGED
|
@@ -3,6 +3,7 @@ import { mkdtempSync, rmSync } from "node:fs";
|
|
|
3
3
|
import { homedir, tmpdir } from "node:os";
|
|
4
4
|
import { join } from "node:path";
|
|
5
5
|
import { performance } from "node:perf_hooks";
|
|
6
|
+
import { assertSafeMountPath, isolatedSubprocessEnv } from "./container.js";
|
|
6
7
|
export const DEFAULT_CAPABILITY_TIMEOUT_MS = 60_000;
|
|
7
8
|
const MAX_OUTPUT_BYTES = 64 * 1024;
|
|
8
9
|
function appendLimited(chunks, capturedBytes, chunk) {
|
|
@@ -11,7 +12,7 @@ function appendLimited(chunks, capturedBytes, chunk) {
|
|
|
11
12
|
chunks.push(chunk.subarray(0, remaining));
|
|
12
13
|
return { capturedBytes: capturedBytes + Math.min(chunk.length, Math.max(remaining, 0)), exceeded: chunk.length > remaining };
|
|
13
14
|
}
|
|
14
|
-
function
|
|
15
|
+
function runProbeCommand(cmd, args, cwd, timeoutMs, env) {
|
|
15
16
|
const startedAt = performance.now();
|
|
16
17
|
const stdout = [];
|
|
17
18
|
const stderr = [];
|
|
@@ -21,8 +22,9 @@ function runProbe(command, cwd, timeoutMs) {
|
|
|
21
22
|
let spawnError = null;
|
|
22
23
|
let killError = null;
|
|
23
24
|
let timedOut = false;
|
|
24
|
-
const child = spawn(
|
|
25
|
+
const child = spawn(cmd, args, {
|
|
25
26
|
cwd,
|
|
27
|
+
...(env ? { env } : {}),
|
|
26
28
|
detached: process.platform !== "win32",
|
|
27
29
|
stdio: ["ignore", "pipe", "pipe"],
|
|
28
30
|
});
|
|
@@ -72,25 +74,78 @@ function runProbe(command, cwd, timeoutMs) {
|
|
|
72
74
|
});
|
|
73
75
|
}
|
|
74
76
|
/** Run every declaration and preserve failures as results, so dispatch can explain a missing tool. */
|
|
75
|
-
export async function probeCapabilities(definitions, projectDir) {
|
|
77
|
+
export async function probeCapabilities(definitions, projectDir, opts) {
|
|
76
78
|
const results = [];
|
|
77
79
|
for (const definition of definitions) {
|
|
78
80
|
let cwd = homedir();
|
|
79
81
|
let temporary = null;
|
|
80
82
|
try {
|
|
81
|
-
if (definition.scope === "worktree") {
|
|
82
|
-
temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
|
|
83
|
-
const path = join(temporary, "worktree");
|
|
84
|
-
const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: projectDir, encoding: "utf8", timeout: 120_000 });
|
|
85
|
-
if (added.status !== 0)
|
|
86
|
-
throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
|
|
87
|
-
const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
|
|
88
|
-
if (full.status !== 0)
|
|
89
|
-
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
90
|
-
cwd = path;
|
|
91
|
-
}
|
|
92
83
|
const timeoutMs = definition.timeout_ms ?? DEFAULT_CAPABILITY_TIMEOUT_MS;
|
|
93
|
-
|
|
84
|
+
let result;
|
|
85
|
+
if (definition.scope === "image") {
|
|
86
|
+
if (!opts?.container?.imageDigest) {
|
|
87
|
+
throw new Error("image capability probe requires an active pinned container image");
|
|
88
|
+
}
|
|
89
|
+
const ctx = opts.container;
|
|
90
|
+
const trimmedDir = typeof projectDir === "string" ? projectDir.trim() : "";
|
|
91
|
+
const safeWorktree = trimmedDir
|
|
92
|
+
? assertSafeMountPath(trimmedDir, "worktree", ctx.hostHome ? { hostHome: ctx.hostHome } : {})
|
|
93
|
+
: null;
|
|
94
|
+
const containerArgs = [
|
|
95
|
+
"run",
|
|
96
|
+
"--rm",
|
|
97
|
+
"--security-opt",
|
|
98
|
+
"no-new-privileges",
|
|
99
|
+
"--add-host",
|
|
100
|
+
"169.254.169.254:127.0.0.1",
|
|
101
|
+
"--add-host",
|
|
102
|
+
"metadata.google.internal:127.0.0.1",
|
|
103
|
+
...(ctx.arch ? ["--platform", ctx.arch] : []),
|
|
104
|
+
...(safeWorktree ? ["-v", `${safeWorktree}:/workspace:ro`, "-w", "/workspace"] : []),
|
|
105
|
+
ctx.imageDigest,
|
|
106
|
+
"/bin/sh",
|
|
107
|
+
"-lc",
|
|
108
|
+
definition.probe,
|
|
109
|
+
];
|
|
110
|
+
const probeHostCwd = safeWorktree ?? tmpdir();
|
|
111
|
+
if (ctx.runner) {
|
|
112
|
+
const startedAt = performance.now();
|
|
113
|
+
const res = ctx.runner(ctx.runtime, containerArgs, {
|
|
114
|
+
cwd: probeHostCwd,
|
|
115
|
+
timeout: timeoutMs,
|
|
116
|
+
env: isolatedSubprocessEnv(process.env),
|
|
117
|
+
});
|
|
118
|
+
result = {
|
|
119
|
+
status: res.status,
|
|
120
|
+
stdout: res.stdout ?? "",
|
|
121
|
+
stderr: res.stderr ?? "",
|
|
122
|
+
error: res.error ?? null,
|
|
123
|
+
killError: null,
|
|
124
|
+
timedOut: false,
|
|
125
|
+
elapsedMs: Math.round(performance.now() - startedAt),
|
|
126
|
+
};
|
|
127
|
+
}
|
|
128
|
+
else {
|
|
129
|
+
result = await runProbeCommand(ctx.runtime, containerArgs, probeHostCwd, timeoutMs, isolatedSubprocessEnv(process.env));
|
|
130
|
+
}
|
|
131
|
+
}
|
|
132
|
+
else {
|
|
133
|
+
if (definition.scope === "worktree") {
|
|
134
|
+
const wtSource = typeof projectDir === "string" ? projectDir.trim() : "";
|
|
135
|
+
if (!wtSource)
|
|
136
|
+
throw new Error("worktree capability probe requires a checked-out project directory");
|
|
137
|
+
temporary = mkdtempSync(join(tmpdir(), "bschat-capability-"));
|
|
138
|
+
const path = join(temporary, "worktree");
|
|
139
|
+
const added = spawnSync("git", ["worktree", "add", "--quiet", "--detach", path, "HEAD"], { cwd: wtSource, encoding: "utf8", timeout: 120_000 });
|
|
140
|
+
if (added.status !== 0)
|
|
141
|
+
throw new Error((added.stderr || added.stdout || "git worktree add failed").trim().split(/\r?\n/, 1)[0]);
|
|
142
|
+
const full = spawnSync("git", ["-C", path, "sparse-checkout", "disable"], { encoding: "utf8", timeout: 30_000 });
|
|
143
|
+
if (full.status !== 0)
|
|
144
|
+
throw new Error(full.error?.message ?? (full.stderr || full.stdout || "git sparse-checkout disable failed").trim());
|
|
145
|
+
cwd = path;
|
|
146
|
+
}
|
|
147
|
+
result = await runProbeCommand("/bin/sh", ["-lc", definition.probe], cwd, timeoutMs);
|
|
148
|
+
}
|
|
94
149
|
const output = `${result.stdout}${result.stderr}`.trim().split(/\r?\n/, 1)[0] ?? "";
|
|
95
150
|
const ok = result.status === 0 && !result.error && !result.timedOut;
|
|
96
151
|
const error = result.timedOut
|
package/dist/client.js
CHANGED
|
@@ -115,8 +115,13 @@ function expectedTextReceiptFields(method, path, body, response) {
|
|
|
115
115
|
required.push("replace.new");
|
|
116
116
|
return required;
|
|
117
117
|
}
|
|
118
|
-
if (action === "wait")
|
|
119
|
-
|
|
118
|
+
if (action === "wait") {
|
|
119
|
+
// A unit wait persists its note only. Review waits also persist a supplied partial verdict.
|
|
120
|
+
const required = strings("note");
|
|
121
|
+
if (response?.unit?.review_wait && typeof fields.partial === "string")
|
|
122
|
+
required.push("partial");
|
|
123
|
+
return required;
|
|
124
|
+
}
|
|
120
125
|
if (["approve", "changes", "proceed"].includes(action))
|
|
121
126
|
return strings("note", "unmet");
|
|
122
127
|
if (["park", "requeue", "decline", "classify", "tags", "reopen", "supersede", "done", "abandon", "merge", "evidence/replace", "restore", "note", "hold", "hold/release", "question/escalate"].includes(action))
|
package/dist/command-runner.js
CHANGED
|
@@ -8,7 +8,7 @@ export async function runCommandSafely(run, out) {
|
|
|
8
8
|
catch (error) {
|
|
9
9
|
if (error instanceof WrittenReceiptMismatchError) {
|
|
10
10
|
const detail = error.message.replace(/^write succeeded; receipt mismatch:\s*/, "");
|
|
11
|
-
printWrittenReceiptMismatch(out, error.response, detail);
|
|
11
|
+
printWrittenReceiptMismatch(out, error.response, detail, error.actionResult);
|
|
12
12
|
return WRITTEN_RECEIPT_MISMATCH_EXIT_CODE;
|
|
13
13
|
}
|
|
14
14
|
throw error;
|
|
@@ -0,0 +1,26 @@
|
|
|
1
|
+
import { str } from "../args.js";
|
|
2
|
+
import { agentRef, loadAgent, resolveAgentName } from "../config.js";
|
|
3
|
+
import { CliError } from "../errors.js";
|
|
4
|
+
import { boundSessions, bindSession } from "../sessions.js";
|
|
5
|
+
/**
|
|
6
|
+
* b9s claude bind <session-id> [--as <agent>] this Claude Code session is you: its hook delivers to you (replaces your earlier session)
|
|
7
|
+
* b9s claude sessions the Claude Code sessions bound on this machine
|
|
8
|
+
*/
|
|
9
|
+
export async function claude(p, out) {
|
|
10
|
+
const sub = p.positionals[1];
|
|
11
|
+
if (sub === "bind") {
|
|
12
|
+
const id = p.positionals[2];
|
|
13
|
+
if (!id)
|
|
14
|
+
throw new CliError("usage", "claude bind <session-id> [--as <agent>] (the session id is in the SessionStart notice a session that is not bound prints, and in the hook payload's session_id)");
|
|
15
|
+
const ref = agentRef(loadAgent(resolveAgentName(str(p.flags, "as"))));
|
|
16
|
+
bindSession("claude-code", id, ref);
|
|
17
|
+
out.print(`Claude Code session ${id} is ${ref}: its hook now delivers your mentions and assignments there, and no other session of yours gets them.`, { session: id, agent: ref });
|
|
18
|
+
return;
|
|
19
|
+
}
|
|
20
|
+
if (sub === "sessions") {
|
|
21
|
+
const bound = boundSessions("claude-code");
|
|
22
|
+
out.print(bound.length ? bound.map((b) => `${b.id} -> ${b.agent}${b.auto ? " (bound automatically)" : ""}`).join("\n") : "No Claude Code session is bound on this machine.", { sessions: bound });
|
|
23
|
+
return;
|
|
24
|
+
}
|
|
25
|
+
throw new CliError("usage", "claude bind <session-id> [--as <agent>] | claude sessions");
|
|
26
|
+
}
|
|
@@ -285,12 +285,14 @@ export async function harnessStart(p, out, harness) {
|
|
|
285
285
|
}
|
|
286
286
|
if (!session)
|
|
287
287
|
throw new CliError("harness_failed", "the harness did not provide a session id");
|
|
288
|
-
// 3. Bind it, so the hooks in that session deliver to this agent and nobody else. Claude Code
|
|
289
|
-
//
|
|
288
|
+
// 3. Bind it, so the hooks in that session deliver to this agent and nobody else. The Claude Code hook
|
|
289
|
+
// takes the agent from BSCHAT_AGENT (the watcher sets it for every turn) and the session id from the map.
|
|
290
290
|
if (harness === "codex")
|
|
291
291
|
bindSession("codex", session, ref);
|
|
292
292
|
if (harness === "antigravity")
|
|
293
293
|
bindSession("antigravity", session, ref);
|
|
294
|
+
if (harness === "claude-code")
|
|
295
|
+
bindSession("claude-code", session, ref);
|
|
294
296
|
const transcript = harness === "dsh" ? dshTurnLog(ref) : harness === "antigravity" ? antigravityLog(ref) : harness === "claude-code" ? claudeTranscript(session) ?? firstTurnLog ?? "" : codexRollout(session) ?? firstTurnLog ?? "";
|
|
295
297
|
writeState(ref, { ...readState(ref), harness_session: { harness, transcript, session_id: session, at: Date.now(), ...(model ? { model } : {}), ...(harness === "claude-code" ? { provider } : {}), ...(initialPid ? { initial_pid: initialPid } : {}) } });
|
|
296
298
|
// A session adopted here may end in a usage-limit error from the machine it came from, written in
|
package/dist/commands/hook.js
CHANGED
|
@@ -1,12 +1,13 @@
|
|
|
1
1
|
import { readFileSync } from "node:fs";
|
|
2
2
|
import { str } from "../args.js";
|
|
3
3
|
import { Client } from "../client.js";
|
|
4
|
-
import { loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
4
|
+
import { ACCOUNT_SCOPE, loadAgent, resolveAgentName, resolveModel } from "../config.js";
|
|
5
|
+
import { findIdentityFile, readIdentityFile } from "../harness.js";
|
|
5
6
|
import { heartbeatNow } from "../heartbeat.js";
|
|
6
7
|
import { fmtMessage } from "../output.js";
|
|
7
8
|
import { readState, writeState } from "../state.js";
|
|
8
9
|
import { goalFromClaudeTranscript, modelFromClaudeTranscript } from "../model.js";
|
|
9
|
-
import { conversationAgent, sessionAgent, syncFromWatchers } from "../sessions.js";
|
|
10
|
+
import { bindSession, conversationAgent, sessionAgent, sessionsOf, syncFromWatchers } from "../sessions.js";
|
|
10
11
|
import { fetchRecoveryBrief, formatOutcomeMeasures, formatRecoveryBrief, outcomeMeasureSnapshot, recoveryBriefUnavailableText } from "../brief.js";
|
|
11
12
|
import { changedNotices, commandNoticeWarning, normalizeShellCommand } from "../notices.js";
|
|
12
13
|
const HEARTBEAT_MS = 60_000;
|
|
@@ -387,7 +388,36 @@ export async function reportDelivery(name, text, kinds, source = "hook") {
|
|
|
387
388
|
* context, and nothing when there is nothing new. Always exits 0: a hook that fails must never
|
|
388
389
|
* break the agent's session. Problems go to stderr.
|
|
389
390
|
*/
|
|
390
|
-
|
|
391
|
+
/**
|
|
392
|
+
* Whether this Claude Code session is the agent's own. The hook's identity comes from
|
|
393
|
+
* BSCHAT_AGENT or the repo's identity file, which every session in the checkout shares, so the
|
|
394
|
+
* session id decides: only the session bound to the agent (b9s claude bind, b9s start) gets its
|
|
395
|
+
* messages and moves its cursors. The first SessionStart while the identity file names this agent
|
|
396
|
+
* and no session is bound is bound automatically, so a single-session setup needs no step.
|
|
397
|
+
*/
|
|
398
|
+
export function claudeSessionBound(ref, sid, cwd, allowAutoBind = false) {
|
|
399
|
+
if (!sid)
|
|
400
|
+
return false;
|
|
401
|
+
const owner = sessionAgent("claude-code", sid);
|
|
402
|
+
if (owner === ref)
|
|
403
|
+
return true;
|
|
404
|
+
// Never let an identity-file auto-bind overwrite another agent's explicit/session binding.
|
|
405
|
+
if (owner !== null)
|
|
406
|
+
return false;
|
|
407
|
+
if (!allowAutoBind)
|
|
408
|
+
return false;
|
|
409
|
+
if (sessionsOf("claude-code", ref).length > 0)
|
|
410
|
+
return false;
|
|
411
|
+
const file = findIdentityFile(cwd);
|
|
412
|
+
if (!file)
|
|
413
|
+
return false;
|
|
414
|
+
const entry = readIdentityFile(file).agents["claude-code"];
|
|
415
|
+
if (!entry || `${entry.project ?? ACCOUNT_SCOPE}/${entry.name}` !== ref)
|
|
416
|
+
return false;
|
|
417
|
+
bindSession("claude-code", sid, ref, { auto: true });
|
|
418
|
+
return true;
|
|
419
|
+
}
|
|
420
|
+
export async function hook(p, payload) {
|
|
391
421
|
const harness = p.positionals[1] ?? "plain";
|
|
392
422
|
if (harness === "antigravity")
|
|
393
423
|
return antigravityHook(p);
|
|
@@ -401,8 +431,26 @@ export async function hook(p) {
|
|
|
401
431
|
catch {
|
|
402
432
|
return; // not configured here, or ambiguous: silent by design; the agent's own commands will say so
|
|
403
433
|
}
|
|
434
|
+
const input = payload === undefined ? readStdinJson() : payload;
|
|
435
|
+
if (harness === "claude-code") {
|
|
436
|
+
const sid = typeof input?.session_id === "string" ? input.session_id : null;
|
|
437
|
+
let bound = false;
|
|
438
|
+
try {
|
|
439
|
+
bound = claudeSessionBound(name, sid, typeof input?.cwd === "string" ? input.cwd : process.cwd(), event === "SessionStart");
|
|
440
|
+
}
|
|
441
|
+
catch (e) {
|
|
442
|
+
process.stderr.write(`b9s: could not check this session's binding: ${e.message}\n`);
|
|
443
|
+
}
|
|
444
|
+
if (!bound) {
|
|
445
|
+
// Nothing of the agent's goes to a session that is not its own, and no cursor or delivery state moves.
|
|
446
|
+
if (event === "SessionStart") {
|
|
447
|
+
const how = sid ? `b9s claude bind ${sid} --as ${name}` : "b9s claude bind <session id> --as " + name;
|
|
448
|
+
process.stdout.write(JSON.stringify({ hookSpecificOutput: { hookEventName: event, additionalContext: `[b9s] This Claude Code session is not bound to ${name}, so none of that agent's messages are delivered here. Only if this session is ${name}, bind it: ${how}` } }) + "\n");
|
|
449
|
+
}
|
|
450
|
+
return;
|
|
451
|
+
}
|
|
452
|
+
}
|
|
404
453
|
// Model observation: hook input (SessionStart `model`, PostModelSwitch `to_model`) or the transcript tail.
|
|
405
|
-
const input = readStdinJson();
|
|
406
454
|
if (input) {
|
|
407
455
|
const state = readState(name);
|
|
408
456
|
const observed = (typeof input.to_model === "string" && input.to_model) || (typeof input.model === "string" && input.model) || (typeof input.transcript_path === "string" ? modelFromClaudeTranscript(input.transcript_path) : null);
|
|
@@ -20,23 +20,36 @@ export async function projectImageAdmin(rest, p, out) {
|
|
|
20
20
|
}
|
|
21
21
|
const c = Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
|
|
22
22
|
if (!sub || !project) {
|
|
23
|
-
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
|
|
23
|
+
throw new CliError("usage", "project image <validate --file f | config <p> [--path f] [--arch linux/amd64|linux/arm64] [--cache name...] [--pool-sessions on|off] [--registry ns] | show <p> | build <p> --commit <sha> --file <devcontainer.json> [--dockerfile f] [--arch a] | activate <p> <sha256:...> | rollback <p> (<sha256:...> | clear)>");
|
|
24
24
|
}
|
|
25
25
|
switch (sub) {
|
|
26
26
|
case "config": {
|
|
27
27
|
const rawCache = str(p.flags, "caches") ?? str(p.flags, "cache");
|
|
28
28
|
const caches = rawCache ? rawCache.split(",").map((s) => s.trim()).filter(Boolean) : [];
|
|
29
|
+
const rawPoolSessions = str(p.flags, "pool-sessions");
|
|
30
|
+
let poolSessionsEnabled;
|
|
31
|
+
if (rawPoolSessions !== undefined) {
|
|
32
|
+
if (rawPoolSessions === "on" || rawPoolSessions === "true")
|
|
33
|
+
poolSessionsEnabled = true;
|
|
34
|
+
else if (rawPoolSessions === "off" || rawPoolSessions === "false")
|
|
35
|
+
poolSessionsEnabled = false;
|
|
36
|
+
else
|
|
37
|
+
throw new CliError("usage", "--pool-sessions must be on|off (or true|false)");
|
|
38
|
+
}
|
|
39
|
+
const registry = str(p.flags, "registry");
|
|
29
40
|
const r = await c.call("PUT", `/projects/${encodeURIComponent(project)}/image-config`, {
|
|
30
41
|
...(str(p.flags, "path") ? { devcontainer_path: str(p.flags, "path") } : {}),
|
|
31
42
|
...(str(p.flags, "arch") ? { target_arch: str(p.flags, "arch") } : {}),
|
|
32
43
|
...(caches.length ? { allowed_caches: caches } : {}),
|
|
44
|
+
...(poolSessionsEnabled !== undefined ? { pool_sessions_enabled: poolSessionsEnabled } : {}),
|
|
45
|
+
...(registry !== undefined ? { registry_namespace: registry } : {}),
|
|
33
46
|
});
|
|
34
|
-
out.print(`Project ${project} image namespace ${r.image.registry_namespace} (${r.image.target_arch}, ${r.image.devcontainer_path})`, r);
|
|
47
|
+
out.print(`Project ${project} image namespace ${r.image.registry_namespace} (${r.image.target_arch}, ${r.image.devcontainer_path}, pool sessions ${r.image.pool_sessions_enabled ? "enabled" : "disabled"})`, r);
|
|
35
48
|
return;
|
|
36
49
|
}
|
|
37
50
|
case "show": {
|
|
38
51
|
const r = await c.call("GET", `/projects/${encodeURIComponent(project)}/image`);
|
|
39
|
-
out.print(`Project ${project} active digest: ${r.image.active_digest ?? "(none)"}${r.image.rollback_digest ? ` (rollback pinned to ${r.image.rollback_digest})` : ""}`, r);
|
|
52
|
+
out.print(`Project ${project} active digest: ${r.image.active_digest ?? "(none)"}${r.image.rollback_digest ? ` (rollback pinned to ${r.image.rollback_digest})` : ""}; pool sessions ${r.image.pool_sessions_enabled ? "enabled" : "disabled"}`, r);
|
|
40
53
|
return;
|
|
41
54
|
}
|
|
42
55
|
case "build": {
|
package/dist/commands/install.js
CHANGED
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
import { spawnSync } from "node:child_process";
|
|
2
|
+
import { boundSessions } from "../sessions.js";
|
|
2
3
|
import { accessSync, constants, existsSync, readFileSync, readdirSync, realpathSync, statfsSync } from "node:fs";
|
|
3
4
|
import { basename, delimiter, join } from "node:path";
|
|
4
5
|
import { homedir, platform } from "node:os";
|
|
@@ -127,6 +128,13 @@ function doctorEnvironmentChecks(pathValue, writableRoots) {
|
|
|
127
128
|
* PATH, npx caches, this repo's hook and instructions, and each watcher (plist versus
|
|
128
129
|
* what launchd is actually running). Read-only; prints the fix for each problem.
|
|
129
130
|
*/
|
|
131
|
+
/** Doctor lines for the Claude Code sessions the hook delivers to; any other session in a checkout gets nothing. */
|
|
132
|
+
export function claudeSessionChecks() {
|
|
133
|
+
const bound = boundSessions("claude-code");
|
|
134
|
+
if (!bound.length)
|
|
135
|
+
return [{ ok: true, what: "no Claude Code session is bound: the first session of a checkout whose identity file names its agent binds itself" }];
|
|
136
|
+
return bound.map((b) => ({ ok: true, what: `Claude Code session ${b.id} is bound to ${b.agent}${b.auto ? " (bound automatically)" : ""}` }));
|
|
137
|
+
}
|
|
130
138
|
export async function doctor(_p, out) {
|
|
131
139
|
const checks = [];
|
|
132
140
|
const rec = readInstall();
|
|
@@ -192,6 +200,7 @@ export async function doctor(_p, out) {
|
|
|
192
200
|
checks.push({ ok: good, what: `Claude Code hook in ${sp}: ${c}`, fix: good ? undefined : "b9s setup --as <your agent> (rewrites the hook to the recorded install)" });
|
|
193
201
|
}
|
|
194
202
|
}
|
|
203
|
+
checks.push(...claudeSessionChecks());
|
|
195
204
|
for (const f of ["AGENTS.md", "GEMINI.md", join(".agents", "rules", "bschat.md")]) {
|
|
196
205
|
const fp = join(root, f);
|
|
197
206
|
if (existsSync(fp) && readFileSync(fp, "utf8").includes("npx -y benignswarm"))
|
|
@@ -194,6 +194,7 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
194
194
|
`${m.name}: last report ${m.last_report_at ?? "never"}; labels ${(m.labels ?? []).join(", ") || "(none)"}; slots ${m.slots ?? "auto"}; writable ${(m.writable ?? []).join(", ") || "-"}; workdir ${rep.workdir ?? m.workdir ?? "~/bschat"}${rep.workdir_free_bytes ? ` (${Math.round(rep.workdir_free_bytes / 1e9)} GB free)` : ""}; cache budget ${m.cache_budget_gb ?? 40} GB (floor ${m.cache_floor_pct ?? 15}%)`,
|
|
195
195
|
rep.os ? ` ${rep.os}/${rep.arch} ${rep.hostname} as ${rep.user}; ${rep.cpus ?? "?"} CPUs, ${rep.mem_total_bytes ? `${Math.round(rep.mem_total_bytes / 1024 ** 3)} GB RAM` : "? RAM"}; b9s ${rep.bschat?.version}; codex ${rep.codex ? `${rep.codex.version}, ${rep.codex.logged_in ? "logged in" : "NOT logged in"}, sandbox ${rep.codex.sandbox ? (rep.codex.sandbox.ok ? "ok" : `FAILS (${rep.codex.sandbox.error})`) : "?"}` : "missing"}; hooks ${rep.managed_hooks ? "managed by policy" : "user-level"}; linger ${rep.linger ?? "n/a"}; disk free ${rep.disk_free_bytes ? `${Math.round(rep.disk_free_bytes / 1e9)} GB` : "?"}` : " (no report yet: is its daemon running?)",
|
|
196
196
|
rep.os ? ` Antigravity: ${rep.antigravity ? `${rep.antigravity.version ?? "agy"}, ${rep.antigravity.available ? "available" : "unavailable"}, ${rep.antigravity.logged_in ? "logged in" : "not logged in"}, sandbox ${rep.antigravity.sandbox ? (rep.antigravity.sandbox.ok ? "ok" : `FAILS (${rep.antigravity.sandbox.error})`) : "not checked"}` : "not installed"}` : null,
|
|
197
|
+
rep.container_runtime ? ` Container runtime: ${rep.container_runtime.runtime ?? "none"} (${rep.container_runtime.rootless ? "rootless" : "daemon"}, ${rep.container_runtime.usable_without_root === false ? "NO non-root access" : "non-root ok"}, arch ${(rep.container_runtime.architectures ?? []).join(",") || rep.arch || "?"}${rep.on_ec2 ? `, EC2 container IMDS ${rep.container_imds_blocked ? "blocked" : "NOT blocked"}` : ""})` : null,
|
|
197
198
|
m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
|
|
198
199
|
];
|
|
199
200
|
const cacheLines = [];
|
|
@@ -225,11 +226,11 @@ export async function machineAdmin(action, rest, p, out) {
|
|
|
225
226
|
}
|
|
226
227
|
}
|
|
227
228
|
const capabilityLines = machineCapabilityLines(m.capabilities ?? []);
|
|
228
|
-
const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
|
|
229
|
+
const rows = m.sessions.map((s) => ({ agent: s.agent, pool: s.pool ?? "-", desired: s.desired, state: s.reported?.state ?? "-", turns_per_hour: s.turns_per_hour ?? 60, coalesce_s: s.turn_coalesce_seconds ?? 180, thread: s.thread ?? "-", harness: s.harness, provider: s.provider ?? "anthropic", sandbox: s.sandbox, image: s.image_digest ? `${s.container_runtime ?? "container"}@${String(s.image_digest).slice(0, 19)}` : "host", model: s.model ?? "-", dir: s.dir || s.reported?.dir || "(auto)", error: s.reported?.error ?? s.reported?.detail ?? "", last_turn: (s.reported?.last_turn ?? "").replace(/^\S+ b9s watch\[[^\]]+\]: /, "") }));
|
|
229
230
|
const providers = rep.claude_code?.providers ?? {};
|
|
230
231
|
const providerLines = Object.entries(providers).map(([provider, check]) => ` Claude Code ${provider}: ${check.logged_in ? "verified" : `NOT verified (${check.reason ?? "unknown reason"})`}`);
|
|
231
232
|
const output = liveReport ? { ...r, machine: { ...m, report: rep } } : r;
|
|
232
|
-
return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), output);
|
|
233
|
+
return out.print([...head, ...machineMacLines(rep.macos), ...machineGitLines(rep.git), ...cacheLines, ...capabilityLines, ...providerLines, rows.length ? table(rows, ["agent", "pool", "desired", "state", "turns_per_hour", "coalesce_s", "thread", "harness", "provider", "sandbox", "image", "model", "dir", "error", "last_turn"]) : " no sessions"].filter((line) => line !== null).join("\n"), output);
|
|
233
234
|
}
|
|
234
235
|
if (action === "maintenance") {
|
|
235
236
|
// A window on the machine: no new turns from 15 min before, its agents away until it ends.
|
|
@@ -631,6 +632,17 @@ export async function poolAdmin(action, rest, p, out, argv) {
|
|
|
631
632
|
throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
|
|
632
633
|
}
|
|
633
634
|
const c = adminClient(p);
|
|
635
|
+
if (action === "slot") {
|
|
636
|
+
const [operation, target, ...extra] = rest;
|
|
637
|
+
const parts = (target ?? "").split("/");
|
|
638
|
+
if (operation !== "stop" || parts.length !== 3 || parts.some((part) => !part) || extra.length) {
|
|
639
|
+
throw new CliError("usage", "pool slot stop <project>/<pool>/<slot> [--reason text]");
|
|
640
|
+
}
|
|
641
|
+
const [project, name, slot] = parts.map(encodeURIComponent);
|
|
642
|
+
const reason = str(p.flags, "reason");
|
|
643
|
+
const r = await c.call("POST", `/projects/${project}/pools/${name}/slots/${slot}/stop`, reason === undefined ? {} : { reason });
|
|
644
|
+
return out.print(`Suspended ${target}; its machine will stop the session.`, r);
|
|
645
|
+
}
|
|
634
646
|
const statusLines = (pool) => [
|
|
635
647
|
`${pool.project}/${pool.name}: ${pool.count} × role ${pool.role ?? "(none)"}, ${pool.sandbox}; busy cap ${pool.turns_per_hour ?? 60}/hour, unproductive fault ${pool.unproductive_per_hour ?? 6}/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` : ""}`,
|
|
636
648
|
...(pool.status?.placed ?? []).map((x) => ` ${x.agent.padEnd(32)} on ${x.machine}`),
|