benignswarm 0.12.97 → 0.12.99

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.
File without changes
package/dist/args.js CHANGED
@@ -29,9 +29,12 @@ export const STRING_FLAGS = [
29
29
  "expectations", "reworks", "cause", "lesson", "disputes", "annotation", "send-back-event", "confirm-causes", "floor",
30
30
  "tool", "processes", "arch", "arn", "base-image", "b9s-version", "cache", "caches", "commit", "dockerfile",
31
31
  "instance-id", "machine-id", "machine-name", "node-sha256", "node-version", "path", "recipe-version", "region",
32
- "root", "signing-key", "catalog", "context", "source-commit", "component", "normalized-key",
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",
36
+ "purpose", "storage-mode", "hosts", "arn", "version-id",
37
+ "mode", "weights", "quality-target", "half-life", "min-samples", "build-explore", "review-explore", "pause-build", "pause-review", "class",
35
38
  ];
36
39
  export const BOOL_FLAGS = [
37
40
  "latest", "no-restart", "json", "follow", "account", "help", "version", "broadcast", "create-channels",
@@ -39,7 +42,7 @@ export const BOOL_FLAGS = [
39
42
  "pending", "force", "no-hooks", "yes", "open", "bind-here", "peek", "once", "launchd", "full", "no-bind",
40
43
  "all", "here", "keep-worktree", "prune", "abandon", "defer", "hold", "clear", "met", "shared", "archive",
41
44
  "approve", "turn", "service", "print-hooks", "create", "rotate", "codex-userns", "bwrap-userns", "print-apparmor",
42
- "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run",
45
+ "cancel", "rerun", "confirmed", "refuted", "no-source", "confirm-bypass-signal", "in-container", "assessment-only", "retrieve-ec2", "no-wait-verify", "preview", "remove-empty", "dry-run", "stdin", "context-confirmed",
43
46
  ];
44
47
  export function parse(argv) {
45
48
  const options = {};
package/dist/client.js CHANGED
@@ -21,14 +21,39 @@ function expectedTextReceiptFields(method, path, body, response) {
21
21
  return strings("topic");
22
22
  if (verb === "POST" && route === "/machine-operations")
23
23
  return strings("ssh_host");
24
+ if (verb === "POST" && /^\/projects\/[^/]+\/machines\/[^/]+\/jobs$/.test(route))
25
+ return strings("command_label");
26
+ if (verb === "POST" && /^\/machines\/[^/]+\/jobs\/requests\/[^/]+\/cancel$/.test(route))
27
+ return strings("reason");
28
+ if (verb === "POST" && /^\/machines\/[^/]+\/jobs\/permits\/[^/]+\/recover$/.test(route))
29
+ return strings("reason");
24
30
  if (verb === "POST" && /^\/machine-operations\/[^/]+\/progress$/.test(route))
25
31
  return strings("detail");
26
32
  if (verb === "POST" && /^\/machine-operations\/[^/]+\/finish$/.test(route))
27
33
  return strings("result");
34
+ if (verb === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete$/.test(route))
35
+ return strings("excerpt");
28
36
  if (verb === "PATCH" && /^\/projects\/[^/]+\/agents\/[^/]+\/moves\/[^/]+$/.test(route))
29
37
  return strings("detail");
30
- if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route))
31
- return fields.dry_run === true ? [] : strings("agreements", "charter");
38
+ if (verb === "PUT" && /^\/projects\/[^/]+\/process$/.test(route)) {
39
+ if (fields.dry_run === true)
40
+ return [];
41
+ const expected = strings("agreements", "charter", "reason");
42
+ if (Array.isArray(fields.vocabulary)) {
43
+ for (const [index, tag] of fields.vocabulary.entries()) {
44
+ if (!tag || typeof tag !== "object" || Array.isArray(tag))
45
+ continue;
46
+ const t = tag;
47
+ if (typeof t.required_class_clear_reason === "string")
48
+ expected.push(`vocabulary.${index}.required_class_clear_reason`);
49
+ const req = t.required_class;
50
+ if (req && typeof req === "object" && !Array.isArray(req) && typeof req.reason === "string") {
51
+ expected.push(`vocabulary.${index}.required_class.reason`);
52
+ }
53
+ }
54
+ }
55
+ return expected;
56
+ }
32
57
  if (verb === "PUT" && /^\/projects\/[^/]+\/context-policy$/.test(route))
33
58
  return strings("note");
34
59
  if (verb === "POST" && route === "/account/needs/answer")
@@ -49,10 +74,13 @@ function expectedTextReceiptFields(method, path, body, response) {
49
74
  });
50
75
  return required;
51
76
  }
77
+ const reqClassReason = fields.required_class && typeof fields.required_class === "object" && !Array.isArray(fields.required_class) && typeof fields.required_class.reason === "string"
78
+ ? ["required_class.reason"]
79
+ : [];
52
80
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units$/.test(route))
53
- return strings("title", "scope");
81
+ return [...strings("title", "scope"), ...reqClassReason];
54
82
  if (verb === "POST" && /^\/projects\/[^/]+\/work-units\/assign$/.test(route))
55
- return strings("title", "scope", "reason");
83
+ return [...strings("title", "scope", "reason"), ...reqClassReason];
56
84
  const wu = workUnits.exec(route);
57
85
  if (wu?.[1] && wu[2]) {
58
86
  const action = wu[2];
@@ -66,8 +94,10 @@ function expectedTextReceiptFields(method, path, body, response) {
66
94
  ? ["context_decision.reason"]
67
95
  : [];
68
96
  }
69
- if (action === "assign" || action === "kind")
97
+ if (action === "assign" || action === "kind" || action === "mandatory-reviewer" || action === "required-class")
70
98
  return strings("reason");
99
+ if (action === "compare")
100
+ return strings("note", "primary_note", "twin_note");
71
101
  if (action === "ask")
72
102
  return strings("question");
73
103
  if (action === "rule")
@@ -149,11 +179,29 @@ function expectedTextReceiptFields(method, path, body, response) {
149
179
  return ["description"];
150
180
  if (verb === "PATCH" && (/^\/roles\/[^/]+$/.test(route) || /^\/projects\/[^/]+\/roles\/[^/]+$/.test(route)) && typeof fields.description === "string")
151
181
  return ["description"];
182
+ if (verb === "POST" && /^\/projects\/[^/]+\/secrets$/.test(route))
183
+ return strings("purpose");
184
+ if (verb === "PATCH" && /^\/projects\/[^/]+\/secrets\/[^/]+$/.test(route))
185
+ return strings("purpose");
152
186
  if (verb === "POST" && route === "/cloud/secrets" && typeof fields.secret_name === "string" && fields.secret_name.trim())
153
187
  return ["secret_name"];
188
+ if (verb === "POST" && /^\/machines\/[^/]+\/quarantine$/.test(route))
189
+ return strings("reason");
190
+ if (verb === "DELETE" && /^\/machines\/[^/]+\/quarantine$/.test(route))
191
+ return strings("reason");
192
+ if (verb === "PUT" && route === "/cloud/regions")
193
+ return strings("reason");
194
+ if (verb === "PUT" && route === "/cloud/hosted-provisioning")
195
+ return strings("reason");
196
+ if (verb === "POST" && route === "/cloud/spend-signals")
197
+ return strings("detail");
198
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/suggestions\/[^/]+\/accept$/.test(route))
199
+ return strings("note");
200
+ if (verb === "POST" && /^\/projects\/[^/]+\/pools\/suggestions\/[^/]+\/reject$/.test(route))
201
+ return strings("note", "reason");
154
202
  return [];
155
203
  }
156
- export function verifyTextReceipts(response, body, requiredFields = []) {
204
+ export function verifyTextReceipts(response, body, requiredFields = [], allowedRedactedFields = [], allowedDiscardedFields = []) {
157
205
  const receipts = Array.isArray(response?.receipts)
158
206
  ? response.receipts
159
207
  : response?.receipt ? [response.receipt] : [];
@@ -174,9 +222,28 @@ export function verifyTextReceipts(response, body, requiredFields = []) {
174
222
  const bytes = new TextEncoder().encode(expected).byteLength;
175
223
  if (receipt.bytes_received !== bytes)
176
224
  throw new CliError("text_receipt_mismatch", `${field}: server received ${receipt.bytes_received} bytes; CLI sent ${bytes}`);
225
+ const sha256 = createHash("sha256").update(expected, "utf8").digest("hex");
226
+ if (receipt.discarded === true) {
227
+ if (!allowedDiscardedFields.includes(field))
228
+ throw new CliError("text_receipt_mismatch", `${field}: server reported an unexpected policy discard`);
229
+ if (receipt.sha256_received !== sha256)
230
+ throw new CliError("text_receipt_mismatch", `${field}: received text SHA-256 does not match the sent text`);
231
+ if (receipt.bytes_stored !== 0 || receipt.sha256 !== undefined)
232
+ throw new CliError("text_receipt_mismatch", `${field}: discarded receipt must confirm that no text was stored`);
233
+ continue;
234
+ }
235
+ if (receipt.redacted === true) {
236
+ if (!allowedRedactedFields.includes(field))
237
+ throw new CliError("text_receipt_mismatch", `${field}: server reported an unexpected policy transformation`);
238
+ if (receipt.sha256_received !== sha256)
239
+ throw new CliError("text_receipt_mismatch", `${field}: received text SHA-256 does not match the sent text`);
240
+ if (!Number.isSafeInteger(receipt.bytes_stored) || receipt.bytes_stored < 0 || typeof receipt.sha256 !== "string" || !/^[a-f0-9]{64}$/i.test(receipt.sha256)) {
241
+ throw new CliError("text_receipt_mismatch", `${field}: redacted receipt is missing the stored text size or SHA-256`);
242
+ }
243
+ continue;
244
+ }
177
245
  if (receipt.bytes_stored !== bytes)
178
246
  throw new CliError("text_receipt_mismatch", `${field}: server stored ${receipt.bytes_stored} of ${bytes} sent bytes`);
179
- const sha256 = createHash("sha256").update(expected, "utf8").digest("hex");
180
247
  if (receipt.sha256 !== sha256)
181
248
  throw new CliError("text_receipt_mismatch", `${field}: stored text SHA-256 does not match the sent text`);
182
249
  }
@@ -279,7 +346,8 @@ export class Client {
279
346
  : undefined;
280
347
  throw new CliError(err.error ?? `http_${res.status}`, err.message ?? text, hint);
281
348
  }
282
- verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json));
349
+ const allowsRedactedExcerpt = method.toUpperCase() === "POST" && /^\/agents\/me\/sessions\/[^/]+\/turns\/[^/]+\/complete(?:\?|$)/.test(path);
350
+ verifyTextReceipts(json, body, expectedTextReceiptFields(method, path, body, json), allowsRedactedExcerpt ? ["excerpt"] : [], allowsRedactedExcerpt ? ["excerpt"] : []);
283
351
  return json;
284
352
  }
285
353
  }
@@ -10,12 +10,14 @@ import { table } from "../output.js";
10
10
  import { milestoneWith, milestonesWith } from "./wu.js";
11
11
  import { awayUntil } from "./agent.js";
12
12
  import { agentMove, machineAdmin, poolAdmin, projectCheckoutAdmin, projectRepoAdmin } from "./machine-admin.js";
13
+ import { routingAdmin, runRequiredClassUpdate } from "./routing-admin.js";
13
14
  import { accountAdmin, answerAdmin, explainAdmin, keysAdmin, needsAdmin, notifierAdmin, processAdmin, skillAdmin, tagList, textCheckAdmin, worktreeAdmin } from "./operator.js";
14
15
  import { adminNotice } from "./notices.js";
15
16
  import { cloudAdmin } from "./cloud-admin.js";
16
17
  import { projectImageAdmin } from "./image-admin.js";
17
18
  import { environmentAdmin } from "./environment-admin.js";
18
19
  import { flowAdmin } from "./flow.js";
20
+ import { projectSecrets } from "./project-secrets.js";
19
21
  function adminClient(p) {
20
22
  return Client.forAdmin(loadAdmin(resolveAdminName(str(p.flags, "admin"))));
21
23
  }
@@ -74,6 +76,8 @@ export async function admin(p, out) {
74
76
  return projectImageAdmin(rest, p, out);
75
77
  if (action === "environment")
76
78
  return projectEnvironmentAdmin(rest, p, out);
79
+ if (action === "secrets")
80
+ return projectSecrets(rest, p, adminClient(p), out);
77
81
  return project(action, rest, p, out);
78
82
  case "github":
79
83
  return githubAdmin(action, rest, p, out);
@@ -93,6 +97,8 @@ export async function admin(p, out) {
93
97
  return keysAdmin(action, rest, p, out);
94
98
  case "process":
95
99
  return processAdmin(action, rest, p, out);
100
+ case "routing":
101
+ return routingAdmin(action, rest, p, out);
96
102
  case "milestones": {
97
103
  // b9s-admin milestones <project> [export [--out f] | set --file f]
98
104
  if (!action)
@@ -480,8 +486,11 @@ async function role(action, rest, p, out) {
480
486
  throw new CliError("usage", "admin role create|edit|list|delete <name> [--project p] [--projects a,b|*] [--post ch1,ch2] [--broadcast] [--create-channels] [--read-account-status] [--assign-outside-qualifications yes|no] [--description d] [--cardinality one|many]");
481
487
  }
482
488
  async function workUnitAdmin(action, rest, p, out) {
489
+ if (action === "required-class" && rest[0] && /^\d+$/.test(rest[1] ?? "")) {
490
+ return runRequiredClassUpdate(adminClient(p), rest[0], Number(rest[1]), p, out);
491
+ }
483
492
  if (action !== "assign" || !rest[0] || !/^\d+$/.test(rest[1] ?? ""))
484
- throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
493
+ throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"] | b9s-admin wu required-class <project> <n> (--class p/h/m/e | --clear) --reason "why"');
485
494
  const to = str(p.flags, "to");
486
495
  if (!to)
487
496
  throw new CliError("usage", 'b9s-admin wu assign <project> <n> --to <agent> [--reason "why"]');
@@ -3,6 +3,22 @@ import { CliError } from "../errors.js";
3
3
  import { need, str } from "../args.js";
4
4
  import { Client } from "../client.js";
5
5
  import { loadAdmin, resolveAdminName } from "../config.js";
6
+ function fmtCents(v) {
7
+ return typeof v === "number" && Number.isFinite(v) ? `$${(v / 100).toFixed(2)}` : "unknown";
8
+ }
9
+ function fmtCount(v) {
10
+ return typeof v === "number" && Number.isFinite(v) ? String(v) : "unknown";
11
+ }
12
+ function fmtBool(v) {
13
+ return typeof v === "boolean" ? String(v) : "unknown";
14
+ }
15
+ function fmtRegionList(v) {
16
+ if (Array.isArray(v))
17
+ return v.length ? v.join(", ") : "none";
18
+ if (v === null)
19
+ return "any";
20
+ return "unknown";
21
+ }
6
22
  export async function cloudAdmin(action, rest, p, out) {
7
23
  const creds = loadAdmin(resolveAdminName(str(p.flags, "admin")));
8
24
  const c = Client.forAdmin(creds);
@@ -122,6 +138,102 @@ export async function cloudAdmin(action, rest, p, out) {
122
138
  out.print(`Operation ${id}: ${r.state}`, r);
123
139
  return;
124
140
  }
125
- default: throw new CliError("usage", "cloud connect|show|policy|test|disconnect|bootstrap-script|secret|launch|operations|inspect|terminate");
141
+ case "capacity": {
142
+ const r = await c.call("GET", "/cloud/capacity");
143
+ const cap = r.capacity;
144
+ const spend = cap?.spend;
145
+ const launchStatus = cap?.launchable === true
146
+ ? "launchable"
147
+ : cap?.launchable === false
148
+ ? `BLOCKED — ${cap?.blocking_reason ?? "unavailable"}`
149
+ : "unknown";
150
+ const hardenedText = cap?.connection_hardened === true
151
+ ? "yes"
152
+ : cap?.connection_hardened === false
153
+ ? `NO (${cap?.hardening_error ?? "test required"})`
154
+ : "unknown";
155
+ const regionText = cap?.region_approved === true
156
+ ? "approved"
157
+ : cap?.region_approved === false
158
+ ? `BLOCKED (${cap?.region_error ?? "not allowlisted"})`
159
+ : "unknown";
160
+ const priceText = cap?.price_table_valid === true
161
+ ? "valid"
162
+ : cap?.price_table_valid === false
163
+ ? `INVALID (${cap?.price_table_error ?? "stale"})`
164
+ : "unknown";
165
+ const spendLine = spend && typeof spend === "object"
166
+ ? ` spend: reserved ${fmtCents(spend.liveReservedCents)}, cap ${fmtCents(spend.dailyCapCents)} (mode=${typeof spend.spendMode === "string" && spend.spendMode ? spend.spendMode : "unknown"}, hard_80pct=${fmtCents(spend.hardCap80PctCents)}, launchable=${fmtCents(spend.launchableCents)}${spend.spendMode === "grace" ? `, grace_cap=${fmtCents(spend.graceCapCents)}` : ""}${spend.graceExpiresAt ? `, grace_expires=${spend.graceExpiresAt}` : ""}${spend.graceExpired === true ? ", grace_expired=yes" : ""}${typeof spend.warningPct === "number" && Number.isFinite(spend.warningPct) ? `, external_signal=${spend.warningPct}%` : ""})`
167
+ : ` spend: ${cap?.configured === false ? "unavailable (not configured)" : "unknown"}`;
168
+ const lines = [
169
+ `Cloud capacity (${cap?.region ?? "unconfigured"}/${cap?.instance_type ?? "-"}): ${launchStatus}`,
170
+ ` hardened ${hardenedText}; region ${regionText}; price table ${priceText}`,
171
+ ` instances active ${fmtCount(cap?.active_instances)}/${fmtCount(cap?.max_instances)}, pending ${fmtCount(cap?.pending_instances)}, launchable additional ${fmtCount(cap?.launchable_additional_instances)} (by instances=${fmtCount(cap?.remaining_by_instances)}, vcpu=${fmtCount(cap?.remaining_by_vcpu)}, storage=${fmtCount(cap?.remaining_by_storage)}, spend=${fmtCount(cap?.remaining_by_spend)})`,
172
+ spendLine,
173
+ ` controls: account_provisioning_disabled=${fmtBool(cap?.account_provisioning_disabled)}, hosted_provisioning_disabled=${fmtBool(cap?.hosted_provisioning_disabled)}`,
174
+ ];
175
+ if (Array.isArray(cap?.active_image_build_projects) && cap.active_image_build_projects.length) {
176
+ lines.push(` active project image builds: ${cap.active_image_build_projects.join(", ")}`);
177
+ }
178
+ out.print(lines.join("\n"), r);
179
+ return;
180
+ }
181
+ case "regions": {
182
+ const [sub, list] = rest;
183
+ if (sub !== "set" && sub !== "clear") {
184
+ throw new CliError("usage", "cloud regions set <region[,region...]> --reason <text> | clear [--reason <text>]");
185
+ }
186
+ if (sub === "set") {
187
+ if (!list)
188
+ throw new CliError("usage", "cloud regions set <region[,region...]> --reason <text>");
189
+ const regions = list.split(",").map((x) => x.trim()).filter(Boolean);
190
+ if (!regions.length)
191
+ throw new CliError("usage", "cloud regions set <region[,region...]> --reason <text>");
192
+ const reason = need(p.flags, "reason");
193
+ const r = await c.call("PUT", "/cloud/regions", { regions, reason });
194
+ const regionStatus = r.region_approved === true ? "approved" : r.region_approved === false ? "NOT in allowlist" : "unknown";
195
+ out.print(`Approved cloud regions set to: ${fmtRegionList(r.approved_regions)} (current region ${regionStatus})`, r);
196
+ return;
197
+ }
198
+ const reason = str(p.flags, "reason") ?? "cleared approved cloud region restrictions";
199
+ const r = await c.call("PUT", "/cloud/regions", { regions: null, reason });
200
+ const regionStatus = r.region_approved === true ? "approved" : r.region_approved === false ? "NOT in allowlist" : "unknown";
201
+ out.print(`Cleared account approved cloud region restrictions (platform defaults: ${fmtRegionList(r.platform_approved_regions)}; current region ${regionStatus})`, r);
202
+ return;
203
+ }
204
+ case "hosted-provisioning": {
205
+ const sub = rest[0];
206
+ if (sub !== "enable" && sub !== "disable") {
207
+ throw new CliError("usage", "cloud hosted-provisioning enable|disable --reason <text>");
208
+ }
209
+ const r = await c.call("PUT", "/cloud/hosted-provisioning", { disabled: sub === "disable", reason: need(p.flags, "reason") });
210
+ out.print(`Hosted cloud provisioning: account_disabled=${fmtBool(r.account_hosted_provisioning_disabled)}, effective_disabled=${fmtBool(r.effective_hosted_provisioning_disabled)}`, r);
211
+ return;
212
+ }
213
+ case "spend-signal": {
214
+ const rawPct = rest[0];
215
+ if (!rawPct)
216
+ throw new CliError("usage", "cloud spend-signal <0..200|clear> [--source aws_budget|cost_explorer|billing_alarm|operator] [--detail <text>]");
217
+ let warning_pct;
218
+ if (rawPct === "clear") {
219
+ warning_pct = null;
220
+ }
221
+ else {
222
+ if (!/^\d+$/.test(rawPct))
223
+ throw new CliError("usage", "cloud spend-signal <0..200|clear> ...");
224
+ warning_pct = Number(rawPct);
225
+ if (warning_pct < 0 || warning_pct > 200)
226
+ throw new CliError("usage", "spend-signal percentage must be between 0 and 200");
227
+ }
228
+ const source = str(p.flags, "source") ?? "operator";
229
+ if (!["aws_budget", "cost_explorer", "billing_alarm", "operator"].includes(source)) {
230
+ throw new CliError("usage", "--source must be aws_budget|cost_explorer|billing_alarm|operator");
231
+ }
232
+ const detail = str(p.flags, "detail");
233
+ const r = await c.call("POST", "/cloud/spend-signals", { warning_pct, source, ...(detail !== undefined ? { detail } : {}) });
234
+ out.print(`Cloud spend signal recorded (launchable=${fmtBool(r.launchable)}${r.blocking_reason ? `, blocked: ${r.blocking_reason}` : ""})`, r);
235
+ return;
236
+ }
237
+ default: throw new CliError("usage", "cloud connect|show|policy|test|disconnect|bootstrap-script|secret|launch|operations|inspect|terminate|capacity|regions|hosted-provisioning|spend-signal");
126
238
  }
127
239
  }
@@ -68,6 +68,11 @@ export async function harnessStart(p, out, harness) {
68
68
  const name = str(p.flags, "as");
69
69
  if (!name)
70
70
  throw new CliError("usage", `${cmd} needs --as <agent-name>`);
71
+ const machineSessionId = str(p.flags, "machine-session-id");
72
+ if (machineSessionId && !/^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$/i.test(machineSessionId))
73
+ throw new CliError("usage", "--machine-session-id must be a UUID");
74
+ if (machineSessionId)
75
+ process.env.BSCHAT_MACHINE_SESSION_ID = machineSessionId;
71
76
  const inContainer = bool(p.flags, "in-container");
72
77
  let errorSlug = name;
73
78
  let watchArgv = null;
@@ -232,7 +237,7 @@ export async function harnessStart(p, out, harness) {
232
237
  `If you ran on another machine before, read your latest note first: \`b9s handoffs --agent ${creds.agent}\` (your units, branches and chat are on the server as before).`,
233
238
  ].join("\n");
234
239
  const diagnostic = [];
235
- if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour))) {
240
+ if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (m) => diagnostic.push(m), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, harness))) {
236
241
  throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the onboarding turn");
237
242
  }
238
243
  try {
@@ -303,8 +308,8 @@ export async function harnessStart(p, out, harness) {
303
308
  mkdirSync(tmp, { recursive: true });
304
309
  const followDelay = Number(str(p.flags, "follow-delay") ?? "300");
305
310
  const prune = bool(p.flags, "prune");
306
- watcherEnv = { TMPDIR: tmp, ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
307
- const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model };
311
+ watcherEnv = { TMPDIR: tmp, ...(machineSessionId ? { BSCHAT_MACHINE_SESSION_ID: machineSessionId } : {}), ...(harness === "claude-code" ? claudeSandboxEnv(sandbox) : {}), ...(harness === "antigravity" ? { BSCHAT_HARNESS: "antigravity", BSCHAT_ANTIGRAVITY_SANDBOX: sandbox, BSCHAT_MODEL: model, ...(effort ? { BSCHAT_EFFORT: effort } : {}) } : {}) };
312
+ const turnSpec = { harness, session, timeout: turnTimeout, turnsPerHour, unproductivePerHour, coalesceSeconds: turnCoalesceSeconds, provider, model, ...(machineSessionId ? { machineSessionId } : {}) };
308
313
  if (inContainer) {
309
314
  const sess = sessionOfExec(exec);
310
315
  if (sess)
@@ -552,7 +557,7 @@ export function runClaudeSandboxSelfCheck(bin, settings, maxBudgetUsd, env, cwd,
552
557
  /** Guard a model-spending connectivity preflight independently from the agent's real turn. */
553
558
  export async function runGuardedClaudeSandboxSelfCheck(ref, turnsPerHour, bin, settings, maxBudgetUsd, env, cwd, session, run = runClaudeSandboxSelfCheck, unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
554
559
  const diagnostic = [];
555
- if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
560
+ if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "claude-code"))) {
556
561
  throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the sandbox self-check");
557
562
  }
558
563
  const probe = probeFor("claude-code", session, ref);
@@ -603,7 +608,7 @@ export function assertAntigravitySelfCheck(output) {
603
608
  /** Run the two connectivity checks through the real model tools inside the per-turn sandbox. */
604
609
  export async function runAntigravitySandboxSelfCheck(ref, bin, settings, cwd, session, model, effort, timeoutSeconds, logPath, turnsPerHour = DEFAULT_TURNS_PER_HOUR, env = antigravityTurnEnv("workspace-write"), unproductivePerHour = DEFAULT_UNPRODUCTIVE_PER_HOUR) {
605
610
  const diagnostic = [];
606
- if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour))) {
611
+ if (!(await beginTurnGuardAttempt(ref, turnsPerHour, (message) => diagnostic.push(message), process.env, unproductivePerHour, process.env.BSCHAT_MACHINE_SESSION_ID, "antigravity"))) {
607
612
  throw new CliError("turn_mode_fault", diagnostic.at(-1) ?? "turn mode guard refused the Antigravity sandbox self-check");
608
613
  }
609
614
  const prompt = [
@@ -158,12 +158,14 @@ export async function gatherUpdates(name, opts) {
158
158
  let messages;
159
159
  let items = [];
160
160
  let questions = [];
161
+ const watchCursorAfter = opts.watchCursor ? state.watch_inbox_after ?? state.inbox_after : undefined;
161
162
  // A poll on the agent's behalf: no presence header, so last_seen keeps meaning "the agent acted".
162
163
  const client = Client.forAgent(creds, resolveModel(opts.model, process.env, process.cwd(), name), { presence: false });
163
164
  try {
164
165
  const qs = new URLSearchParams({ limit: "20" });
165
- if (state.inbox_after)
166
- qs.set("after", state.inbox_after);
166
+ const inboxAfter = opts.watchCursor ? watchCursorAfter : state.inbox_after;
167
+ if (inboxAfter)
168
+ qs.set("after", inboxAfter);
167
169
  const r = await client.call("GET", `/inbox?${qs}`);
168
170
  messages = r.messages;
169
171
  items = r.items ?? [];
@@ -204,10 +206,19 @@ export async function gatherUpdates(name, opts) {
204
206
  process.stderr.write(`b9s: outcome measures: ${e.message}\n`);
205
207
  }
206
208
  const next = { ...state, last_check: Date.now() };
207
- if (messages.length)
208
- next.inbox_after = messages[messages.length - 1].created_at;
209
+ if (messages.length) {
210
+ if (opts.watchCursor)
211
+ next.watch_inbox_after = messages[messages.length - 1].created_at;
212
+ else
213
+ next.inbox_after = messages[messages.length - 1].created_at;
214
+ }
209
215
  if (nextMeasureState !== null)
210
216
  next.measure_state = nextMeasureState;
217
+ const initialWatchCursor = opts.watchCursor && state.watch_inbox_after === undefined
218
+ ? state.inbox_after ?? (messages.length
219
+ ? new Date(Date.parse(messages[0].created_at) - 1).toISOString()
220
+ : undefined)
221
+ : undefined;
211
222
  const channelRead = { ...(state.channel_read ?? {}) };
212
223
  const follows = new Set(state.follows ?? []);
213
224
  const digest = [];
@@ -278,7 +289,9 @@ export async function gatherUpdates(name, opts) {
278
289
  for (const [k, v] of Object.entries(channelRead))
279
290
  if (merged[k] === undefined)
280
291
  merged[k] = v;
281
- writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}) });
292
+ // Keep fetched messages visible to wakeOnce until it knows whether direct work was delivered.
293
+ // Empty polls still persist the independent watcher baseline.
294
+ writeState(name, { ...state, channel_read: merged, ...(next.pending_reads ? { pending_reads: next.pending_reads } : {}), ...(initialWatchCursor !== undefined ? { watch_inbox_after: initialWatchCursor } : {}) });
282
295
  }
283
296
  else {
284
297
  writeState(name, { ...next, ...(noticeChanges ? { notice_state: noticeChanges.next } : {}) });
@@ -332,7 +345,8 @@ export async function gatherUpdates(name, opts) {
332
345
  if (deferredReads.length)
333
346
  visibleReadCommands.push("b9s read --pending");
334
347
  const cmds = [...(messages.length || questions.length || items.length ? ["b9s inbox --unread"] : []), ...visibleReadCommands];
335
- const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || new RegExp(`(^|[^\\w@])@${name.replace(/[-_]/g, "\\$&")}(?![\\w-])`).test(message.body);
348
+ const escapedAgent = creds.agent.replace(/[-_]/g, "\\$&");
349
+ const isDirectMessage = (message) => message.role_name === "human" || !!message.reply_to_seq || message.mentions?.includes(creds.agent) || new RegExp(`(^|[^\\w@])@${escapedAgent}(?![\\w-])`).test(message.body);
336
350
  const direct = questions.length > 0 || items.length > 0 || noticeLines.length > 0 || measureLines.length > 0 || messages.some(isDirectMessage);
337
351
  const tier = direct ? "direct" : messages.length ? "role" : followed.length ? "followed" : "digest";
338
352
  const directTimes = [
@@ -343,7 +357,7 @@ export async function gatherUpdates(name, opts) {
343
357
  const firstDirectAt = directTimes.sort()[0] ?? null;
344
358
  const urgent = messages.some((message) => message.urgent === true || message.priority === "urgent")
345
359
  || items.some((item) => item.urgent === true || item.priority === "urgent");
346
- return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
360
+ return { text: delivery.text, counts: { messages: messages.length, questions: questions.length, items: items.length, followed: followed.length, digest: digest.length, notices: noticeLines.length }, noticeLines, noticeNext, measureSnapshot: nextMeasureState ?? undefined, latestOperatorAt: operator, readCommands: cmds, tier, firstDirectAt, urgent, ...(opts.watchCursor && messages.length ? { watchCursorAfter: messages[messages.length - 1].created_at } : {}), delivery: { bytes: delivery.bytes, by_kind: delivery.by_kind }, parts };
347
361
  }
348
362
  /** Command patterns warn without blocking; errors remain visible to the caller. */
349
363
  export async function commandWarnings(name, command) {
@@ -555,7 +569,7 @@ async function antigravityHook(p) {
555
569
  return out({});
556
570
  }
557
571
  if (typeof input?.transcriptPath === "string" && input.transcriptPath)
558
- noteSession(name, "antigravity", input.transcriptPath, conv);
572
+ noteSession(name, "antigravity", input.transcriptPath, conv, event === "SessionStart" && input?.source === "compact");
559
573
  if (typeof input?.modelName === "string" && input.modelName) {
560
574
  const st = readState(name);
561
575
  if (st.model !== input.modelName)
@@ -679,10 +693,9 @@ function noteSession(name, harness, transcript, sessionId, compacted = false) {
679
693
  const st = readState(name);
680
694
  const cur = st.harness_session;
681
695
  const same = !!cur && cur.transcript === transcript && cur.harness === harness;
682
- if (same && !compacted)
683
- return;
684
696
  const compactions = same ? [...(cur.compactions ?? [])] : [];
685
697
  if (compacted)
686
698
  compactions.push(Date.now());
687
- writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: same ? cur.at : Date.now(), ...(compactions.length ? { compactions: compactions.slice(-1000) } : {}), ...(same && cur.provider ? { provider: cur.provider } : {}) } });
699
+ const observedAt = Date.now();
700
+ writeState(name, { ...st, harness_session: { harness, transcript, session_id: sessionId, at: same ? cur.at : observedAt, last_seen_at: observedAt, ...(compactions.length ? { compactions: compactions.slice(-1000) } : {}), ...(same && cur.provider ? { provider: cur.provider } : {}) } });
688
701
  }
@@ -7,6 +7,7 @@ import { CliError } from "../errors.js";
7
7
  import { table } from "../output.js";
8
8
  import { CLI_VERSION } from "../version.js";
9
9
  import { runMachineResize } from "./machine-resize.js";
10
+ import { poolSuggestionsAdmin } from "./routing-admin.js";
10
11
  /**
11
12
  * b9s-admin machine: provision machines over the operator's own ssh and declare the agent
12
13
  * sessions they run (docs/REMOTE-MACHINES.md). The server never sees an ssh credential: every ssh
@@ -187,6 +188,7 @@ export async function machineAdmin(action, rest, p, out) {
187
188
  `${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}%)`,
188
189
  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?)",
189
190
  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,
191
+ m.quarantined ? ` QUARANTINED: ${m.quarantine?.reason ?? "operator containment"}${m.quarantine?.at ? ` (${m.quarantine.at})` : ""}` : null,
190
192
  ];
191
193
  const cacheLines = [];
192
194
  const declaredCaches = (m.build_caches ?? []);
@@ -459,7 +461,36 @@ export async function machineAdmin(action, rest, p, out) {
459
461
  return out.print(`Removed ${ref} from ${machineName}; the agent and its thread stay.`, { removed: ref });
460
462
  }
461
463
  }
462
- throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | resize <name> --type <instance-type> | remove <name> | session add|stop|start|resume|limit|coalesce|thread|remove <machine> <project>/<agent> [...]");
464
+ if (action === "quarantine") {
465
+ const name = rest[0];
466
+ if (!name)
467
+ throw new CliError("usage", "machine quarantine <name> --reason <text> [--evidence <json>]");
468
+ const reason = need(p.flags, "reason");
469
+ const rawEvidence = str(p.flags, "evidence");
470
+ let evidence;
471
+ if (rawEvidence !== undefined) {
472
+ try {
473
+ evidence = JSON.parse(rawEvidence);
474
+ }
475
+ catch {
476
+ throw new CliError("usage", "--evidence must be valid JSON");
477
+ }
478
+ }
479
+ const r = await c.call("POST", `/machines/${encodeURIComponent(name)}/quarantine`, {
480
+ reason,
481
+ ...(evidence !== undefined ? { evidence } : {}),
482
+ });
483
+ return out.print(`Machine ${name} quarantined: ${reason}`, r);
484
+ }
485
+ if (action === "unquarantine") {
486
+ const name = rest[0];
487
+ if (!name)
488
+ throw new CliError("usage", "machine unquarantine <name> [--reason <text>]");
489
+ const reason = str(p.flags, "reason");
490
+ const r = await c.call("DELETE", `/machines/${encodeURIComponent(name)}/quarantine`, reason !== undefined ? { reason } : undefined);
491
+ return out.print(`Machine ${name} quarantine cleared`, r);
492
+ }
493
+ throw new CliError("usage", "machine add <name> --ssh <host> | list | show <name> | resize <name> --type <instance-type> | quarantine <name> --reason <text> | unquarantine <name> | remove <name> | session add|stop|start|resume|limit|coalesce|thread|remove <machine> <project>/<agent> [...]");
463
494
  }
464
495
  async function confirmMachineName(machine, p) {
465
496
  const supplied = str(p.flags, "confirm");
@@ -587,6 +618,9 @@ export function repeated(argv, flag) {
587
618
  * pool list [project] | show <project>/<name> | remove <project>/<name>
588
619
  */
589
620
  export async function poolAdmin(action, rest, p, out, argv) {
621
+ if (action === "suggestions" || action === "suggestion") {
622
+ return poolSuggestionsAdmin(action, rest, p, out);
623
+ }
590
624
  if (action === "set" && p.flags["turn-coalesce-seconds"] !== undefined) {
591
625
  throw new CliError("usage", "--turn-coalesce-seconds is only supported for individual machine sessions; pool settings do not support turn coalescing");
592
626
  }