@linxiraos/pi-messenger 1.1.0 → 1.3.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 (66) hide show
  1. package/CHANGELOG.md +741 -676
  2. package/LICENSE +45 -0
  3. package/README.md +424 -424
  4. package/THIRD-PARTY-NOTICES.txt +22951 -0
  5. package/config-overlay.ts +175 -171
  6. package/config.ts +221 -209
  7. package/crew/agents/crew-plan-sync.md +66 -64
  8. package/crew/agents/crew-planner.md +173 -172
  9. package/crew/agents/crew-reviewer.md +58 -58
  10. package/crew/agents/crew-worker.md +130 -129
  11. package/crew/agents.ts +507 -434
  12. package/crew/handlers/coordination.ts +350 -332
  13. package/crew/handlers/plan.ts +988 -906
  14. package/crew/handlers/review.ts +354 -333
  15. package/crew/handlers/revise.ts +400 -376
  16. package/crew/handlers/status.ts +303 -295
  17. package/crew/handlers/sync.ts +237 -233
  18. package/crew/handlers/task.ts +820 -792
  19. package/crew/handlers/team.ts +294 -235
  20. package/crew/handlers/work.ts +467 -425
  21. package/crew/id-allocator.ts +30 -30
  22. package/crew/index.ts +297 -257
  23. package/crew/live-progress.ts +58 -58
  24. package/crew/lobby.ts +504 -473
  25. package/crew/prompt.ts +262 -252
  26. package/crew/registry.ts +114 -114
  27. package/crew/spawn.ts +135 -111
  28. package/crew/state-autonomous.ts +163 -164
  29. package/crew/state-planning.ts +264 -263
  30. package/crew/state.ts +20 -20
  31. package/crew/store.ts +646 -642
  32. package/crew/task-actions.ts +162 -131
  33. package/crew/team/store.ts +572 -479
  34. package/crew/team/subagent-roles.ts +105 -87
  35. package/crew/team/types.ts +50 -50
  36. package/crew/types.ts +194 -194
  37. package/crew/utils/artifacts.ts +57 -62
  38. package/crew/utils/config.ts +158 -156
  39. package/crew/utils/discover.ts +221 -219
  40. package/crew/utils/install.ts +94 -85
  41. package/crew/utils/migrations.ts +126 -0
  42. package/crew/utils/progress.ts +191 -187
  43. package/crew/utils/result.ts +16 -16
  44. package/crew/utils/risk-labels.ts +5 -7
  45. package/crew/utils/task-format.ts +14 -14
  46. package/crew/utils/team-roles.ts +44 -28
  47. package/crew/utils/truncate.ts +76 -79
  48. package/crew/utils/verdict.ts +55 -55
  49. package/editor-binary.ts +150 -0
  50. package/editor-command.ts +107 -0
  51. package/editor-target.ts +40 -0
  52. package/feed.ts +321 -268
  53. package/handlers.ts +1041 -1107
  54. package/index.ts +1314 -1206
  55. package/install.mjs +187 -189
  56. package/lib.ts +587 -467
  57. package/overlay-actions.ts +519 -511
  58. package/overlay-coordinator.ts +150 -150
  59. package/overlay-render.ts +770 -676
  60. package/overlay.ts +872 -830
  61. package/package.json +64 -60
  62. package/paths.ts +60 -0
  63. package/skills/pi-messenger-crew/SKILL.md +375 -347
  64. package/store.ts +1147 -1139
  65. package/teamagent-command.ts +321 -0
  66. package/vitest.config.ts +10 -10
package/crew/agents.ts CHANGED
@@ -1,434 +1,507 @@
1
- /**
2
- * Crew - Agent Spawning
3
- *
4
- * Spawns pi processes with progress tracking, truncation, and artifacts.
5
- */
6
-
7
- import { spawn } from "node:child_process";
8
- import { randomUUID } from "node:crypto";
9
- import * as fs from "node:fs";
10
- import * as os from "node:os";
11
- import * as path from "node:path";
12
- import { fileURLToPath } from "node:url";
13
- import { discoverCrewAgents, type CrewAgentConfig } from "./utils/discover.ts";
14
- import { truncateOutput } from "./utils/truncate.ts";
15
- import {
16
- createProgress,
17
- parseJsonlLine,
18
- updateProgress,
19
- getAssistantText,
20
- compactEventForArtifact,
21
- getTerminalProviderError,
22
- type PiEvent,
23
- } from "./utils/progress.ts";
24
- import {
25
- getArtifactPaths,
26
- ensureArtifactsDir,
27
- writeArtifact,
28
- writeMetadata,
29
- appendJsonl
30
- } from "./utils/artifacts.ts";
31
- import { loadCrewConfig, getTruncationForRole, type CrewConfig } from "./utils/config.ts";
32
- import { removeLiveWorker, updateLiveWorker } from "./live-progress.ts";
33
- import { autonomousState, waitForConcurrencyChange } from "./state.ts";
34
- import { registerWorker, unregisterWorker, killAll } from "./registry.ts";
35
- import type { AgentTask, AgentResult } from "./types.ts";
36
- import { generateMemorableName } from "../lib.ts";
37
-
38
- const __filename = fileURLToPath(import.meta.url);
39
- const __dirname = path.dirname(__filename);
40
- const EXTENSION_DIR = path.resolve(__dirname, "..");
41
- const BUILTIN_TOOLS = new Set(["read", "bash", "edit", "write", "grep", "find", "ls"]);
42
-
43
- export interface SpawnOptions {
44
- onProgress?: (results: AgentResult[]) => void;
45
- crewDir?: string;
46
- signal?: AbortSignal;
47
- messengerDirs?: { registry: string; inbox: string };
48
- }
49
-
50
- export function shutdownAllWorkers(): void {
51
- killAll();
52
- }
53
-
54
- export function resolveModel(
55
- taskModel?: string,
56
- paramModel?: string,
57
- roleModel?: string,
58
- configModel?: string,
59
- sessionModel?: string,
60
- agentModel?: string,
61
- ): string | undefined {
62
- return taskModel ?? paramModel ?? roleModel ?? configModel ?? sessionModel ?? agentModel;
63
- }
64
-
65
- export function getPiCommand(): string {
66
- return process.platform === "win32" ? "pi.cmd" : "pi";
67
- }
68
-
69
- export function pushModelArgs(args: string[], model: string): void {
70
- const slashIdx = model.indexOf("/");
71
- if (slashIdx !== -1) {
72
- args.push("--provider", model.substring(0, slashIdx), "--model", model.substring(slashIdx + 1));
73
- } else {
74
- args.push("--model", model);
75
- }
76
- }
77
-
78
- const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh"]);
79
-
80
- export function resolveThinking(
81
- configThinking?: string,
82
- agentThinking?: string,
83
- ): string | undefined {
84
- const resolved = configThinking ?? agentThinking;
85
- if (!resolved || resolved === "off") return undefined;
86
- return resolved;
87
- }
88
-
89
- export function modelHasThinkingSuffix(model: string | undefined): boolean {
90
- if (!model) return false;
91
- const colonIdx = model.lastIndexOf(":");
92
- if (colonIdx === -1) return false;
93
- return THINKING_LEVELS.has(model.substring(colonIdx + 1));
94
- }
95
-
96
- export function raceTimeout(promise: Promise<void>, ms: number): Promise<boolean> {
97
- return new Promise<boolean>(resolve => {
98
- const timer = setTimeout(() => resolve(false), ms);
99
- promise.then(
100
- () => {
101
- clearTimeout(timer);
102
- resolve(true);
103
- },
104
- () => {
105
- clearTimeout(timer);
106
- resolve(false);
107
- },
108
- );
109
- });
110
- }
111
-
112
- function discoverWorkerName(
113
- pid: number | undefined,
114
- registryDir: string | undefined
115
- ): string | null {
116
- if (!pid || !registryDir || !fs.existsSync(registryDir)) return null;
117
- try {
118
- for (const file of fs.readdirSync(registryDir)) {
119
- if (!file.endsWith(".json")) continue;
120
- const reg = JSON.parse(fs.readFileSync(path.join(registryDir, file), "utf-8"));
121
- if (reg.pid === pid) return reg.name;
122
- }
123
- } catch {}
124
- return null;
125
- }
126
-
127
- const SHUTDOWN_MESSAGE = `⚠️ SHUTDOWN REQUESTED: Please wrap up your current work.
128
- 1. Release any file reservations
129
- 2. If the task is not complete, leave it as in_progress (do NOT mark done)
130
- 3. Do NOT commit anything
131
- 4. Exit`;
132
-
133
- /**
134
- * Spawn multiple agents in parallel with concurrency limit.
135
- */
136
- export async function spawnAgents(
137
- tasks: AgentTask[],
138
- cwd: string,
139
- options: SpawnOptions = {}
140
- ): Promise<AgentResult[]> {
141
- const crewDir = options.crewDir ?? path.join(cwd, ".pi", "messenger", "crew");
142
- const config = loadCrewConfig(crewDir);
143
- const agents = discoverCrewAgents(cwd);
144
- const runId = randomUUID().slice(0, 8);
145
-
146
- // Setup artifacts directory if enabled
147
- const artifactsDir = path.join(crewDir, "artifacts");
148
- if (config.artifacts.enabled) {
149
- ensureArtifactsDir(artifactsDir, config.artifacts.cleanupDays);
150
- }
151
-
152
- const results: AgentResult[] = [];
153
- const queue = tasks.map((task, index) => ({ task, index }));
154
- const running: Promise<void>[] = [];
155
-
156
- while (queue.length > 0 || running.length > 0) {
157
- if (options.signal?.aborted && running.length === 0) break;
158
-
159
- while (running.length < autonomousState.concurrency && queue.length > 0) {
160
- if (options.signal?.aborted) break;
161
- const { task, index } = queue.shift()!;
162
- const promise = runAgent(task, index, cwd, agents, config, runId, artifactsDir, options)
163
- .then(result => {
164
- results.push(result);
165
- running.splice(running.indexOf(promise), 1);
166
- options.onProgress?.(results);
167
- });
168
- running.push(promise);
169
- }
170
- if (running.length > 0) {
171
- await Promise.race([...running, waitForConcurrencyChange()]);
172
- if (options.signal?.aborted) continue;
173
- }
174
- }
175
-
176
- return results;
177
- }
178
-
179
- async function runAgent(
180
- task: AgentTask,
181
- index: number,
182
- cwd: string,
183
- agents: CrewAgentConfig[],
184
- config: CrewConfig,
185
- runId: string,
186
- artifactsDir: string,
187
- options: SpawnOptions
188
- ): Promise<AgentResult> {
189
- const agentConfig = agents.find(a => a.name === task.agent);
190
- const progress = createProgress(task.agent);
191
- const startTime = Date.now();
192
- const workerName = generateMemorableName();
193
-
194
- const role = agentConfig?.crewRole ?? "worker";
195
- const maxOutput = task.maxOutput
196
- ?? agentConfig?.maxOutput
197
- ?? getTruncationForRole(config, role);
198
-
199
- let artifactPaths = config.artifacts.enabled
200
- ? getArtifactPaths(artifactsDir, runId, task.agent, index)
201
- : undefined;
202
-
203
- if (artifactPaths) {
204
- try {
205
- writeArtifact(artifactPaths.inputPath, `# Task for ${task.agent}\n\n${task.task}`);
206
- } catch {
207
- artifactPaths = undefined;
208
- }
209
- }
210
-
211
- return new Promise((resolve) => {
212
- // Build args for pi command
213
- const args = ["--mode", "json", "--no-session", "-p"];
214
- const model = task.modelOverride ?? config.models?.[role] ?? agentConfig?.model;
215
- if (model) pushModelArgs(args, model);
216
-
217
- const thinking = resolveThinking(
218
- config.thinking?.[role],
219
- agentConfig?.thinking,
220
- );
221
- if (thinking && !modelHasThinkingSuffix(model)) {
222
- args.push("--thinking", thinking);
223
- }
224
-
225
- if (agentConfig?.tools?.length) {
226
- const builtinTools: string[] = [];
227
- const extensionPaths: string[] = [];
228
- for (const tool of agentConfig.tools) {
229
- if (tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")) {
230
- extensionPaths.push(tool);
231
- } else if (BUILTIN_TOOLS.has(tool)) {
232
- builtinTools.push(tool);
233
- }
234
- }
235
-
236
- if (builtinTools.length > 0) {
237
- args.push("--tools", builtinTools.join(","));
238
- }
239
- for (const extensionPath of extensionPaths) {
240
- args.push("--extension", extensionPath);
241
- }
242
- }
243
-
244
- // Pass extension so workers can use pi_messenger
245
- args.push("--extension", EXTENSION_DIR);
246
-
247
- let promptTmpDir: string | null = null;
248
- if (agentConfig?.systemPrompt) {
249
- promptTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-messenger-agent-"));
250
- const promptPath = path.join(promptTmpDir, `${task.agent.replace(/[^\w.-]/g, "_")}.md`);
251
- fs.writeFileSync(promptPath, agentConfig.systemPrompt, { mode: 0o600 });
252
- args.push("--append-system-prompt", promptPath);
253
- }
254
-
255
- args.push(task.task);
256
-
257
- const envOverrides = config.work.env ?? {};
258
- const workerFlag = role === "worker"
259
- ? { PI_CREW_WORKER: "1", PI_AGENT_NAME: workerName }
260
- : {};
261
- const env = Object.keys(envOverrides).length > 0 || role === "worker"
262
- ? { ...process.env, ...envOverrides, ...workerFlag }
263
- : undefined;
264
-
265
- const proc = spawn(getPiCommand(), args, {
266
- cwd,
267
- stdio: ["ignore", "pipe", "pipe"],
268
- ...(env ? { env } : {}),
269
- });
270
- if (task.taskId) {
271
- registerWorker({ type: "worker", proc, name: workerName, cwd, taskId: task.taskId });
272
- }
273
- let gracefulShutdownRequested = false;
274
- let discoveredWorkerName: string | null = null;
275
-
276
- let jsonlBuffer = "";
277
- let fullOutput = "";
278
- let terminalProviderError: string | null = null;
279
-
280
- proc.stdout?.on("data", (data) => {
281
- try {
282
- jsonlBuffer += data.toString();
283
- const lines = jsonlBuffer.split("\n");
284
- jsonlBuffer = lines.pop() ?? "";
285
-
286
- for (const line of lines) {
287
- const event = parseJsonlLine(line);
288
- if (event) {
289
- updateProgress(progress, event, startTime);
290
- const assistantText = getAssistantText(event);
291
- if (assistantText) fullOutput = assistantText;
292
- if (artifactPaths) {
293
- try { appendJsonl(artifactPaths.jsonlPath, JSON.stringify(compactEventForArtifact(event))); }
294
- catch { artifactPaths = undefined; }
295
- }
296
- const providerError = getTerminalProviderError(event);
297
- if (providerError && !terminalProviderError) {
298
- terminalProviderError = providerError;
299
- progress.error = providerError;
300
- proc.kill("SIGTERM");
301
- }
302
- if (task.taskId) {
303
- updateLiveWorker(cwd, task.taskId, {
304
- taskId: task.taskId,
305
- agent: task.agent,
306
- name: workerName,
307
- progress: {
308
- ...progress,
309
- recentTools: progress.recentTools.map(tool => ({ ...tool })),
310
- },
311
- startedAt: startTime,
312
- });
313
- }
314
- }
315
- }
316
- } catch {}
317
- });
318
-
319
- let stderr = "";
320
- proc.stderr?.on("data", (data) => { stderr += data.toString(); });
321
-
322
- proc.on("close", (code) => {
323
- if (task.taskId) {
324
- removeLiveWorker(cwd, task.taskId);
325
- unregisterWorker(cwd, task.taskId);
326
- }
327
- const exitCode = terminalProviderError ? 1 : code ?? 1;
328
- progress.status = exitCode === 0 ? "completed" : "failed";
329
- progress.durationMs = Date.now() - startTime;
330
- if (terminalProviderError) progress.error = terminalProviderError;
331
- else if (stderr && exitCode !== 0) progress.error = stderr;
332
-
333
- const truncation = truncateOutput(fullOutput, maxOutput, artifactPaths?.outputPath);
334
-
335
- if (artifactPaths) {
336
- try {
337
- writeArtifact(artifactPaths.outputPath, fullOutput);
338
- writeMetadata(artifactPaths.metadataPath, {
339
- runId,
340
- agent: task.agent,
341
- index,
342
- exitCode,
343
- durationMs: progress.durationMs,
344
- tokens: progress.tokens,
345
- truncated: truncation.truncated,
346
- error: progress.error,
347
- });
348
- } catch {}
349
- }
350
-
351
- if (promptTmpDir) {
352
- try { fs.rmSync(promptTmpDir, { recursive: true, force: true }); } catch {}
353
- }
354
-
355
- resolve({
356
- agent: task.agent,
357
- exitCode,
358
- output: truncation.text,
359
- truncated: truncation.truncated,
360
- progress,
361
- config: agentConfig,
362
- taskId: task.taskId,
363
- wasGracefullyShutdown: gracefulShutdownRequested,
364
- error: progress.error,
365
- artifactPaths: artifactPaths ? {
366
- input: artifactPaths.inputPath,
367
- output: artifactPaths.outputPath,
368
- jsonl: artifactPaths.jsonlPath,
369
- metadata: artifactPaths.metadataPath,
370
- } : undefined,
371
- });
372
-
373
- if (gracefulShutdownRequested && discoveredWorkerName && options.messengerDirs?.registry) {
374
- try {
375
- fs.unlinkSync(path.join(options.messengerDirs.registry, `${discoveredWorkerName}.json`));
376
- } catch {}
377
- }
378
- });
379
-
380
- // Handle abort signal
381
- if (options.signal) {
382
- const gracefulShutdown = async () => {
383
- gracefulShutdownRequested = true;
384
-
385
- let messageSent = false;
386
- discoveredWorkerName = discoverWorkerName(proc.pid, options.messengerDirs?.registry);
387
- if (discoveredWorkerName && options.messengerDirs) {
388
- try {
389
- const inboxDir = path.join(options.messengerDirs.inbox, discoveredWorkerName);
390
- if (fs.existsSync(inboxDir)) {
391
- const msgFile = path.join(inboxDir, `${Date.now()}-shutdown.json`);
392
- fs.writeFileSync(msgFile, JSON.stringify({
393
- id: randomUUID(),
394
- from: "crew-orchestrator",
395
- to: discoveredWorkerName,
396
- text: SHUTDOWN_MESSAGE,
397
- timestamp: new Date().toISOString(),
398
- replyTo: null,
399
- }));
400
- messageSent = true;
401
- }
402
- } catch {}
403
- }
404
-
405
- if (messageSent) {
406
- const graceMs = config.work.shutdownGracePeriodMs ?? 30000;
407
- const exitPromise = new Promise<void>(r => proc.once("exit", () => r()));
408
- const exited = await raceTimeout(exitPromise, graceMs);
409
- if (exited) return;
410
- }
411
-
412
- if (!proc.killed && proc.exitCode === null) {
413
- proc.kill("SIGTERM");
414
- const termPromise = new Promise<void>(r => proc.once("exit", () => r()));
415
- const killed = await raceTimeout(termPromise, 5000);
416
- if (killed) return;
417
- } else {
418
- return;
419
- }
420
-
421
- if (proc.exitCode === null) {
422
- proc.kill("SIGKILL");
423
- }
424
- };
425
- if (options.signal.aborted) {
426
- gracefulShutdown().catch(() => {});
427
- } else {
428
- options.signal.addEventListener("abort", () => {
429
- gracefulShutdown().catch(() => {});
430
- }, { once: true });
431
- }
432
- }
433
- });
434
- }
1
+ /**
2
+ * Crew - Agent Spawning
3
+ *
4
+ * Spawns zeta CLI subprocesses with progress tracking, truncation, and artifacts.
5
+ */
6
+
7
+ import { spawn } from "node:child_process";
8
+ import { randomUUID } from "node:crypto";
9
+ import * as fs from "node:fs";
10
+ import * as os from "node:os";
11
+ import * as path from "node:path";
12
+ import { fileURLToPath } from "node:url";
13
+ import { CLI_BIN_NAME } from "@linxiraos/pi-utils/dirs";
14
+ import { discoverCrewAgents, type CrewAgentConfig } from "./utils/discover.ts";
15
+ import { getProjectCrewDir } from "../paths.ts";
16
+ import { truncateOutput } from "./utils/truncate.ts";
17
+ import {
18
+ createProgress,
19
+ parseJsonlLine,
20
+ updateProgress,
21
+ getAssistantText,
22
+ compactEventForArtifact,
23
+ getTerminalProviderError,
24
+ } from "./utils/progress.ts";
25
+ import { getArtifactPaths, ensureArtifactsDir, writeArtifact, writeMetadata, appendJsonl } from "./utils/artifacts.ts";
26
+ import { loadCrewConfig, getTruncationForRole, type CrewConfig } from "./utils/config.ts";
27
+ import { removeLiveWorker, updateLiveWorker } from "./live-progress.ts";
28
+ import { autonomousState, waitForConcurrencyChange } from "./state.ts";
29
+ import { registerWorker, unregisterWorker, killAll } from "./registry.ts";
30
+ import type { AgentTask, AgentResult } from "./types.ts";
31
+ import { generateMemorableName } from "../lib.ts";
32
+
33
+ const __filename = fileURLToPath(import.meta.url);
34
+ const __dirname = path.dirname(__filename);
35
+ const EXTENSION_DIR = path.resolve(__dirname, "..");
36
+
37
+ export interface SpawnOptions {
38
+ onProgress?: (results: AgentResult[]) => void;
39
+ crewDir?: string;
40
+ signal?: AbortSignal;
41
+ messengerDirs?: { registry: string; inbox: string };
42
+ }
43
+
44
+ export function shutdownAllWorkers(): void {
45
+ killAll();
46
+ }
47
+
48
+ export function resolveModel(
49
+ taskModel?: string,
50
+ paramModel?: string,
51
+ roleModel?: string,
52
+ configModel?: string,
53
+ sessionModel?: string,
54
+ agentModel?: string,
55
+ ): string | undefined {
56
+ return taskModel ?? paramModel ?? roleModel ?? configModel ?? sessionModel ?? agentModel;
57
+ }
58
+
59
+ /**
60
+ * Resolve the CLI that crew subprocesses run: the zeta CLI this extension is
61
+ * loaded by — never upstream `pi`, and never the workspace `zeta` product.
62
+ *
63
+ * Priority (mirrors the host's own subprocess resolver, task/omp-command.ts):
64
+ * 1. `PI_SUBPROCESS_CMD` env override (documented escape hatch for embedders).
65
+ * 2. Source/dev run: `process.execPath` is the Bun/Node runtime and
66
+ * `process.argv[1]` the TS/JS CLI entry — spawn `[runtime, entry]`.
67
+ * 3. Compiled binary: `process.execPath` IS the CLI executable.
68
+ * 4. PATH lookup of the published CLI name — `CLI_BIN_NAME` ("zetacode") first,
69
+ * then the `CLI_FALLBACK_NAMES` install list (also just "zetacode"): the
70
+ * product ships exactly one bin name now, so no hyphenated compatibility
71
+ * alias is ever probed. On Windows only real executables qualify:
72
+ * `.cmd`/`.bat` shims cannot be spawned without a shell (EINVAL under Bun
73
+ * and modern Node), and spawning through a shell would expose task text to
74
+ * command injection. When nothing resolves, the primary name is returned
75
+ * anyway so the spawn fails with a clear ENOENT instead of silently
76
+ * running the wrong CLI.
77
+ */
78
+ const CLI_FALLBACK_NAMES = ["zetacode"];
79
+
80
+ /** Script-file argv[1] discriminates a source-mode CLI run from a compiled binary. */
81
+ const ENTRY_SCRIPT_RE = /\.(?:[cm]?[jt]sx?)$/;
82
+
83
+ interface CliSpawnCommand {
84
+ cmd: string;
85
+ args: string[];
86
+ }
87
+
88
+ let cachedCliCommand: CliSpawnCommand | null = null;
89
+
90
+ function isJsRuntimeExecutable(): boolean {
91
+ const base = path.basename(process.execPath).replace(/\.exe$/i, "").toLowerCase();
92
+ return base === "bun" || base === "node" || base === "electron";
93
+ }
94
+
95
+ function resolveCliFromPath(): string | null {
96
+ const searchDirs = (process.env.PATH ?? "").split(path.delimiter).filter(Boolean);
97
+ const suffixes = process.platform === "win32" ? [".exe"] : [""];
98
+ for (const dir of searchDirs) {
99
+ for (const name of [CLI_BIN_NAME, ...CLI_FALLBACK_NAMES]) {
100
+ for (const suffix of suffixes) {
101
+ const candidate = path.join(dir, name + suffix);
102
+ try {
103
+ fs.accessSync(candidate, fs.constants.X_OK);
104
+ if (fs.statSync(candidate).isFile()) return candidate;
105
+ } catch {
106
+ // Keep scanning.
107
+ }
108
+ }
109
+ }
110
+ }
111
+ return null;
112
+ }
113
+
114
+ export function getCliSpawnCommand(): CliSpawnCommand {
115
+ if (cachedCliCommand) return cachedCliCommand;
116
+
117
+ const envCmd = process.env.PI_SUBPROCESS_CMD?.trim();
118
+ const entry = process.argv[1];
119
+ let resolved: CliSpawnCommand;
120
+ if (envCmd) {
121
+ resolved = { cmd: envCmd, args: [] };
122
+ } else if (isJsRuntimeExecutable() && entry && ENTRY_SCRIPT_RE.test(entry)) {
123
+ resolved = { cmd: process.execPath, args: [entry] };
124
+ } else if (!isJsRuntimeExecutable()) {
125
+ resolved = { cmd: process.execPath, args: [] };
126
+ } else {
127
+ resolved = { cmd: resolveCliFromPath() ?? CLI_BIN_NAME, args: [] };
128
+ }
129
+
130
+ cachedCliCommand = resolved;
131
+ return resolved;
132
+ }
133
+
134
+ /** Test seam: forget the cached CLI resolution so a test can re-resolve. */
135
+ export function resetCliCommandCache(): void {
136
+ cachedCliCommand = null;
137
+ }
138
+
139
+ export function pushModelArgs(args: string[], model: string): void {
140
+ const slashIdx = model.indexOf("/");
141
+ if (slashIdx !== -1) {
142
+ args.push("--provider", model.substring(0, slashIdx), "--model", model.substring(slashIdx + 1));
143
+ } else {
144
+ args.push("--model", model);
145
+ }
146
+ }
147
+
148
+ const THINKING_LEVELS = new Set(["off", "minimal", "low", "medium", "high", "xhigh"]);
149
+
150
+ export function resolveThinking(configThinking?: string, agentThinking?: string): string | undefined {
151
+ const resolved = configThinking ?? agentThinking;
152
+ if (!resolved || resolved === "off") return undefined;
153
+ return resolved;
154
+ }
155
+
156
+ export function modelHasThinkingSuffix(model: string | undefined): boolean {
157
+ if (!model) return false;
158
+ const colonIdx = model.lastIndexOf(":");
159
+ if (colonIdx === -1) return false;
160
+ return THINKING_LEVELS.has(model.substring(colonIdx + 1));
161
+ }
162
+
163
+ export function raceTimeout(promise: Promise<void>, ms: number): Promise<boolean> {
164
+ return new Promise<boolean>(resolve => {
165
+ const timer = setTimeout(() => resolve(false), ms);
166
+ promise.then(
167
+ () => {
168
+ clearTimeout(timer);
169
+ resolve(true);
170
+ },
171
+ () => {
172
+ clearTimeout(timer);
173
+ resolve(false);
174
+ },
175
+ );
176
+ });
177
+ }
178
+
179
+ function discoverWorkerName(pid: number | undefined, registryDir: string | undefined): string | null {
180
+ if (!pid || !registryDir || !fs.existsSync(registryDir)) return null;
181
+ try {
182
+ for (const file of fs.readdirSync(registryDir)) {
183
+ if (!file.endsWith(".json")) continue;
184
+ const reg = JSON.parse(fs.readFileSync(path.join(registryDir, file), "utf-8"));
185
+ if (reg.pid === pid) return reg.name;
186
+ }
187
+ } catch {}
188
+ return null;
189
+ }
190
+
191
+ const SHUTDOWN_MESSAGE = `⚠️ SHUTDOWN REQUESTED: Please wrap up your current work.
192
+ 1. Release any file reservations
193
+ 2. If the task is not complete, leave it as in_progress (do NOT mark done)
194
+ 3. Do NOT commit anything
195
+ 4. Exit`;
196
+
197
+ /**
198
+ * Spawn multiple agents in parallel with concurrency limit.
199
+ */
200
+ export async function spawnAgents(tasks: AgentTask[], cwd: string, options: SpawnOptions = {}): Promise<AgentResult[]> {
201
+ const crewDir = options.crewDir ?? getProjectCrewDir(cwd);
202
+ const config = loadCrewConfig(crewDir);
203
+ const agents = discoverCrewAgents(cwd);
204
+ const runId = randomUUID().slice(0, 8);
205
+
206
+ // Setup artifacts directory if enabled
207
+ const artifactsDir = path.join(crewDir, "artifacts");
208
+ if (config.artifacts.enabled) {
209
+ ensureArtifactsDir(artifactsDir, config.artifacts.cleanupDays);
210
+ }
211
+
212
+ const results: AgentResult[] = [];
213
+ const queue = tasks.map((task, index) => ({ task, index }));
214
+ const running: Promise<void>[] = [];
215
+
216
+ while (queue.length > 0 || running.length > 0) {
217
+ if (options.signal?.aborted && running.length === 0) break;
218
+
219
+ while (running.length < autonomousState.concurrency && queue.length > 0) {
220
+ if (options.signal?.aborted) break;
221
+ const { task, index } = queue.shift()!;
222
+ const promise = runAgent(task, index, cwd, agents, config, runId, artifactsDir, options).then(result => {
223
+ results.push(result);
224
+ running.splice(running.indexOf(promise), 1);
225
+ options.onProgress?.(results);
226
+ });
227
+ running.push(promise);
228
+ }
229
+ if (running.length > 0) {
230
+ await Promise.race([...running, waitForConcurrencyChange()]);
231
+ if (options.signal?.aborted) continue;
232
+ }
233
+ }
234
+
235
+ return results;
236
+ }
237
+
238
+ async function runAgent(
239
+ task: AgentTask,
240
+ index: number,
241
+ cwd: string,
242
+ agents: CrewAgentConfig[],
243
+ config: CrewConfig,
244
+ runId: string,
245
+ artifactsDir: string,
246
+ options: SpawnOptions,
247
+ ): Promise<AgentResult> {
248
+ const agentConfig = agents.find(a => a.name === task.agent);
249
+ const progress = createProgress(task.agent);
250
+ const startTime = Date.now();
251
+ const workerName = generateMemorableName();
252
+
253
+ const role = agentConfig?.crewRole ?? "worker";
254
+ const maxOutput = task.maxOutput ?? agentConfig?.maxOutput ?? getTruncationForRole(config, role);
255
+
256
+ let artifactPaths = config.artifacts.enabled ? getArtifactPaths(artifactsDir, runId, task.agent, index) : undefined;
257
+
258
+ if (artifactPaths) {
259
+ try {
260
+ writeArtifact(artifactPaths.inputPath, `# Task for ${task.agent}\n\n${task.task}`);
261
+ } catch {
262
+ artifactPaths = undefined;
263
+ }
264
+ }
265
+
266
+ return new Promise(resolve => {
267
+ // Build args for the zeta CLI. Flag surface verified against the host
268
+ // parser (packages/coding-agent/src/cli/{args,flag-tables}.ts):
269
+ // --mode json, --no-session, -p/--print, --provider/--model, --thinking,
270
+ // --tools (comma-separated), repeatable --extension,
271
+ // --append-system-prompt, trailing positional prompt. Upstream pi used
272
+ // the same vocabulary, so no per-flag adaptation is needed.
273
+ const args = ["--mode", "json", "--no-session", "-p"];
274
+ const model = task.modelOverride ?? config.models?.[role] ?? agentConfig?.model;
275
+ if (model) pushModelArgs(args, model);
276
+
277
+ const thinking = resolveThinking(config.thinking?.[role], agentConfig?.thinking);
278
+ if (thinking && !modelHasThinkingSuffix(model)) {
279
+ args.push("--thinking", thinking);
280
+ }
281
+
282
+ if (agentConfig?.tools?.length) {
283
+ const builtinTools: string[] = [];
284
+ const extensionPaths: string[] = [];
285
+ for (const tool of agentConfig.tools) {
286
+ if (tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")) {
287
+ extensionPaths.push(tool);
288
+ } else {
289
+ builtinTools.push(tool);
290
+ }
291
+ }
292
+
293
+ if (builtinTools.length > 0) {
294
+ args.push("--tools", builtinTools.join(","));
295
+ }
296
+ for (const extensionPath of extensionPaths) {
297
+ args.push("--extension", extensionPath);
298
+ }
299
+ }
300
+
301
+ // Pass extension so workers can use pi_messenger
302
+ args.push("--extension", EXTENSION_DIR);
303
+
304
+ let promptTmpDir: string | null = null;
305
+ if (agentConfig?.systemPrompt) {
306
+ promptTmpDir = fs.mkdtempSync(path.join(os.tmpdir(), "pi-messenger-agent-"));
307
+ const promptPath = path.join(promptTmpDir, `${task.agent.replace(/[^\w.-]/g, "_")}.md`);
308
+ fs.writeFileSync(promptPath, agentConfig.systemPrompt, { mode: 0o600 });
309
+ args.push("--append-system-prompt", promptPath);
310
+ }
311
+
312
+ args.push(task.task);
313
+
314
+ const envOverrides = config.work.env ?? {};
315
+ const workerFlag = role === "worker" ? { PI_CREW_WORKER: "1", PI_AGENT_NAME: workerName } : {};
316
+ const env =
317
+ Object.keys(envOverrides).length > 0 || role === "worker"
318
+ ? { ...process.env, ...envOverrides, ...workerFlag }
319
+ : undefined;
320
+
321
+ const cli = getCliSpawnCommand();
322
+ const proc = spawn(cli.cmd, [...cli.args, ...args], {
323
+ cwd,
324
+ stdio: ["ignore", "pipe", "pipe"],
325
+ ...(env ? { env } : {}),
326
+ });
327
+ if (task.taskId) {
328
+ registerWorker({ type: "worker", proc, name: workerName, cwd, taskId: task.taskId });
329
+ }
330
+ let gracefulShutdownRequested = false;
331
+ let discoveredWorkerName: string | null = null;
332
+
333
+ let jsonlBuffer = "";
334
+ let fullOutput = "";
335
+ let terminalProviderError: string | null = null;
336
+
337
+ proc.stdout?.on("data", data => {
338
+ try {
339
+ jsonlBuffer += data.toString();
340
+ const lines = jsonlBuffer.split("\n");
341
+ jsonlBuffer = lines.pop() ?? "";
342
+
343
+ for (const line of lines) {
344
+ const event = parseJsonlLine(line);
345
+ if (event) {
346
+ updateProgress(progress, event, startTime);
347
+ const assistantText = getAssistantText(event);
348
+ if (assistantText) fullOutput = assistantText;
349
+ if (artifactPaths) {
350
+ try {
351
+ appendJsonl(artifactPaths.jsonlPath, JSON.stringify(compactEventForArtifact(event)));
352
+ } catch {
353
+ artifactPaths = undefined;
354
+ }
355
+ }
356
+ const providerError = getTerminalProviderError(event);
357
+ if (providerError && !terminalProviderError) {
358
+ terminalProviderError = providerError;
359
+ progress.error = providerError;
360
+ proc.kill("SIGTERM");
361
+ }
362
+ if (task.taskId) {
363
+ updateLiveWorker(cwd, task.taskId, {
364
+ taskId: task.taskId,
365
+ agent: task.agent,
366
+ name: workerName,
367
+ progress: {
368
+ ...progress,
369
+ recentTools: progress.recentTools.map(tool => ({ ...tool })),
370
+ },
371
+ startedAt: startTime,
372
+ });
373
+ }
374
+ }
375
+ }
376
+ } catch {}
377
+ });
378
+
379
+ let stderr = "";
380
+ proc.stderr?.on("data", data => {
381
+ stderr += data.toString();
382
+ });
383
+
384
+ proc.on("close", code => {
385
+ if (task.taskId) {
386
+ removeLiveWorker(cwd, task.taskId);
387
+ unregisterWorker(cwd, task.taskId);
388
+ }
389
+ const exitCode = terminalProviderError ? 1 : (code ?? 1);
390
+ progress.status = exitCode === 0 ? "completed" : "failed";
391
+ progress.durationMs = Date.now() - startTime;
392
+ if (terminalProviderError) progress.error = terminalProviderError;
393
+ else if (stderr && exitCode !== 0) progress.error = stderr;
394
+
395
+ const truncation = truncateOutput(fullOutput, maxOutput, artifactPaths?.outputPath);
396
+
397
+ if (artifactPaths) {
398
+ try {
399
+ writeArtifact(artifactPaths.outputPath, fullOutput);
400
+ writeMetadata(artifactPaths.metadataPath, {
401
+ runId,
402
+ agent: task.agent,
403
+ index,
404
+ exitCode,
405
+ durationMs: progress.durationMs,
406
+ tokens: progress.tokens,
407
+ truncated: truncation.truncated,
408
+ error: progress.error,
409
+ });
410
+ } catch {}
411
+ }
412
+
413
+ if (promptTmpDir) {
414
+ try {
415
+ fs.rmSync(promptTmpDir, { recursive: true, force: true });
416
+ } catch {}
417
+ }
418
+
419
+ resolve({
420
+ agent: task.agent,
421
+ exitCode,
422
+ output: truncation.text,
423
+ truncated: truncation.truncated,
424
+ progress,
425
+ config: agentConfig,
426
+ taskId: task.taskId,
427
+ wasGracefullyShutdown: gracefulShutdownRequested,
428
+ error: progress.error,
429
+ artifactPaths: artifactPaths
430
+ ? {
431
+ input: artifactPaths.inputPath,
432
+ output: artifactPaths.outputPath,
433
+ jsonl: artifactPaths.jsonlPath,
434
+ metadata: artifactPaths.metadataPath,
435
+ }
436
+ : undefined,
437
+ });
438
+
439
+ if (gracefulShutdownRequested && discoveredWorkerName && options.messengerDirs?.registry) {
440
+ try {
441
+ fs.unlinkSync(path.join(options.messengerDirs.registry, `${discoveredWorkerName}.json`));
442
+ } catch {}
443
+ }
444
+ });
445
+
446
+ // Handle abort signal
447
+ if (options.signal) {
448
+ const gracefulShutdown = async () => {
449
+ gracefulShutdownRequested = true;
450
+
451
+ let messageSent = false;
452
+ discoveredWorkerName = discoverWorkerName(proc.pid, options.messengerDirs?.registry);
453
+ if (discoveredWorkerName && options.messengerDirs) {
454
+ try {
455
+ const inboxDir = path.join(options.messengerDirs.inbox, discoveredWorkerName);
456
+ if (fs.existsSync(inboxDir)) {
457
+ const msgFile = path.join(inboxDir, `${Date.now()}-shutdown.json`);
458
+ fs.writeFileSync(
459
+ msgFile,
460
+ JSON.stringify({
461
+ id: randomUUID(),
462
+ from: "crew-orchestrator",
463
+ to: discoveredWorkerName,
464
+ text: SHUTDOWN_MESSAGE,
465
+ timestamp: new Date().toISOString(),
466
+ replyTo: null,
467
+ }),
468
+ );
469
+ messageSent = true;
470
+ }
471
+ } catch {}
472
+ }
473
+
474
+ if (messageSent) {
475
+ const graceMs = config.work.shutdownGracePeriodMs ?? 30000;
476
+ const exitPromise = new Promise<void>(r => proc.once("exit", () => r()));
477
+ const exited = await raceTimeout(exitPromise, graceMs);
478
+ if (exited) return;
479
+ }
480
+
481
+ if (!proc.killed && proc.exitCode === null) {
482
+ proc.kill("SIGTERM");
483
+ const termPromise = new Promise<void>(r => proc.once("exit", () => r()));
484
+ const killed = await raceTimeout(termPromise, 5000);
485
+ if (killed) return;
486
+ } else {
487
+ return;
488
+ }
489
+
490
+ if (proc.exitCode === null) {
491
+ proc.kill("SIGKILL");
492
+ }
493
+ };
494
+ if (options.signal.aborted) {
495
+ gracefulShutdown().catch(() => {});
496
+ } else {
497
+ options.signal.addEventListener(
498
+ "abort",
499
+ () => {
500
+ gracefulShutdown().catch(() => {});
501
+ },
502
+ { once: true },
503
+ );
504
+ }
505
+ }
506
+ });
507
+ }