pi-braid 0.40.5 → 0.41.0

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.
Files changed (95) hide show
  1. package/AGENTS.md +17 -18
  2. package/README.md +128 -130
  3. package/TOOLS.md +35 -35
  4. package/build-info.json +4 -4
  5. package/dist/extensions/core/agent-environment/index.js +4 -3
  6. package/dist/extensions/core/prompt-builder/index.js +12 -7
  7. package/dist/extensions/core/prompt-builder/instance-composition.d.ts +51 -10
  8. package/dist/extensions/core/prompt-builder/instance-composition.js +87 -14
  9. package/dist/extensions/core/prompt-builder/system-info-tool.d.ts +3 -3
  10. package/dist/extensions/core/prompt-builder/system-info-tool.js +3 -3
  11. package/dist/extensions/core/prompt-builder/tool-guidelines.js +1 -1
  12. package/dist/extensions/core/skills-tool/auto-inject.d.ts +89 -10
  13. package/dist/extensions/core/skills-tool/auto-inject.js +150 -21
  14. package/dist/extensions/core/skills-tool/index.d.ts +70 -2
  15. package/dist/extensions/core/skills-tool/index.js +149 -15
  16. package/dist/extensions/core/skills-tool/reach.d.ts +119 -0
  17. package/dist/extensions/core/skills-tool/reach.js +213 -0
  18. package/dist/extensions/core/skills-tool/skill-triggers.d.ts +47 -10
  19. package/dist/extensions/core/skills-tool/skill-triggers.js +66 -23
  20. package/dist/extensions/enforcement/handlers/register-session-compact.js +12 -1
  21. package/dist/extensions/enforcement/handlers/register-session-shutdown-resumption.js +15 -34
  22. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.d.ts +2 -1
  23. package/dist/extensions/enforcement/handlers/register-session-start-discoverability.js +55 -28
  24. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.d.ts +14 -10
  25. package/dist/extensions/enforcement/handlers/register-turn-end-hygiene.js +88 -82
  26. package/dist/extensions/enforcement/resume-state.d.ts +76 -0
  27. package/dist/extensions/enforcement/resume-state.js +90 -0
  28. package/dist/extensions/enforcement/substate/context-hygiene-state.d.ts +9 -0
  29. package/dist/extensions/enforcement/substate/context-hygiene-state.js +8 -0
  30. package/dist/extensions/enforcement/whisper.d.ts +12 -0
  31. package/dist/extensions/enforcement/whisper.js +16 -1
  32. package/dist/extensions/heartbeat/heartbeat-scheduler/index.js +14 -6
  33. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.d.ts +7 -0
  34. package/dist/extensions/heartbeat/heartbeat-scheduler/policies.js +372 -0
  35. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.d.ts +8 -2
  36. package/dist/extensions/memory/context-manager/handlers/tools/context-compress.js +54 -21
  37. package/dist/lib/config/braid-paths.d.ts +14 -0
  38. package/dist/lib/config/braid-paths.js +18 -0
  39. package/dist/lib/config/braid-settings.d.ts +21 -0
  40. package/dist/lib/config/braid-settings.js +16 -0
  41. package/dist/lib/detection/context-tiers.d.ts +47 -3
  42. package/dist/lib/detection/context-tiers.js +122 -13
  43. package/dist/lib/events/turn-boundary.d.ts +78 -0
  44. package/dist/lib/events/turn-boundary.js +91 -0
  45. package/dist/lib/orchestrator/workers.d.ts +3 -2
  46. package/dist/lib/orchestrator/workers.js +22 -4
  47. package/dist/lib/state/global-state.d.ts +1 -1
  48. package/docs/CONTEXT-MAP.md +1 -1
  49. package/docs/CONTEXT-POLICY.md +8 -0
  50. package/docs/FLEET.md +99 -0
  51. package/docs/LOCAL_DEV.md +0 -1
  52. package/docs/ROADMAP.md +5 -5
  53. package/docs/SETUP.md +19 -18
  54. package/package.json +5 -1
  55. package/scripts/fleet/cli.mjs +499 -0
  56. package/scripts/fleet/driver-rpc.mjs +376 -0
  57. package/scripts/fleet/driver-scripted.mjs +239 -0
  58. package/scripts/fleet/journal.mjs +994 -0
  59. package/scripts/fleet/procs.mjs +76 -0
  60. package/scripts/fleet/supervisor.mjs +1494 -0
  61. package/scripts/fleet/tool-guard.mjs +467 -0
  62. package/skills/herdr-topology/SKILL.md +6 -1
  63. package/skills/release-pipeline/SKILL.md +20 -4
  64. package/skills/research/SKILL.md +32 -0
  65. package/skills/subagent-orchestration/SKILL.md +2 -2
  66. package/src/extensions/core/agent-environment/index.ts +4 -3
  67. package/src/extensions/core/prompt-builder/AGENTS.md +8 -4
  68. package/src/extensions/core/prompt-builder/index.ts +12 -7
  69. package/src/extensions/core/prompt-builder/instance-composition.ts +98 -14
  70. package/src/extensions/core/prompt-builder/system-info-tool.ts +3 -3
  71. package/src/extensions/core/prompt-builder/tool-guidelines.ts +1 -1
  72. package/src/extensions/core/skills-tool/auto-inject.ts +196 -24
  73. package/src/extensions/core/skills-tool/index.ts +217 -15
  74. package/src/extensions/core/skills-tool/reach.ts +256 -0
  75. package/src/extensions/core/skills-tool/skill-triggers.ts +90 -20
  76. package/src/extensions/enforcement/handlers/register-session-compact.ts +12 -1
  77. package/src/extensions/enforcement/handlers/register-session-shutdown-resumption.ts +23 -36
  78. package/src/extensions/enforcement/handlers/register-session-start-discoverability.ts +59 -29
  79. package/src/extensions/enforcement/handlers/register-turn-end-hygiene.ts +101 -81
  80. package/src/extensions/enforcement/resume-state.ts +127 -0
  81. package/src/extensions/enforcement/substate/context-hygiene-state.ts +17 -0
  82. package/src/extensions/enforcement/whisper.ts +21 -1
  83. package/src/extensions/heartbeat/heartbeat-scheduler/index.ts +20 -5
  84. package/src/extensions/heartbeat/heartbeat-scheduler/policies.ts +370 -0
  85. package/src/extensions/memory/AGENTS.md +25 -1
  86. package/src/extensions/memory/context-manager/handlers/tools/context-compress.ts +80 -27
  87. package/src/lib/config/braid-paths.ts +20 -0
  88. package/src/lib/config/braid-settings.ts +46 -0
  89. package/src/lib/detection/context-tiers.ts +186 -13
  90. package/src/lib/events/AGENTS.md +1 -0
  91. package/src/lib/events/turn-boundary.ts +115 -0
  92. package/src/lib/orchestrator/workers.ts +33 -12
  93. package/src/lib/state/global-state.ts +1 -0
  94. package/src/lib/utils/AGENTS.md +1 -1
  95. package/src/types/extension-context.d.ts +22 -79
@@ -0,0 +1,499 @@
1
+ #!/usr/bin/env node
2
+ /**
3
+ * pi-braid-fleet: the supervisor fleet's four operator commands, over one
4
+ * journal.
5
+ *
6
+ * fleet spawn <parent|-> <charter> register a node and make sure one supervisor runs
7
+ * fleet status [--json] the fleet as the journal and ps report it
8
+ * fleet inject <node> <text> deliver a message; steers a running turn when it can
9
+ * fleet ask <node> <question> record a question with a token a human can answer
10
+ *
11
+ * `inject --token <token>` is the answer path: the token is shared between ask
12
+ * and answer, so one verb covers both directions (ordinary steer, and a reply
13
+ * to a parked node).
14
+ *
15
+ * Delivery tiers, recorded on the inbox row, never guessed at:
16
+ * A a turn was in flight, and the child ran the steered text inside that turn
17
+ * (`delivered_tier = 'A'`). Written only from the driver's own
18
+ * `steer_delivered` event: pi answers a steer request when it has *queued*
19
+ * the text, and a queue is not a delivery, so the ack alone records
20
+ * nothing.
21
+ * B the supervisor was up but the node was not streaming; queued, and the
22
+ * next turn for the node carries it (`delivered_tier = 'B'`)
23
+ * C no supervisor was running; the message waits in the journal for the next
24
+ * turn a supervisor drives (`state = 'recorded'`)
25
+ *
26
+ * So `inject` during a turn reports "steered", not "delivered": the row stays
27
+ * `recorded` until the child runs the text, and the turn after it carries the
28
+ * message if the child ends without doing so.
29
+ *
30
+ * And the other end of the same account: a message is retired
31
+ * (`state = 'consumed'`) only when its body was in the prompt a turn sent. One
32
+ * that no turn will ever carry - the node is done, or failed at its attempt
33
+ * bound - is stamped `undeliverable` by the supervisor and counted in `status`,
34
+ * and this command refuses to queue for a finished node in the first place.
35
+ */
36
+
37
+ import { spawn } from "node:child_process";
38
+ import { randomBytes } from "node:crypto";
39
+ import { closeSync, existsSync, mkdirSync, openSync, realpathSync } from "node:fs";
40
+ import { basename, dirname, join, resolve } from "node:path";
41
+ import { fileURLToPath } from "node:url";
42
+
43
+ import { openJournal, resolveFleetRoot } from "./journal.mjs";
44
+ import { buildStatus, controlSocketPath, DEFAULT_ANSWER, requestOnControlSocket, undeliverableReason } from "./supervisor.mjs";
45
+ import { pidIsAlive } from "./procs.mjs";
46
+
47
+ const HERE = dirname(fileURLToPath(import.meta.url));
48
+ const SUPERVISOR = join(HERE, "supervisor.mjs");
49
+
50
+ export function defaultRoot(cwd = process.cwd()) {
51
+ return resolveFleetRoot(process.env.PI_FLEET_ROOT ?? join(cwd, ".fleet"));
52
+ }
53
+
54
+ function slug(text) {
55
+ return String(text)
56
+ .toLowerCase()
57
+ .replace(/[^a-z0-9]+/g, "-")
58
+ .replace(/^-|-$/g, "")
59
+ .slice(0, 24) || "node";
60
+ }
61
+
62
+ /** One request, one response line, over the supervisor's unix socket. */
63
+ export function controlRequest(root, request, { timeoutMs = 10_000 } = {}) {
64
+ const path = controlSocketPath(root);
65
+ if (!existsSync(path)) return Promise.resolve(null);
66
+ return requestOnControlSocket(path, request, { timeoutMs });
67
+ }
68
+
69
+ /** The journalled supervisor that is still a live process, or null. */
70
+ function liveSupervisor(journal) {
71
+ for (const row of journal.supervisors()) {
72
+ if (row.state !== "live") continue;
73
+ if (pidIsAlive(row.pid)) return row;
74
+ journal.setSupervisorState(row.pid, "dead");
75
+ }
76
+ return null;
77
+ }
78
+
79
+ /**
80
+ * The supervisor's command line, built in one place so a flag cannot be read by
81
+ * the parser and then dropped on the way to the process that understands it.
82
+ *
83
+ * `--idle-exit-ms` is the flag that made this a function: `fleet spawn`
84
+ * accepted it and never passed it on, which is worse than not accepting it, so
85
+ * it is now forwarded and its value is refused when it is not a number the
86
+ * supervisor can use.
87
+ */
88
+ export function supervisorArgs(root, options = {}) {
89
+ const args = [SUPERVISOR, "--root", resolveFleetRoot(root)];
90
+ if (options.cap != null) args.push("--cap", String(options.cap));
91
+ if (options.driver) args.push("--driver", options.driver);
92
+ if (options.model) args.push("--model", options.model);
93
+ if (options.piBin) args.push("--pi-bin", options.piBin);
94
+ if (options.idleExitMs != null) args.push("--idle-exit-ms", String(wholeMilliseconds(options.idleExitMs, "--idle-exit-ms")));
95
+ for (const extension of options.extensions ?? []) args.push("--extension", extension);
96
+ for (const flag of options.childFlags ?? []) args.push(flag);
97
+ return args;
98
+ }
99
+
100
+ /**
101
+ * A flag the supervisor will read as milliseconds, or a refusal.
102
+ *
103
+ * Read from its spelled form on purpose: `--idle-exit-ms` with no value arrives
104
+ * as the boolean `true`, and `Number(true)` is 1, which would have been a
105
+ * supervisor told to exit after one millisecond. A caller that has already
106
+ * parsed the flag passes a number, and a number is checked the same way.
107
+ */
108
+ function wholeMilliseconds(value, flag) {
109
+ const text = typeof value === "number" ? String(value) : value;
110
+ if (typeof text !== "string" || !/^\d+$/.test(text.trim()) || Number(text) <= 0) {
111
+ throw new Error(`${flag} needs a whole number of milliseconds greater than 0 (got ${JSON.stringify(value)})`);
112
+ }
113
+ return Number(text);
114
+ }
115
+
116
+ /**
117
+ * Start the supervisor unless one is already there. Two instruments answer
118
+ * that, and they answer different questions: the channel says whether a
119
+ * supervisor can actually be reached, the journal row says whether a process
120
+ * claims the job. A supervisor that never bound, or refused to, leaves a row
121
+ * that only the channel corrects, so the channel is asked first, and the
122
+ * journal is the answer when the channel is the thing that is broken. Starting
123
+ * a second supervisor over a live channel is the one outcome neither may cause.
124
+ *
125
+ * Detached with its own process group: the drill kills it with SIGKILL, which
126
+ * is only a meaningful test if nothing else is holding it up.
127
+ */
128
+ export async function ensureSupervisor(root, options = {}) {
129
+ const answering = await controlRequest(root, { op: "ping" }, { timeoutMs: 1000 });
130
+ if (answering?.ok) return { started: false, pid: answering.data.pid };
131
+ const journal = openJournal(root, {});
132
+ const live = liveSupervisor(journal);
133
+ journal.close();
134
+ if (live) return { started: false, pid: live.pid };
135
+ const logPath = join(resolveFleetRoot(root), "supervisor.log");
136
+ mkdirSync(dirname(logPath), { recursive: true });
137
+ const logFd = openSync(logPath, "a");
138
+ const args = supervisorArgs(root, options);
139
+ const child = spawn(process.execPath, args, {
140
+ detached: true,
141
+ stdio: ["ignore", logFd, logFd],
142
+ cwd: process.cwd(),
143
+ env: process.env,
144
+ });
145
+ child.unref();
146
+ closeSync(logFd);
147
+ return { started: true, pid: child.pid, logPath };
148
+ }
149
+
150
+ function svrLogPath(root) {
151
+ return join(resolveFleetRoot(root), "supervisor.log");
152
+ }
153
+
154
+ async function waitForSupervisor(root, { timeoutMs = 10_000 } = {}) {
155
+ const started = Date.now();
156
+ while (Date.now() - started < timeoutMs) {
157
+ const reply = await controlRequest(root, { op: "ping" }, { timeoutMs: 500 });
158
+ if (reply?.ok) return reply.data;
159
+ await new Promise((resolveWait) => setTimeout(resolveWait, 100));
160
+ }
161
+ return null;
162
+ }
163
+
164
+ // ── commands ────────────────────────────────────────────────────────────────
165
+
166
+ async function cmdSpawn(args) {
167
+ const [parent, charter] = args._;
168
+ if (!parent || !charter) throw new Error("usage: fleet spawn <parent|-> <charter-path>");
169
+ // Read before the node is registered: a flag refused after the journal has
170
+ // already recorded a spawn is a half-done command, and the operator asked for
171
+ // one thing that failed.
172
+ const idleExitMs = args["idle-exit-ms"] == null ? undefined : wholeMilliseconds(args["idle-exit-ms"], "--idle-exit-ms");
173
+ const root = args.root ?? defaultRoot();
174
+ const charterPath = resolve(charter);
175
+ if (!existsSync(charterPath)) throw new Error(`charter not found: ${charterPath}`);
176
+ const journal = openJournal(root, {});
177
+ try {
178
+ if (parent !== "-" && !journal.getNode(parent)) throw new Error(`no such parent node: ${parent}`);
179
+ const existing = journal.listNodes();
180
+ const stem = basename(charterPath).split(".")[0];
181
+ const nodeId = `n${existing.length + 1}-${slug(stem)}`;
182
+ if (journal.getNode(nodeId)) throw new Error(`node id already taken: ${nodeId}`);
183
+ journal.addNode({
184
+ nodeId,
185
+ parentId: parent === "-" ? null : parent,
186
+ projectRoot: args["project-root"] ? resolve(args["project-root"]) : process.cwd(),
187
+ charterPath,
188
+ driver: args.driver ?? "rpc",
189
+ tokenCap: args["token-cap"] ? Number(args["token-cap"]) : null,
190
+ spendCapUsd: args["spend-cap"] ? Number(args["spend-cap"]) : null,
191
+ });
192
+ console.log(`spawned ${nodeId} (parent ${parent}) charter ${charterPath}`);
193
+ } finally {
194
+ journal.close();
195
+ }
196
+ const supervisor = await ensureSupervisor(root, {
197
+ cap: args.cap ? Number(args.cap) : undefined,
198
+ driver: args["supervisor-driver"],
199
+ model: args.model,
200
+ piBin: args["pi-bin"],
201
+ idleExitMs,
202
+ extensions: args.extension ? [].concat(args.extension) : [],
203
+ });
204
+ const live = supervisor.started ? await waitForSupervisor(root) : { pid: supervisor.pid };
205
+ if (!live) {
206
+ throw new Error(`supervisor did not answer on ${controlSocketPath(root)}; see ${svrLogPath(root)}`);
207
+ }
208
+ // "(started)" is a claim about this command, so it holds only when the
209
+ // supervisor that answers is the one this command started. A process spawned
210
+ // over a live channel is refused by the incumbent, and the pid that answers
211
+ // names the supervisor that was already there.
212
+ const answeredBy = live.pid ?? supervisor.pid;
213
+ const startedHere = supervisor.started && answeredBy === supervisor.pid;
214
+ console.log(
215
+ `supervisor ${answeredBy}${startedHere ? " (started)" : " (already running)"} root ${resolveFleetRoot(root)}`,
216
+ );
217
+ // An idle exit belongs to the process that was started with it. Saying that
218
+ // when this command did not start one is the difference between a flag that
219
+ // was applied and a flag that was dropped quietly.
220
+ if (args["idle-exit-ms"] != null && !startedHere) {
221
+ console.log(
222
+ `note: --idle-exit-ms ${idleExitMs} was not applied: supervisor ${answeredBy} was already running and keeps its own idle exit`,
223
+ );
224
+ }
225
+ }
226
+
227
+ async function cmdStatus(args) {
228
+ const root = args.root ?? defaultRoot();
229
+ const live = await controlRequest(root, { op: "status" }, { timeoutMs: 1500 });
230
+ let status = live?.ok ? live.data : null;
231
+ let supervisor = "up";
232
+ if (!status) {
233
+ supervisor = "down";
234
+ const journal = openJournal(root, {});
235
+ try {
236
+ status = buildStatus(journal);
237
+ } finally {
238
+ journal.close();
239
+ }
240
+ }
241
+ if (args.json) {
242
+ console.log(JSON.stringify(status, null, 2));
243
+ return;
244
+ }
245
+ printStatus(status, { supervisor });
246
+ }
247
+
248
+ function printStatus(status, { supervisor }) {
249
+ const resident = status.resident ?? { pids: [], totalMb: 0 };
250
+ console.log(`fleet store ${status.store}`);
251
+ console.log(
252
+ `schema ${status.schemaVersion} supervisor ${supervisor} epoch ${status.epoch ?? "-"} cap ${status.cap ?? "-"} active ${status.active.length}`,
253
+ );
254
+ console.log(
255
+ `resident ${resident.totalMb} MB over ${resident.pids.length} pids ${resident.pids.map((row) => `${row.pid}:${row.mb}`).join(" ") || "-"}`,
256
+ );
257
+ // The drain's own account of the store. A deferral is the record of a pass
258
+ // that could not finish, and a completed one says so rather than reading as
259
+ // an open failure; a wait is a supervisor that is contending for the write
260
+ // lock, which is worth seeing before a drain ever gives up.
261
+ if (status.drain?.deferred) {
262
+ const deferred = status.drain.deferred;
263
+ const outcome = deferred.recoveredAt
264
+ ? `completed at ${new Date(deferred.recoveredAt).toISOString()}`
265
+ : "still outstanding";
266
+ console.log(
267
+ `drain deferred ${new Date(deferred.at).toISOString()}: ${deferred.attempts} attempt(s) in ${deferred.waitedMs} ms (${deferred.error}); ${outcome}`,
268
+ );
269
+ }
270
+ if (status.drain?.waited) {
271
+ const waited = status.drain.waited;
272
+ console.log(
273
+ `drain waited ${waited.waitedMs} ms over ${waited.attempts} attempt(s) for the store lock, last at ${new Date(waited.at).toISOString()}`,
274
+ );
275
+ }
276
+ console.log(`nodes ${status.nodes.length}:`);
277
+ for (const node of status.nodes) {
278
+ const effects = node.lastTurn ? JSON.stringify(node.lastTurn.effects) : "{}";
279
+ const undeliverable = node.undeliverable > 0 ? ` undeliverable ${node.undeliverable}` : "";
280
+ console.log(
281
+ ` ${node.nodeId.padEnd(22)} ${node.state.padEnd(17)} turns ${String(node.turns).padStart(3)} attempts ${node.attempts} session ${node.sessionId ?? "-"}`,
282
+ );
283
+ console.log(
284
+ ` last turn ${node.lastTurn ? `${node.lastTurn.turnId} ${node.lastTurn.kind} ${node.lastTurn.state}` : "-"} effects ${effects} pending ${node.pending}${undeliverable} lease ${node.lease ?? "-"}`,
285
+ );
286
+ if (node.openAsks.length > 0) console.log(` asks ${node.openAsks.join(", ")}`);
287
+ if (node.doneReason) console.log(` note ${node.doneReason}`);
288
+ }
289
+ if (status.asks.length > 0) {
290
+ console.log("open asks:");
291
+ for (const ask of status.asks) {
292
+ console.log(
293
+ ` ${ask.token} node ${ask.nodeId} priority ${ask.priority ?? 0} deadline ${new Date(ask.deadlineAt).toISOString()} ${ask.question}`,
294
+ );
295
+ console.log(` default ${ask.defaultAnswer ?? "-"}`);
296
+ }
297
+ }
298
+ if (status.fences?.length > 0) {
299
+ console.log("fences:");
300
+ for (const fence of status.fences) {
301
+ console.log(` turn ${fence.turnId} node ${fence.nodeId} pgid ${fence.pgid ?? "-"} killed ${fence.killed} (${fence.reason})`);
302
+ }
303
+ }
304
+ }
305
+
306
+ async function cmdInject(args) {
307
+ const [nodeId, ...rest] = args._;
308
+ const text = rest.join(" ").trim();
309
+ if (!nodeId || !text) throw new Error("usage: fleet inject <node> <text> [--token <ask-token>]");
310
+ const root = args.root ?? defaultRoot();
311
+ const reply = await controlRequest(root, {
312
+ op: "inject",
313
+ node: nodeId,
314
+ text,
315
+ token: args.token,
316
+ msgId: args["msg-id"],
317
+ });
318
+ if (reply?.ok) {
319
+ const data = reply.data;
320
+ // "Delivered" is a claim, and only a delivery event earns it. A steer's ack
321
+ // is pi saying it queued the text, so the row is still `recorded` when this
322
+ // prints: it must not read as though a model saw it.
323
+ if (data.steered) {
324
+ console.log(
325
+ `steered ${data.msgId} into ${nodeId} turn ${data.turnId} (the child queued it${data.disposition ? `, disposition ${data.disposition}` : ""})`,
326
+ );
327
+ console.log(" delivery is recorded when that turn runs the text; if it ends first, the next turn carries it");
328
+ } else {
329
+ console.log(`queued ${data.msgId} for ${nodeId} tier ${data.tier} (the next turn for this node carries it)`);
330
+ }
331
+ if (data.reason) console.log(`note: ${data.reason}`);
332
+ return;
333
+ }
334
+ if (reply && !reply.ok) throw new Error(reply.error);
335
+ // No supervisor listening: record the message so the next drive carries it.
336
+ const journal = openJournal(root, {});
337
+ try {
338
+ const node = journal.getNode(nodeId);
339
+ if (!node) throw new Error(`no such node: ${nodeId}`);
340
+ // The journal alone can decide this half: a done node is never driven again.
341
+ // The attempt bound is the running supervisor's policy and is not visible
342
+ // here, so a failed node is queued and the supervisor's sweep stamps it
343
+ // `undeliverable` if the bound is what keeps it from running.
344
+ const retired = undeliverableReason(node);
345
+ if (retired) throw new Error(`cannot queue a message for ${nodeId}: ${retired}; no turn will ever carry it`);
346
+ let kind = "user";
347
+ if (args.token) {
348
+ const ask = journal.getAsk(args.token);
349
+ if (!ask || ask.state !== "open") throw new Error(`no open ask: ${args.token}`);
350
+ journal.resolveAsk(args.token, { answerText: text, answerSource: "fleet-inject" });
351
+ if (journal.getNode(nodeId).state === "waiting_on_human") journal.setNodeState(nodeId, "settled");
352
+ kind = "answer";
353
+ }
354
+ const message = journal.addMessage({
355
+ msgId: args["msg-id"] ?? `m-${randomBytes(6).toString("hex")}`,
356
+ nodeId,
357
+ kind,
358
+ body: text,
359
+ token: args.token,
360
+ });
361
+ console.log(`recorded ${message.msg_id} for ${nodeId} tier C (no supervisor running; the next turn this node is driven for carries it)`);
362
+ } finally {
363
+ journal.close();
364
+ }
365
+ }
366
+
367
+ async function cmdAsk(args) {
368
+ const [nodeId, ...rest] = args._;
369
+ const question = rest.join(" ").trim();
370
+ if (!nodeId || !question) throw new Error("usage: fleet ask <node> <question> [--default <answer>] [--ttl-seconds N]");
371
+ const root = args.root ?? defaultRoot();
372
+ const journal = openJournal(root, {});
373
+ try {
374
+ const node = journal.getNode(nodeId);
375
+ if (!node) throw new Error(`no such node: ${nodeId}`);
376
+ if (node.state === "done") throw new Error(`node is done: ${nodeId}`);
377
+ const ttlMs = (args["ttl-seconds"] ? Number(args["ttl-seconds"]) : 600) * 1000;
378
+ const token = `ask-${randomBytes(6).toString("hex")}`;
379
+ const ask = journal.recordAsk({
380
+ token,
381
+ nodeId,
382
+ priority: args.priority ? Number(args.priority) : 0,
383
+ question,
384
+ defaultAnswer: args.default ?? DEFAULT_ANSWER,
385
+ deadlineAt: Date.now() + ttlMs,
386
+ });
387
+ journal.setNodeState(nodeId, "waiting_on_human");
388
+ console.log(`ask ${ask.token} for ${nodeId}`);
389
+ console.log(` priority: ${ask.priority}`);
390
+ console.log(` question: ${ask.question}`);
391
+ console.log(` default: ${ask.default_answer}`);
392
+ console.log(` deadline: ${new Date(ask.deadline_at).toISOString()}`);
393
+ console.log(` answer: fleet inject ${nodeId} "<answer>" --token ${ask.token}`);
394
+ } finally {
395
+ journal.close();
396
+ }
397
+ }
398
+
399
+ // ── argv ────────────────────────────────────────────────────────────────────
400
+
401
+ function parseArgs(argv) {
402
+ const args = { _: [] };
403
+ for (let i = 0; i < argv.length; i += 1) {
404
+ const token = argv[i];
405
+ if (!token.startsWith("--")) {
406
+ args._.push(token);
407
+ continue;
408
+ }
409
+ const [key, inline] = token.slice(2).split("=");
410
+ if (inline != null) {
411
+ args[key] = inline;
412
+ continue;
413
+ }
414
+ const next = argv[i + 1];
415
+ if (next == null || next.startsWith("--")) {
416
+ args[key] = true;
417
+ continue;
418
+ }
419
+ args[key] = next;
420
+ i += 1;
421
+ }
422
+ return args;
423
+ }
424
+
425
+ const USAGE = `pi-braid-fleet: the supervisor fleet's operator command.
426
+
427
+ The fleet is one supervisor process driving local node sessions against one
428
+ SQLite journal. It is not the worker registry \`orchestrate\` keeps for parallel
429
+ agents; that pool is a different thing with the same word in its prose.
430
+
431
+ commands:
432
+ spawn <parent|-> <charter> [--cap N] [--model p/m] [--token-cap N] [--idle-exit-ms N]
433
+ status [--json]
434
+ inject <node> <text> [--token <ask-token>]
435
+ ask <node> <question> [--default <answer>] [--priority N] [--ttl-seconds N]
436
+ common: --root <fleet-root> (default $PI_FLEET_ROOT or <cwd>/.fleet)
437
+
438
+ spawn's --cap, --model, --pi-bin, --extension, --supervisor-driver and
439
+ --idle-exit-ms configure the supervisor this command starts; a supervisor that
440
+ is already running keeps the flags it was started with, and spawn says so.
441
+
442
+ exit: 0 success, 1 the command failed, 2 unknown command or bad usage.
443
+ guide: docs/FLEET.md, in this package.`;
444
+
445
+ async function main() {
446
+ const [command, ...rest] = process.argv.slice(2);
447
+ // A help request is an answer, not a refusal: usage on stdout, exit 0. That
448
+ // includes the bare invocation, because an operator who types the command
449
+ // name and nothing else is asking what it does. An unknown word stays a
450
+ // refusal (stderr, exit 2): that caller asked for something that is not here.
451
+ if (command == null || command === "--help" || command === "-h" || command === "help") {
452
+ console.log(USAGE);
453
+ return undefined;
454
+ }
455
+ const args = parseArgs(rest);
456
+ switch (command) {
457
+ case "spawn":
458
+ return cmdSpawn(args);
459
+ case "status":
460
+ return cmdStatus(args);
461
+ case "inject":
462
+ return cmdInject(args);
463
+ case "ask":
464
+ return cmdAsk(args);
465
+ default:
466
+ console.error(`pi-braid-fleet: unknown command "${command}"\n`);
467
+ console.error(USAGE);
468
+ process.exitCode = 2;
469
+ return undefined;
470
+ }
471
+ }
472
+
473
+ /**
474
+ * Is this module the process's entry point?
475
+ *
476
+ * npm installs the `bin` entry as a symlink into `node_modules/.bin`, and the
477
+ * kernel does not rewrite argv: `process.argv[1]` stays the symlink while
478
+ * `import.meta.url` names the file it points at. Comparing the two as spelled
479
+ * makes the installed command load this module, match nothing, and exit 0 with
480
+ * no output at all, so the comparison is on real paths.
481
+ */
482
+ function isEntryPoint() {
483
+ const entry = process.argv[1];
484
+ if (!entry) return false;
485
+ const self = fileURLToPath(import.meta.url);
486
+ try {
487
+ return realpathSync(entry) === realpathSync(self);
488
+ } catch {
489
+ // A path that cannot be resolved cannot be another spelling of this file.
490
+ return resolve(entry) === self;
491
+ }
492
+ }
493
+
494
+ if (isEntryPoint()) {
495
+ main().catch((error) => {
496
+ console.error(`fleet: ${error.message}`);
497
+ process.exitCode = 1;
498
+ });
499
+ }