@llblab/pi-actors 0.22.5 → 0.24.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 (180) hide show
  1. package/AGENTS.md +125 -59
  2. package/BACKLOG.md +88 -403
  3. package/CHANGELOG.md +39 -0
  4. package/README.md +14 -1
  5. package/dist/fixtures/protocol/actor-message-branch.json +13 -0
  6. package/dist/fixtures/protocol/artifact-manifest.json +9 -0
  7. package/dist/fixtures/protocol/mailbox-contract.json +15 -0
  8. package/dist/fixtures/protocol/recipe-summary.json +16 -0
  9. package/dist/fixtures/protocol/room-message.json +11 -0
  10. package/dist/fixtures/protocol/room-roster.json +11 -0
  11. package/dist/fixtures/protocol/run-inbox-message.json +9 -0
  12. package/dist/fixtures/protocol/run-outbox-event.json +9 -0
  13. package/dist/fixtures/protocol/run-state.json +10 -0
  14. package/dist/index.js +18 -2
  15. package/dist/lib/actor-inspector-tui.d.ts +4 -0
  16. package/dist/lib/actor-inspector-tui.js +58 -44
  17. package/dist/lib/actor-rooms.d.ts +16 -0
  18. package/dist/lib/actor-rooms.js +123 -28
  19. package/dist/lib/actor-worker.d.ts +13 -0
  20. package/dist/lib/actor-worker.js +86 -0
  21. package/dist/lib/async-runner.d.ts +5 -0
  22. package/dist/lib/async-runner.js +134 -0
  23. package/dist/lib/async-runs.d.ts +34 -2
  24. package/dist/lib/async-runs.js +224 -50
  25. package/dist/lib/build-dist.d.ts +5 -0
  26. package/dist/lib/build-dist.js +24 -0
  27. package/dist/lib/command-templates.js +5 -5
  28. package/dist/lib/conformance.d.ts +12 -0
  29. package/dist/lib/conformance.js +28 -0
  30. package/dist/lib/coordinator.d.ts +5 -0
  31. package/dist/lib/coordinator.js +557 -0
  32. package/dist/lib/limits.d.ts +11 -0
  33. package/dist/lib/limits.js +11 -0
  34. package/dist/lib/locker.d.ts +5 -0
  35. package/dist/lib/locker.js +310 -0
  36. package/dist/lib/mailbox-loop.d.ts +41 -0
  37. package/dist/lib/mailbox-loop.js +62 -0
  38. package/dist/lib/observability.d.ts +2 -2
  39. package/dist/lib/observability.js +57 -57
  40. package/dist/lib/output.js +4 -5
  41. package/dist/lib/prompts.d.ts +1 -1
  42. package/dist/lib/prompts.js +1 -1
  43. package/dist/lib/recipe-discovery.js +1 -0
  44. package/dist/lib/recipe-references.d.ts +11 -2
  45. package/dist/lib/recipe-references.js +29 -4
  46. package/dist/lib/recipe-usage.d.ts +2 -1
  47. package/dist/lib/recipe-usage.js +15 -3
  48. package/dist/lib/recipe-utils.d.ts +5 -0
  49. package/dist/lib/recipe-utils.js +385 -0
  50. package/dist/lib/runtime-notifier.js +3 -7
  51. package/dist/lib/runtime.js +12 -2
  52. package/dist/lib/state-readers.d.ts +21 -0
  53. package/dist/lib/state-readers.js +74 -0
  54. package/dist/lib/tools.js +198 -39
  55. package/dist/lib/validate-recipe.d.ts +6 -0
  56. package/dist/lib/validate-recipe.js +104 -0
  57. package/dist/recipes/actor-worker.json +35 -0
  58. package/dist/recipes/coordinator-locker.json +45 -0
  59. package/dist/recipes/lens-swarm.json +66 -0
  60. package/dist/recipes/locker.json +45 -0
  61. package/dist/recipes/music-player.json +38 -0
  62. package/dist/recipes/pipeline-architect-coordinator.json +95 -0
  63. package/dist/recipes/pipeline-artifact-bundle.json +100 -0
  64. package/dist/recipes/pipeline-artifact-report.json +58 -0
  65. package/dist/recipes/pipeline-artifact-write.json +72 -0
  66. package/dist/recipes/pipeline-async-run-ops.json +70 -0
  67. package/dist/recipes/pipeline-checkpoint-continuation.json +67 -0
  68. package/dist/recipes/pipeline-development-tasking.json +81 -0
  69. package/dist/recipes/pipeline-docs-maintenance.json +80 -0
  70. package/dist/recipes/pipeline-media-library.json +59 -0
  71. package/dist/recipes/pipeline-quorum-review.json +79 -0
  72. package/dist/recipes/pipeline-release-readiness.json +110 -0
  73. package/dist/recipes/pipeline-release-summary.json +88 -0
  74. package/dist/recipes/pipeline-repo-health.json +89 -0
  75. package/dist/recipes/pipeline-research-synthesis.json +94 -0
  76. package/dist/recipes/pipeline-review-readiness.json +54 -0
  77. package/dist/recipes/pipeline-room-swarm.json +50 -0
  78. package/dist/recipes/subagent-artifact.json +32 -0
  79. package/dist/recipes/subagent-checkpoint.json +33 -0
  80. package/dist/recipes/subagent-conflict-report.json +32 -0
  81. package/dist/recipes/subagent-contradiction-map.json +33 -0
  82. package/dist/recipes/subagent-critic.json +35 -0
  83. package/dist/recipes/subagent-evidence-map.json +33 -0
  84. package/dist/recipes/subagent-followup.json +33 -0
  85. package/dist/recipes/subagent-judge.json +33 -0
  86. package/dist/recipes/subagent-merge.json +33 -0
  87. package/dist/recipes/subagent-message.json +34 -0
  88. package/dist/recipes/subagent-normalize.json +31 -0
  89. package/dist/recipes/subagent-plan.json +33 -0
  90. package/dist/recipes/subagent-prompt.json +28 -0
  91. package/dist/recipes/subagent-quorum.json +43 -0
  92. package/dist/recipes/subagent-review-coordinator.json +114 -0
  93. package/dist/recipes/subagent-review.json +37 -0
  94. package/dist/recipes/subagent-task-card.json +35 -0
  95. package/dist/recipes/subagent-tools.json +27 -0
  96. package/dist/recipes/subagent-verify.json +34 -0
  97. package/dist/recipes/subagents-prompts.json +51 -0
  98. package/dist/recipes/utility-actor-message.json +23 -0
  99. package/dist/recipes/utility-artifact-manifest.json +16 -0
  100. package/dist/recipes/utility-artifact-write.json +16 -0
  101. package/dist/recipes/utility-changelog-head.json +11 -0
  102. package/dist/recipes/utility-changelog-section.json +13 -0
  103. package/dist/recipes/utility-coordinator-lock-snapshot.json +13 -0
  104. package/dist/recipes/utility-git-log.json +11 -0
  105. package/dist/recipes/utility-git-status.json +9 -0
  106. package/dist/recipes/utility-jsonl-tail.json +10 -0
  107. package/dist/recipes/utility-markdown-index.json +14 -0
  108. package/dist/recipes/utility-package-summary.json +11 -0
  109. package/dist/recipes/utility-playlist-build.json +17 -0
  110. package/dist/recipes/utility-playlist-scan.json +11 -0
  111. package/dist/recipes/utility-run-ops-snapshot.json +17 -0
  112. package/dist/recipes/utility-run-state-files.json +13 -0
  113. package/dist/recipes/utility-run-summary.json +11 -0
  114. package/dist/recipes/utility-skill-summary.json +13 -0
  115. package/dist/recipes/utility-validate-recipe.json +13 -0
  116. package/dist/recipes/utility-validation-wrapper.json +13 -0
  117. package/dist/scripts/actor-worker.mjs +31 -0
  118. package/dist/scripts/async-runner.mjs +31 -0
  119. package/dist/scripts/build-dist.mjs +25 -0
  120. package/dist/scripts/conformance.mjs +33 -0
  121. package/dist/scripts/coordinator.mjs +31 -0
  122. package/dist/scripts/locker.mjs +33 -0
  123. package/dist/scripts/music-player.mjs +964 -0
  124. package/dist/scripts/recipe-utils.mjs +31 -0
  125. package/dist/scripts/validate-recipe.mjs +34 -0
  126. package/dist/skills/actors/SKILL.md +375 -0
  127. package/dist/skills/swarm/SKILL.md +467 -0
  128. package/dist/skills/swarm/references/development-swarm.md +596 -0
  129. package/docs/actor-messages.md +2 -2
  130. package/docs/async-runs.md +13 -1
  131. package/docs/template-recipes.md +2 -2
  132. package/docs/tool-registry.md +0 -1
  133. package/fixtures/protocol/actor-message-branch.json +13 -0
  134. package/fixtures/protocol/artifact-manifest.json +9 -0
  135. package/fixtures/protocol/mailbox-contract.json +15 -0
  136. package/fixtures/protocol/recipe-summary.json +16 -0
  137. package/fixtures/protocol/room-message.json +11 -0
  138. package/fixtures/protocol/room-roster.json +11 -0
  139. package/fixtures/protocol/run-inbox-message.json +9 -0
  140. package/fixtures/protocol/run-outbox-event.json +9 -0
  141. package/fixtures/protocol/run-state.json +10 -0
  142. package/index.ts +21 -0
  143. package/lib/actor-inspector-tui.ts +138 -59
  144. package/lib/actor-rooms.ts +241 -60
  145. package/lib/actor-worker.ts +118 -0
  146. package/lib/async-runner.ts +173 -0
  147. package/lib/async-runs.ts +302 -53
  148. package/lib/build-dist.ts +30 -0
  149. package/lib/command-templates.ts +5 -5
  150. package/lib/conformance.ts +46 -0
  151. package/lib/coordinator.ts +649 -0
  152. package/lib/limits.ts +12 -0
  153. package/lib/locker.ts +340 -0
  154. package/lib/mailbox-loop.ts +148 -0
  155. package/lib/observability.ts +34 -23
  156. package/lib/output.ts +4 -6
  157. package/lib/prompts.ts +1 -1
  158. package/lib/recipe-discovery.ts +1 -0
  159. package/lib/recipe-references.ts +57 -6
  160. package/lib/recipe-usage.ts +31 -4
  161. package/lib/recipe-utils.ts +486 -0
  162. package/lib/runtime-notifier.ts +4 -6
  163. package/lib/runtime.ts +31 -7
  164. package/lib/state-readers.ts +93 -0
  165. package/lib/tools.ts +297 -58
  166. package/lib/validate-recipe.ts +110 -0
  167. package/package.json +11 -2
  168. package/recipes/actor-worker.json +35 -0
  169. package/recipes/pipeline-quorum-review.json +12 -7
  170. package/scripts/actor-worker.mjs +31 -0
  171. package/scripts/async-runner.mjs +11 -195
  172. package/scripts/build-dist.mjs +25 -0
  173. package/scripts/conformance.mjs +33 -0
  174. package/scripts/coordinator.mjs +19 -616
  175. package/scripts/locker.mjs +23 -322
  176. package/scripts/music-player.mjs +21 -2
  177. package/scripts/recipe-utils.mjs +20 -467
  178. package/scripts/validate-recipe.mjs +23 -113
  179. package/skills/actors/SKILL.md +7 -4
  180. package/skills/swarm/SKILL.md +3 -1
@@ -1,628 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import { spawn } from "node:child_process";
3
- import { existsSync } from "node:fs";
4
- import { mkdir, readFile, rm, stat, writeFile } from "node:fs/promises";
5
- import { createConnection } from "node:net";
6
-
7
- function arg(name, fallback = "") {
8
- const prefix = `--${name}=`;
9
- const value = process.argv.find((item) => item.startsWith(prefix));
10
- return value ? value.slice(prefix.length) : fallback;
11
- }
12
-
13
- function numberArg(name, fallback) {
14
- const value = Number(arg(name, String(fallback)));
15
- return Number.isFinite(value) && value >= 0 ? value : fallback;
16
- }
17
-
18
- function boolArg(name, fallback = false) {
19
- const value = arg(name, String(fallback)).trim().toLowerCase();
20
- return ["1", "true", "yes", "on"].includes(value);
21
- }
22
-
23
- function normalizeRoles(value) {
24
- if (!Array.isArray(value)) throw new Error("roles must be an array");
25
- return value.map((role, index) => ({
26
- name: String(role.name ?? `actor-${index + 1}`),
27
- persona: String(role.persona ?? role.role ?? "room participant"),
28
- }));
29
- }
30
-
31
- function parseRoles(raw) {
32
- if (!raw.trim()) return defaultRoles;
33
- try {
34
- return normalizeRoles(JSON.parse(raw));
35
- } catch {
36
- return raw.split(",").map((item, index) => ({
37
- name: item.trim() || `actor-${index + 1}`,
38
- persona: "room participant",
39
- }));
40
- }
41
- }
42
-
43
- async function loadRoles(raw, path) {
44
- if (path.trim())
45
- return normalizeRoles(JSON.parse(await readFile(path, "utf8")));
46
- return parseRoles(raw);
47
- }
48
-
49
- function shellQuote(value) {
50
- return `'${String(value).replaceAll("'", "'\\''")}'`;
51
- }
52
-
53
- function agentDir() {
54
- return process.env.PI_CODING_AGENT_DIR || `${process.env.HOME}/.pi/agent`;
55
- }
56
-
57
- function runStateDir(runId) {
58
- return `${agentDir()}/tmp/pi-actors/runs/${runId}`;
59
- }
60
-
61
- async function sleep(ms) {
62
- await new Promise((resolve) => setTimeout(resolve, ms));
63
- }
64
-
65
- const STATE_LOCK_MAX_AGE_MS = 5 * 60 * 1000;
66
- const STATE_LOCK_TIMEOUT_MS = 5000;
67
-
68
- async function waitForPath(path, timeoutMs = 5000) {
69
- const started = Date.now();
70
- while (!existsSync(path)) {
71
- if (Date.now() - started > timeoutMs)
72
- throw new Error(`timed out waiting for ${path}`);
73
- await sleep(50);
74
- }
75
- }
76
-
77
- async function acquireStateLock(parentDir, name, label) {
78
- await mkdir(parentDir, { recursive: true });
79
- const lockDir = `${parentDir}/${name}`;
80
- const started = Date.now();
81
- while (true) {
82
- try {
83
- await mkdir(lockDir);
84
- await writeFile(
85
- `${lockDir}/owner.json`,
86
- `${JSON.stringify({ pid: process.pid, created_at: new Date().toISOString() })}\n`,
87
- "utf8",
88
- );
89
- return async () => rm(lockDir, { recursive: true, force: true });
90
- } catch (error) {
91
- try {
92
- const current = await stat(lockDir);
93
- if (Date.now() - current.mtimeMs > STATE_LOCK_MAX_AGE_MS) {
94
- await rm(lockDir, { recursive: true, force: true });
95
- continue;
96
- }
97
- } catch {
98
- continue;
99
- }
100
- if (Date.now() - started > STATE_LOCK_TIMEOUT_MS) {
101
- throw new Error(`${label} lock timed out.`, { cause: error });
102
- }
103
- await sleep(10);
104
- }
105
- }
106
- }
107
-
108
- async function acquireBranchInboxLock(runId, branchName) {
109
- return acquireStateLock(
110
- `${runStateDir(runId)}/branches/${branchName}`,
111
- ".inbox.lock",
112
- `Branch inbox ${branchName}`,
113
- );
114
- }
115
-
116
- async function readLockerControl(locker) {
117
- const controlJson = `${locker.stateDir}/control.json`;
118
- await waitForPath(controlJson);
119
- return JSON.parse(await readFile(controlJson, "utf8"));
120
- }
121
-
122
- function writeNamedPipeLine(path, line) {
123
- return new Promise((resolve, reject) => {
124
- const socket = createConnection(path);
125
- let settled = false;
126
- const finish = (error) => {
127
- if (settled) return;
128
- settled = true;
129
- if (error) reject(error);
130
- else resolve();
131
- };
132
- socket.on("error", finish);
133
- socket.on("connect", () => socket.end(line, () => finish()));
134
- });
135
- }
136
-
137
- async function writeLockerMessage(locker, message) {
138
- if (!locker) return;
139
- const control = locker.control ?? (await readLockerControl(locker));
140
- locker.control = control;
141
- const line = `${JSON.stringify(message)}\n`;
142
- if (control.type === "named-pipe")
143
- await writeNamedPipeLine(control.path, line);
144
- else await writeFile(control.path, line, { flag: "a" });
145
- await sleep(50);
146
- }
147
-
148
- async function startLocker(config) {
149
- if (!config.locker) return undefined;
150
- const lockerStateDir = `${runStateDir(config.runId)}/locker`;
151
- await mkdir(lockerStateDir, { recursive: true });
152
- const child = spawn(
153
- new URL("./locker.mjs", import.meta.url).pathname,
154
- [
155
- "serve",
156
- "--state-dir",
157
- lockerStateDir,
158
- "--lease-ms",
159
- String(config.lockerLeaseMs),
160
- ],
161
- {
162
- env: { ...process.env, run_id: config.runId },
163
- stdio: ["ignore", "pipe", "pipe"],
164
- },
165
- );
166
- child.stdout.on("data", (chunk) => process.stdout.write(`[locker] ${chunk}`));
167
- child.stderr.on("data", (chunk) => process.stderr.write(`[locker] ${chunk}`));
168
- const locker = { child, stateDir: lockerStateDir };
169
- locker.control = await readLockerControl(locker);
170
- await writeLockerMessage(locker, {
171
- type: "lock.enqueue",
172
- body: {
173
- id: "coordinator-artifact",
174
- task: "Own final artifact synthesis",
175
- resources: [config.artifactPath || "artifact"],
176
- },
177
- });
178
- return locker;
179
- }
180
-
181
- async function stopLocker(locker) {
182
- if (!locker) return;
183
- try {
184
- await writeLockerMessage(locker, { type: "control.stop", body: {} });
185
- await sleep(100);
186
- } finally {
187
- if (!locker.child.killed) locker.child.kill("SIGTERM");
188
- }
189
- }
190
-
191
- function runPi(prompt, model, thinking) {
192
- return new Promise((resolve) => {
193
- const args = [
194
- "--tools",
195
- "inspect,message",
196
- "--no-context-files",
197
- "--no-skills",
198
- "--no-session",
199
- ];
200
- if (model) {
201
- args.push("--model", model);
202
- }
203
- if (thinking) {
204
- args.push("--thinking", thinking);
205
- }
206
- args.push("-p", prompt);
207
-
208
- const child = spawn("pi", args, { stdio: ["ignore", "pipe", "pipe"] });
209
- let stdout = "";
210
- let stderr = "";
211
- child.stdout.on("data", (chunk) => {
212
- stdout += chunk;
213
- });
214
- child.stderr.on("data", (chunk) => {
215
- stderr += chunk;
216
- });
217
- child.on("close", (code) => resolve({ code, stdout, stderr }));
218
- child.on("error", (error) =>
219
- resolve({ code: 1, stdout, stderr: String(error) }),
220
- );
221
- });
222
- }
223
-
224
- async function readRoomTranscript(config) {
225
- const messagesPath = `${runStateDir(config.runId)}/rooms/main/messages.jsonl`;
226
- try {
227
- const raw = await readFile(messagesPath, "utf8");
228
- return raw
229
- .split("\n")
230
- .filter(Boolean)
231
- .slice(-160)
232
- .map((line) => {
233
- try {
234
- const message = JSON.parse(line);
235
- const from = String(message.from || "unknown").replace(
236
- /^branch:[^/]+\//,
237
- "",
238
- );
239
- const type = String(message.type || "message");
240
- const body =
241
- typeof message.body === "string"
242
- ? message.body
243
- : JSON.stringify(message.body ?? "");
244
- return `${from} [${type}]: ${body}`;
245
- } catch {
246
- return line;
247
- }
248
- })
249
- .join("\n");
250
- } catch {
251
- return "";
252
- }
253
- }
254
-
255
- async function synthesize(config, locker) {
256
- if (!config.artifactPath) return;
257
- if (locker) {
258
- await writeLockerMessage(locker, {
259
- type: "lock.claim",
260
- body: { owner: "coordinator:synthesizer" },
261
- });
262
- }
263
- const transcript = await readRoomTranscript(config);
264
- const prompt = `Synthesize this transcript into a concise Markdown artifact. Mission: ${config.mission}. Include: Title, Consensus, Roles, Protocol, Final Artifact Shape, Next Actions, Open Questions. Use only the transcript evidence below.\n\nTRANSCRIPT:\n${transcript.slice(-24000)}`;
265
- const result = await runPi(prompt, config.model, config.thinking);
266
- await writeFile(
267
- config.artifactPath,
268
- result.stdout.trim()
269
- ? result.stdout
270
- : "# Synthesis Artifact\n\nNo synthesis output.\n",
271
- "utf8",
272
- );
273
- if (locker) {
274
- await writeLockerMessage(locker, {
275
- type: "lock.complete",
276
- body: { id: "coordinator-artifact", artifact: config.artifactPath },
277
- });
278
- await writeLockerMessage(locker, {
279
- type: "lock.release",
280
- body: { resource: config.artifactPath },
281
- });
282
- }
283
- process.stdout.write(`artifact=${config.artifactPath}\n`);
284
- }
285
-
286
- async function readInboxLines(inboxPath) {
287
- if (!existsSync(inboxPath)) return [];
288
- const content = await readFile(inboxPath, "utf8");
289
- return content
290
- .split("\n")
291
- .filter(Boolean)
292
- .map((line) => JSON.parse(line));
293
- }
294
-
295
- async function writeInboxMessages(inboxPath, messages) {
296
- await writeFile(
297
- inboxPath,
298
- messages.map((message) => JSON.stringify(message)).join("\n") + "\n",
299
- "utf8",
300
- );
301
- }
302
-
303
- async function mutateBranchInbox(runId, branchName, mutate, fallback) {
304
- const inboxPath = `${runStateDir(runId)}/branches/${branchName}/inbox.jsonl`;
305
- const releaseLock = await acquireBranchInboxLock(runId, branchName);
306
- try {
307
- const messages = await readInboxLines(inboxPath);
308
- const result = mutate(messages);
309
- if (result.messages) await writeInboxMessages(inboxPath, result.messages);
310
- return result.value;
311
- } catch {
312
- return fallback;
313
- } finally {
314
- await releaseLock();
315
- }
316
- }
317
-
318
- async function claimQueuedInboxMessages(runId, branchName) {
319
- return mutateBranchInbox(
320
- runId,
321
- branchName,
322
- (messages) => {
323
- const claimedAt = new Date().toISOString();
324
- const queuedMessages = [];
325
- const updated = messages.map((msg, index) => {
326
- if (msg.status !== "queued" && msg.status) return msg;
327
- const claimed = {
328
- ...msg,
329
- claimed_at: claimedAt,
330
- id: msg.id || `legacy-${Date.now()}-${index}`,
331
- status: "claimed",
332
- };
333
- queuedMessages.push(claimed);
334
- return claimed;
335
- });
336
- return {
337
- messages: queuedMessages.length > 0 ? updated : undefined,
338
- value: queuedMessages,
339
- };
340
- },
341
- [],
342
- );
343
- }
344
-
345
- async function updateInboxMessagesStatus(runId, branchName, ids, status) {
346
- await mutateBranchInbox(runId, branchName, (messages) => {
347
- const idSet = new Set(ids);
348
- const updated = messages.map((msg) => {
349
- if (!msg.id || !idSet.has(msg.id)) return msg;
350
- return { ...msg, [`${status}_at`]: new Date().toISOString(), status };
351
- });
352
- return { messages: updated, value: undefined };
353
- });
354
- }
355
-
356
- async function executeParticipantPrompt(role, basePrompt, config) {
357
- const branchName = role.name;
358
- const queuedMessages = await claimQueuedInboxMessages(
359
- config.runId,
360
- branchName,
361
- );
362
-
363
- let finalPrompt = basePrompt;
364
- const claimedIds = [];
365
-
366
- if (queuedMessages.length > 0) {
367
- let inboxSection =
368
- "\n\nDIRECT INBOX MESSAGES FOR YOU (queued mailbox work):\n";
369
- for (const msg of queuedMessages) {
370
- const bodyText =
371
- typeof msg.body === "string"
372
- ? msg.body
373
- : JSON.stringify(msg.body ?? "");
374
- inboxSection += `- From: ${msg.from || "unknown"} (Type: ${msg.type || "message"})\n Body: ${bodyText}\n`;
375
- if (msg.id) claimedIds.push(msg.id);
376
- }
377
- inboxSection +=
378
- "\nPlease acknowledge and address these direct messages in your response.\n";
379
- finalPrompt += inboxSection;
380
- }
381
-
382
- const result = await runPi(finalPrompt, config.model, config.thinking);
383
-
384
- if (claimedIds.length > 0) {
385
- const finalStatus = result.code === 0 ? "handled" : "failed";
386
- await updateInboxMessagesStatus(
387
- config.runId,
388
- branchName,
389
- claimedIds,
390
- finalStatus,
391
- );
392
- }
393
-
394
- return result;
395
- }
396
-
397
- async function participantRound(role, round, config) {
398
- const displayName = role.name;
399
- const address = `branch:${config.runId}/${role.name}`;
400
- const prompt = `You are ${displayName} (${address}), ${role.persona}. Mission: ${config.mission}. Round ${round}/${config.rounds}. First call inspect target=${config.room} view=previews lines=30 and inspect target=${config.room} view=contacts. Then call message once to ${config.room} from ${address} type=chat.message. Body: 2-4 sentences that react to a named participant, propose the next coordination step, and refine the shared artifact. Use contacts for peer names and addresses. End stdout with summary <=160 chars.`;
401
- const result = await executeParticipantPrompt(role, prompt, config);
402
- process.stdout.write(
403
- `[${role.name} round ${round}] code=${result.code}\n${result.stdout}\n`,
404
- );
405
- if (result.stderr.trim())
406
- process.stderr.write(`[${role.name} round ${round}] ${result.stderr}\n`);
407
- }
408
-
409
- async function participantJoin(role, config) {
410
- const displayName = role.name;
411
- const address = `branch:${config.runId}/${role.name}`;
412
- const joinPrompt = `You are ${displayName}, ${role.persona}. Mission: ${config.mission}. Call tool message exactly once with to=${shellQuote(config.room)}, from=${shellQuote(address)}, type='actor.join', summary='${displayName} joined', body JSON {"role":${JSON.stringify(role.persona)},"display":${JSON.stringify(displayName)},"caps":["coordination","synthesis"],"claim":"coordinate on mission"}. Then print one short line.`;
413
- await runPi(joinPrompt, config.model, config.thinking);
414
- }
415
2
 
416
- async function participantLeave(role, config) {
417
- const displayName = role.name;
418
- const address = `branch:${config.runId}/${role.name}`;
419
- const leavePrompt = `Call tool message exactly once with to=${shellQuote(config.room)}, from=${shellQuote(address)}, type='actor.leave', summary='${displayName} left', body='finished coordinated work'. Then print goodbye.`;
420
- await runPi(leavePrompt, config.model, config.thinking);
421
- }
422
-
423
- // 1. consensus / swarm mode: iterative chat in a room
424
- async function runConsensus(config, locker) {
425
- await Promise.all(config.roles.map((role) => participantJoin(role, config)));
426
- for (let round = 1; round <= config.rounds; round += 1) {
427
- await Promise.all(
428
- config.roles.map((role) => participantRound(role, round, config)),
429
- );
430
- if (round < config.rounds && config.delay > 0)
431
- await sleep(config.delay * 1000);
432
- }
433
- await Promise.all(config.roles.map((role) => participantLeave(role, config)));
434
- }
435
-
436
- // 2. pipeline mode: sequential step-by-step
437
- async function runPipeline(config, locker) {
438
- for (const role of config.roles) {
439
- await participantJoin(role, config);
440
- for (let round = 1; round <= config.rounds; round += 1) {
441
- await participantRound(role, round, config);
442
- if (round < config.rounds && config.delay > 0)
443
- await sleep(config.delay * 1000);
444
- }
445
- await participantLeave(role, config);
446
- }
447
- }
448
-
449
- // 3. fanout mode: run completely parallel independent processes
450
- async function runFanout(config, locker) {
451
- await Promise.all(
452
- config.roles.map(async (role) => {
453
- await participantJoin(role, config);
454
- for (let round = 1; round <= config.rounds; round += 1) {
455
- await participantRound(role, round, config);
456
- if (round < config.rounds && config.delay > 0)
457
- await sleep(config.delay * 1000);
458
- }
459
- await participantLeave(role, config);
460
- }),
461
- );
462
- }
463
-
464
- // 4. pool mode: dynamic task pulling from the locker queue
465
- async function runPool(config, locker) {
466
- if (!locker) {
467
- throw new Error("Pool mode requires locker enabled (--locker=true)");
468
- }
469
- // Enqueue a set of sub-tasks based on the mission splits (for demo/simulation, we enqueue 3 sub-tasks)
470
- for (let index = 1; index <= 3; index += 1) {
471
- await writeLockerMessage(locker, {
472
- type: "lock.enqueue",
473
- body: {
474
- id: `subtask-${index}`,
475
- task: `Execute subtask ${index} under mission: ${config.mission}`,
476
- resources: [`resource-${index}`],
477
- },
478
- });
479
- }
480
-
481
- // Workers concurrently poll task queue
482
- await Promise.all(
483
- config.roles.map(async (role) => {
484
- const address = `branch:${config.runId}/${role.name}`;
485
- await participantJoin(role, config);
486
-
487
- while (true) {
488
- // Dequeue/Claim a task from the locker
489
- await writeLockerMessage(locker, {
490
- type: "lock.claim",
491
- body: { owner: role.name },
492
- });
493
- await sleep(100);
494
-
495
- // Check locks and queue state from locker snapshot
496
- const lockerData = await readJsonFile(`${locker.stateDir}/locks.json`);
497
- const assignedTask = Object.values(lockerData).find(
498
- (lock) => lock.owner === role.name,
499
- );
3
+ /**
4
+ * Multi-actor coordinator helper shim.
5
+ *
6
+ * Runtime logic lives in lib/coordinator.ts and is compiled to
7
+ * dist/lib/coordinator.js for installed JS-only packages.
8
+ */
500
9
 
501
- if (!assignedTask) {
502
- // No task assigned or queue is empty
503
- break;
504
- }
505
-
506
- const taskId = assignedTask.task;
507
- const prompt = `You are ${role.name}, ${role.persona}. You have been assigned task ${taskId}: "${assignedTask.task}". Solve it as part of the overall mission: ${config.mission}. End your response with a clear summary.`;
508
- const result = await executeParticipantPrompt(role, prompt, config);
509
-
510
- process.stdout.write(
511
- `[${role.name} completed ${taskId}] code=${result.code}\n${result.stdout}\n`,
512
- );
513
-
514
- // Report task completion back to locker and release resource locks
515
- await writeLockerMessage(locker, {
516
- type: "lock.complete",
517
- body: { id: taskId, result: result.stdout },
518
- });
519
- // Release any locks associated with this resource
520
- for (const [res, lock] of Object.entries(lockerData)) {
521
- if (lock.owner === role.name) {
522
- await writeLockerMessage(locker, {
523
- type: "lock.release",
524
- body: { resource: res },
525
- });
526
- }
527
- }
528
- }
529
-
530
- await participantLeave(role, config);
531
- }),
532
- );
533
- }
534
-
535
- const coordinatorModes = {
536
- consensus: runConsensus,
537
- fanout: runFanout,
538
- pipeline: runPipeline,
539
- pool: runPool,
540
- };
10
+ import { existsSync } from "node:fs";
11
+ import { dirname, join } from "node:path";
12
+ import { fileURLToPath, pathToFileURL } from "node:url";
541
13
 
542
- async function readJsonFile(path) {
543
- try {
544
- return JSON.parse(await readFile(path, "utf8"));
545
- } catch {
546
- return {};
547
- }
14
+ function packageRoot() {
15
+ return dirname(dirname(fileURLToPath(import.meta.url)));
548
16
  }
549
17
 
550
- const defaultRoles = [
551
- {
552
- name: "mapper",
553
- persona: "systems mapper; tracks shared structure and dependencies",
554
- },
555
- {
556
- name: "memory",
557
- persona: "memory keeper; preserves decisions and unresolved questions",
558
- },
559
- {
560
- name: "risk",
561
- persona: "risk scout; challenges weak coordination and missing owners",
562
- },
563
- {
564
- name: "flow",
565
- persona: "flow designer; turns scattered ideas into process rhythm",
566
- },
567
- {
568
- name: "operator",
569
- persona: "operator; converts ideas into concrete next actions",
570
- },
571
- {
572
- name: "narrative",
573
- persona: "narrative synthesizer; keeps the artifact coherent",
574
- },
575
- {
576
- name: "interface",
577
- persona: "interface designer; makes outputs visible and usable",
578
- },
579
- {
580
- name: "facilitator",
581
- persona: "facilitator; asks for consensus and convergence",
582
- },
583
- ];
584
-
585
- const config = {
586
- runId: arg(
587
- "run-id",
588
- process.env.run_id || process.env.RUN_ID || "coordinator-run",
589
- ),
590
- mode: arg("mode", "consensus"), // "consensus" (default/swarm), "pipeline", "fanout", "pool"
591
- mission: arg(
592
- "mission",
593
- "Coordinate a shared artifact and converge on next actions",
594
- ),
595
- model: arg("model", ""),
596
- thinking: arg("thinking", "off"),
597
- roles: await loadRoles(arg("roles", ""), arg("roles-path", "")),
598
- rounds: numberArg("rounds", 4),
599
- delay: numberArg("delay", 10),
600
- artifactPath: arg("artifact-path", ""),
601
- locker: boolArg("locker", false),
602
- lockerLeaseMs: numberArg("locker-lease-ms", 600000),
603
- };
604
-
605
- if (!config.model) {
606
- console.error("--model is required");
607
- process.exit(2);
18
+ function mainModulePath() {
19
+ const root = packageRoot();
20
+ const compiled = join(root, "dist", "lib", "coordinator.js");
21
+ return existsSync(compiled) ? compiled : join(root, "lib", "coordinator.ts");
608
22
  }
609
- config.room = `room:${config.runId}`;
610
23
 
611
- const failures = [];
612
- const locker = await startLocker(config);
24
+ const { runCoordinator } = await import(pathToFileURL(mainModulePath()).href);
613
25
 
614
26
  try {
615
- const runMode = coordinatorModes[config.mode];
616
- if (!runMode) throw new Error(`Unknown coordinator mode: ${config.mode}`);
617
- await runMode(config, locker);
618
- await synthesize(config, locker);
619
- } catch (globalError) {
620
- failures.push(`Global coordinator error: ${globalError.message}`);
621
- } finally {
622
- await stopLocker(locker);
623
- }
624
-
625
- if (failures.length > 0) {
626
- console.error(failures.join("\n"));
27
+ await runCoordinator(process.argv.slice(2));
28
+ } catch (error) {
29
+ console.error(error instanceof Error ? error.message : String(error));
627
30
  process.exit(1);
628
31
  }