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