@loka1/pi-orchestra 0.0.0-stage → 0.6.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.
- package/CHANGELOG.md +313 -0
- package/LICENSE +21 -0
- package/README.md +662 -2
- package/assets/preview.html +226 -0
- package/assets/preview.png +0 -0
- package/config/orchestra.json.example +35 -0
- package/config/templates/review-squad.md +11 -0
- package/extensions/lib/agents.ts +110 -0
- package/extensions/lib/chat.ts +171 -0
- package/extensions/lib/commands.ts +118 -0
- package/extensions/lib/config.ts +236 -0
- package/extensions/lib/format.ts +663 -0
- package/extensions/lib/git.ts +99 -0
- package/extensions/lib/log.ts +233 -0
- package/extensions/lib/mail.ts +115 -0
- package/extensions/lib/metrics.ts +365 -0
- package/extensions/lib/providers.ts +355 -0
- package/extensions/lib/redact.ts +57 -0
- package/extensions/lib/retry.ts +61 -0
- package/extensions/lib/state.ts +694 -0
- package/extensions/lib/templates.ts +153 -0
- package/extensions/lib/types.ts +171 -0
- package/extensions/lib/worker.ts +450 -0
- package/extensions/orchestra.ts +3043 -0
- package/extensions/ui/browse.ts +497 -0
- package/extensions/ui/join.ts +289 -0
- package/package.json +56 -4
- package/skills/orchestra/SKILL.md +86 -0
|
@@ -0,0 +1,3043 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* pi-orchestra
|
|
3
|
+
*
|
|
4
|
+
* Orchestration inside pi, with no external runtime: a coordinator session
|
|
5
|
+
* (you) spawns worker sessions (`pi --mode rpc`), assigns them tasks, steers
|
|
6
|
+
* them, answers their questions and collects their results.
|
|
7
|
+
*
|
|
8
|
+
* Concepts (deliberately close to Orca's orchestration model):
|
|
9
|
+
* Run a unit of work with a name and a goal
|
|
10
|
+
* Task one unit of work inside a run, optionally depending on other tasks
|
|
11
|
+
* Dispatch one worker process working on a task (or a free-form spec)
|
|
12
|
+
* Gate a question a worker is blocked on
|
|
13
|
+
*
|
|
14
|
+
* Every worker is a full pi session with its own context window, tools, model
|
|
15
|
+
* and session log, so the coordinator stays small.
|
|
16
|
+
*
|
|
17
|
+
* This file is the extension entry point. `extensions/lib/*` holds the pure
|
|
18
|
+
* state, mail, process and formatting layers.
|
|
19
|
+
*/
|
|
20
|
+
|
|
21
|
+
import { StringEnum } from "@earendil-works/pi-ai";
|
|
22
|
+
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
23
|
+
import { Text, truncateToWidth } from "@earendil-works/pi-tui";
|
|
24
|
+
import { Type } from "typebox";
|
|
25
|
+
import { mkdirSync, writeFileSync } from "node:fs";
|
|
26
|
+
import { join } from "node:path";
|
|
27
|
+
import { fileURLToPath } from "node:url";
|
|
28
|
+
|
|
29
|
+
import { type AgentScope, discoverAgents, findAgent } from "./lib/agents.ts";
|
|
30
|
+
import { type OrchestraConfig, DEFAULT_CONFIG, loadConfig, resolveStateDir } from "./lib/config.ts";
|
|
31
|
+
import { type Dispatch, type Gate, type OrchestraState, type Run, type Task, activeRun, archiveAndClearState, archiveRuns, pidAlive, pruneStore, createDispatch, createRun, createTask, ensureStore, isTerminalStatus, killPid, listDispatches, listTasks, loadState, newId,
|
|
32
|
+
reconcileOrphans, setTaskDeps, nowIso, refreshTaskReadiness, runOf, saveState, storePaths, totalUsage } from "./lib/state.ts";
|
|
33
|
+
import { pendingQuestions, postQuestion, waitForAnswer, writeAnswer } from "./lib/mail.ts";
|
|
34
|
+
import { readRecords, readTranscript, searchLogs, transcriptText } from "./lib/log.ts";
|
|
35
|
+
import { type ChatBlock, chatBlockFromEvent, chatBlocks, chatText } from "./lib/chat.ts";
|
|
36
|
+
import { metricsJsonl, metricsTable, runMetrics, runReport } from "./lib/metrics.ts";
|
|
37
|
+
import { diffReport, gitDiff, gitHead, statText } from "./lib/git.ts";
|
|
38
|
+
import { ORCHESTRA_COMMANDS, completeOrchestraArgument } from "./lib/commands.ts";
|
|
39
|
+
import { planRetry } from "./lib/retry.ts";
|
|
40
|
+
import {
|
|
41
|
+
browseItems,
|
|
42
|
+
dispatchGlyph,
|
|
43
|
+
dispatchReport,
|
|
44
|
+
fit,
|
|
45
|
+
formatCost,
|
|
46
|
+
formatTokens,
|
|
47
|
+
hasLiveWork,
|
|
48
|
+
liveDispatches,
|
|
49
|
+
questionReport,
|
|
50
|
+
runSummary,
|
|
51
|
+
shortId,
|
|
52
|
+
statusLine,
|
|
53
|
+
tasksTable,
|
|
54
|
+
widgetRows,
|
|
55
|
+
workersTable,
|
|
56
|
+
} from "./lib/format.ts";
|
|
57
|
+
import {
|
|
58
|
+
type BrowseResult,
|
|
59
|
+
type BrowseSession,
|
|
60
|
+
createBrowseComponent,
|
|
61
|
+
createDetailComponent,
|
|
62
|
+
detailTitle,
|
|
63
|
+
} from "./ui/browse.ts";
|
|
64
|
+
import { createJoinComponent, joinTitle } from "./ui/join.ts";
|
|
65
|
+
import {
|
|
66
|
+
type ModelRef,
|
|
67
|
+
formatModel,
|
|
68
|
+
pickAvailableModel,
|
|
69
|
+
probeArgs,
|
|
70
|
+
probeModel,
|
|
71
|
+
providerExtensions,
|
|
72
|
+
resolveExtensions,
|
|
73
|
+
resolveModelChoice,
|
|
74
|
+
} from "./lib/providers.ts";
|
|
75
|
+
import { redact } from "./lib/redact.ts";
|
|
76
|
+
import { type RunTemplate, findTemplate, listTemplates } from "./lib/templates.ts";
|
|
77
|
+
import { type PiInvocation, WorkerProcess, getPiInvocation } from "./lib/worker.ts";
|
|
78
|
+
|
|
79
|
+
const COORDINATOR_ACTIONS = [
|
|
80
|
+
"status",
|
|
81
|
+
"run_create",
|
|
82
|
+
"run_list",
|
|
83
|
+
"run_use",
|
|
84
|
+
"task_create",
|
|
85
|
+
"task_list",
|
|
86
|
+
"task_update",
|
|
87
|
+
"worker_start",
|
|
88
|
+
"worker_resume",
|
|
89
|
+
"worker_list",
|
|
90
|
+
"worker_show",
|
|
91
|
+
"worker_read",
|
|
92
|
+
"worker_stop",
|
|
93
|
+
"worker_keep_open",
|
|
94
|
+
"worker_send",
|
|
95
|
+
"wait",
|
|
96
|
+
"answer",
|
|
97
|
+
"gate_list",
|
|
98
|
+
"archive",
|
|
99
|
+
"search",
|
|
100
|
+
"metrics",
|
|
101
|
+
"export",
|
|
102
|
+
"prune",
|
|
103
|
+
"diff",
|
|
104
|
+
"budget",
|
|
105
|
+
"report",
|
|
106
|
+
"chat",
|
|
107
|
+
"reset",
|
|
108
|
+
] as const;
|
|
109
|
+
|
|
110
|
+
/** Tool result helper: one text block plus structured details for branching/rendering. */
|
|
111
|
+
function textResult(text: string, details: Record<string, unknown> = {}) {
|
|
112
|
+
return { content: [{ type: "text" as const, text }], details };
|
|
113
|
+
}
|
|
114
|
+
|
|
115
|
+
/** Command helper: show text in the transcript and, when available, as a notification. */
|
|
116
|
+
function notify(ctx: ExtensionContext, text: string, level: "info" | "warning" | "error" = "info"): void {
|
|
117
|
+
if (ctx.hasUI) {
|
|
118
|
+
try {
|
|
119
|
+
ctx.ui.notify(text, level);
|
|
120
|
+
return;
|
|
121
|
+
} catch {
|
|
122
|
+
// Fall through to a plain message.
|
|
123
|
+
}
|
|
124
|
+
}
|
|
125
|
+
process.stdout.write(`${text}\n`);
|
|
126
|
+
}
|
|
127
|
+
|
|
128
|
+
// ---------------------------------------------------------------------------
|
|
129
|
+
// entry point
|
|
130
|
+
// ---------------------------------------------------------------------------
|
|
131
|
+
|
|
132
|
+
export default function orchestraExtension(pi: ExtensionAPI): void {
|
|
133
|
+
if (process.env.PI_ORCHESTRA_WORKER === "1") {
|
|
134
|
+
registerWorkerTools(pi);
|
|
135
|
+
return;
|
|
136
|
+
}
|
|
137
|
+
registerCoordinator(pi);
|
|
138
|
+
}
|
|
139
|
+
|
|
140
|
+
// ---------------------------------------------------------------------------
|
|
141
|
+
// worker side
|
|
142
|
+
// ---------------------------------------------------------------------------
|
|
143
|
+
|
|
144
|
+
function registerWorkerTools(pi: ExtensionAPI): void {
|
|
145
|
+
const root = process.env.PI_ORCHESTRA_ROOT;
|
|
146
|
+
const dispatchId = process.env.PI_ORCHESTRA_DISPATCH;
|
|
147
|
+
if (!root || !dispatchId) return;
|
|
148
|
+
|
|
149
|
+
const timeoutDefault = Number(process.env.PI_ORCHESTRA_ANSWER_TIMEOUT_MS ?? 15 * 60 * 1000);
|
|
150
|
+
|
|
151
|
+
pi.registerTool({
|
|
152
|
+
name: "orchestra_ask",
|
|
153
|
+
label: "Ask coordinator",
|
|
154
|
+
description:
|
|
155
|
+
"Ask the orchestrator that dispatched you a question and block until it answers. Use this for a decision you should not make alone, or missing information. Ask one focused question at a time.",
|
|
156
|
+
promptSnippet: "Ask the orchestrator a blocking question when you need a decision",
|
|
157
|
+
promptGuidelines: [
|
|
158
|
+
"Use orchestra_ask when a decision belongs to the orchestrator (scope, destructive changes, missing credentials) instead of guessing.",
|
|
159
|
+
"Use orchestra_ask with a single focused question; do not ask several unrelated questions in one call.",
|
|
160
|
+
],
|
|
161
|
+
parameters: Type.Object({
|
|
162
|
+
question: Type.String({ description: "One focused question for the orchestrator." }),
|
|
163
|
+
options: Type.Optional(
|
|
164
|
+
Type.Array(Type.String(), { description: "Optional list of acceptable answers to choose from." }),
|
|
165
|
+
),
|
|
166
|
+
timeoutMs: Type.Optional(Type.Number({ description: "How long to wait for an answer (default 15m)." })),
|
|
167
|
+
}),
|
|
168
|
+
async execute(_toolCallId, params, signal) {
|
|
169
|
+
const entry = postQuestion(root, dispatchId, params.question, params.options);
|
|
170
|
+
const outcome = await waitForAnswer(root, dispatchId, entry.id, {
|
|
171
|
+
timeoutMs: params.timeoutMs ?? timeoutDefault,
|
|
172
|
+
signal,
|
|
173
|
+
});
|
|
174
|
+
if ("answer" in outcome) {
|
|
175
|
+
return {
|
|
176
|
+
content: [{ type: "text" as const, text: outcome.answer }],
|
|
177
|
+
details: { questionId: entry.id, answer: outcome.answer },
|
|
178
|
+
};
|
|
179
|
+
}
|
|
180
|
+
return {
|
|
181
|
+
content: [
|
|
182
|
+
{
|
|
183
|
+
type: "text" as const,
|
|
184
|
+
text:
|
|
185
|
+
outcome.reason === "aborted"
|
|
186
|
+
? "The question was cancelled before the orchestrator answered."
|
|
187
|
+
: "No answer arrived before the timeout. Continue with your best judgement and say so in your report.",
|
|
188
|
+
},
|
|
189
|
+
],
|
|
190
|
+
details: { questionId: entry.id, reason: outcome.reason },
|
|
191
|
+
isError: true,
|
|
192
|
+
};
|
|
193
|
+
},
|
|
194
|
+
});
|
|
195
|
+
}
|
|
196
|
+
|
|
197
|
+
// ---------------------------------------------------------------------------
|
|
198
|
+
// coordinator side
|
|
199
|
+
// ---------------------------------------------------------------------------
|
|
200
|
+
|
|
201
|
+
interface Runtime {
|
|
202
|
+
ready: boolean;
|
|
203
|
+
cwd: string;
|
|
204
|
+
root: string;
|
|
205
|
+
config: OrchestraConfig;
|
|
206
|
+
state: OrchestraState;
|
|
207
|
+
workers: Map<string, WorkerProcess>;
|
|
208
|
+
finalized: Set<string>;
|
|
209
|
+
pollTimer?: NodeJS.Timeout;
|
|
210
|
+
uiTimer?: NodeJS.Timeout;
|
|
211
|
+
uiDirty: boolean;
|
|
212
|
+
/** Per-dispatch budget timers (wrap-up + hard stop). */
|
|
213
|
+
budgetTimers: Map<string, NodeJS.Timeout[]>;
|
|
214
|
+
stallTimer?: NodeJS.Timeout;
|
|
215
|
+
stalled: Set<string>;
|
|
216
|
+
/** Dispatches whose process outlived a previous coordinator session. */
|
|
217
|
+
orphans: string[];
|
|
218
|
+
/** The worker whose chat is joined, with its live conversation. */
|
|
219
|
+
joined?: { dispatchId: string; blocks: ChatBlock[]; repaint?: () => void };
|
|
220
|
+
lastWidget?: string;
|
|
221
|
+
watchId?: string;
|
|
222
|
+
widgetMounted?: boolean;
|
|
223
|
+
widgetTui?: { requestRender(force?: boolean): void };
|
|
224
|
+
browseRepaint?: () => void;
|
|
225
|
+
agentScope: AgentScope;
|
|
226
|
+
}
|
|
227
|
+
|
|
228
|
+
/** Colour a widget row by its leading status glyph (theme is only available inside the mount). */
|
|
229
|
+
function colorizeWidget(theme: { fg(color: string, text: string): string }, line: string): string {
|
|
230
|
+
const glyph = line.trimStart()[0];
|
|
231
|
+
if (glyph === "●" || glyph === "◌" || glyph === "?") return theme.fg("accent", line);
|
|
232
|
+
if (glyph === "✗" || glyph === "⏱" || glyph === "☠") return theme.fg("error", line);
|
|
233
|
+
if (glyph === "✓") return theme.fg("success", line);
|
|
234
|
+
if (glyph === "…") return theme.fg("dim", line);
|
|
235
|
+
return line;
|
|
236
|
+
}
|
|
237
|
+
|
|
238
|
+
function registerCoordinator(pi: ExtensionAPI): void {
|
|
239
|
+
const runtime: Runtime = {
|
|
240
|
+
ready: false,
|
|
241
|
+
cwd: process.cwd(),
|
|
242
|
+
root: "",
|
|
243
|
+
config: DEFAULT_CONFIG,
|
|
244
|
+
state: { version: 1, seq: 0, runs: {}, tasks: {}, dispatches: {}, gates: {} },
|
|
245
|
+
workers: new Map(),
|
|
246
|
+
finalized: new Set(),
|
|
247
|
+
budgetTimers: new Map(),
|
|
248
|
+
stalled: new Set(),
|
|
249
|
+
orphans: [],
|
|
250
|
+
uiDirty: true,
|
|
251
|
+
agentScope: "both",
|
|
252
|
+
};
|
|
253
|
+
|
|
254
|
+
function ready(cwd: string): Runtime {
|
|
255
|
+
if (runtime.ready) return runtime;
|
|
256
|
+
runtime.cwd = cwd;
|
|
257
|
+
runtime.config = loadConfig(cwd).config;
|
|
258
|
+
runtime.root = resolveStateDir(cwd, runtime.config);
|
|
259
|
+
ensureStore(runtime.root);
|
|
260
|
+
runtime.state = loadState(runtime.root);
|
|
261
|
+
markInterruptedDispatches();
|
|
262
|
+
runtime.ready = true;
|
|
263
|
+
startTimers();
|
|
264
|
+
if (runtime.orphans.length > 0) {
|
|
265
|
+
const ids = runtime.orphans.map(shortId).join(", ");
|
|
266
|
+
notify(
|
|
267
|
+
cwd ? (lastCtx ?? ({} as ExtensionContext)) : ({} as ExtensionContext),
|
|
268
|
+
`${runtime.orphans.length} worker(s) from a previous session are still running (${ids}). /orchestra stop <id> kills the process; /orchestra resume <id> continues its work.`,
|
|
269
|
+
"warning",
|
|
270
|
+
);
|
|
271
|
+
}
|
|
272
|
+
return runtime;
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** Dispatches left "running" by a previous coordinator process cannot be reached any more. */
|
|
276
|
+
function markInterruptedDispatches(): void {
|
|
277
|
+
const detached = Object.values(runtime.state.dispatches).filter(
|
|
278
|
+
(dispatch: Dispatch) => !isTerminalStatus(dispatch.status) && !runtime.workers.has(dispatch.id),
|
|
279
|
+
);
|
|
280
|
+
const { orphaned, lost } = reconcileOrphans(runtime.state);
|
|
281
|
+
runtime.orphans = [];
|
|
282
|
+
let changed = detached.length > 0;
|
|
283
|
+
if (orphaned.length > 0) {
|
|
284
|
+
runtime.orphans = orphaned;
|
|
285
|
+
// Nothing to attach to, so the task is not "running" in this session any more.
|
|
286
|
+
for (const id of orphaned) {
|
|
287
|
+
const dispatch = runtime.state.dispatches[id];
|
|
288
|
+
if (!dispatch?.taskId) continue;
|
|
289
|
+
const task = runtime.state.tasks[dispatch.taskId];
|
|
290
|
+
if (task && task.status === "running") {
|
|
291
|
+
task.status = "pending";
|
|
292
|
+
task.dispatchId = undefined;
|
|
293
|
+
task.error = `Worker ${dispatch.id} is orphaned (pid ${dispatch.pid ?? "?"}).`;
|
|
294
|
+
task.updatedAt = nowIso();
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (lost.length > 0) {
|
|
299
|
+
for (const id of lost) {
|
|
300
|
+
const dispatch = runtime.state.dispatches[id];
|
|
301
|
+
if (!dispatch?.taskId) continue;
|
|
302
|
+
const task = runtime.state.tasks[dispatch.taskId];
|
|
303
|
+
if (task && task.status === "running") {
|
|
304
|
+
task.status = "failed";
|
|
305
|
+
task.error = "Worker lost after coordinator restart.";
|
|
306
|
+
task.updatedAt = nowIso();
|
|
307
|
+
}
|
|
308
|
+
}
|
|
309
|
+
}
|
|
310
|
+
// The dispatch is authoritative: a task must not keep a "failed" glyph after its
|
|
311
|
+
// worker settled, nor stay "running" after its worker timed out or was stopped.
|
|
312
|
+
for (const task of Object.values(runtime.state.tasks)) {
|
|
313
|
+
const dispatch = task.dispatchId ? runtime.state.dispatches[task.dispatchId] : undefined;
|
|
314
|
+
if (!dispatch) continue;
|
|
315
|
+
if (dispatch.status === "settled" && task.status !== "done") {
|
|
316
|
+
task.status = "done";
|
|
317
|
+
task.error = undefined;
|
|
318
|
+
task.updatedAt = nowIso();
|
|
319
|
+
changed = true;
|
|
320
|
+
} else if (
|
|
321
|
+
(dispatch.status === "failed" || dispatch.status === "timeout" || dispatch.status === "lost") &&
|
|
322
|
+
task.status !== "failed"
|
|
323
|
+
) {
|
|
324
|
+
task.status = "failed";
|
|
325
|
+
task.error = dispatch.error ?? `Worker ${dispatch.status}.`;
|
|
326
|
+
task.updatedAt = nowIso();
|
|
327
|
+
changed = true;
|
|
328
|
+
} else if (dispatch.status === "stopped" && task.status === "running") {
|
|
329
|
+
task.status = "pending";
|
|
330
|
+
task.dispatchId = undefined;
|
|
331
|
+
task.updatedAt = nowIso();
|
|
332
|
+
changed = true;
|
|
333
|
+
}
|
|
334
|
+
}
|
|
335
|
+
if (changed) {
|
|
336
|
+
refreshTaskReadiness(runtime.state);
|
|
337
|
+
saveState(runtime.root, runtime.state);
|
|
338
|
+
}
|
|
339
|
+
}
|
|
340
|
+
|
|
341
|
+
function startTimers(): void {
|
|
342
|
+
if (runtime.pollTimer) return;
|
|
343
|
+
runtime.pollTimer = setInterval(() => void pollMail(), 1000);
|
|
344
|
+
runtime.pollTimer.unref?.();
|
|
345
|
+
runtime.uiTimer = setInterval(() => {
|
|
346
|
+
if (!runtime.uiDirty && !runtime.watchId && !runtime.browseRepaint && !runtime.joined) return;
|
|
347
|
+
runtime.uiDirty = false;
|
|
348
|
+
refreshUI(lastCtx);
|
|
349
|
+
}, 500);
|
|
350
|
+
runtime.uiTimer.unref?.();
|
|
351
|
+
startStallWatch();
|
|
352
|
+
}
|
|
353
|
+
|
|
354
|
+
function stopTimers(): void {
|
|
355
|
+
if (runtime.pollTimer) clearInterval(runtime.pollTimer);
|
|
356
|
+
if (runtime.uiTimer) clearInterval(runtime.uiTimer);
|
|
357
|
+
if (runtime.stallTimer) clearInterval(runtime.stallTimer);
|
|
358
|
+
runtime.pollTimer = undefined;
|
|
359
|
+
runtime.uiTimer = undefined;
|
|
360
|
+
runtime.stallTimer = undefined;
|
|
361
|
+
}
|
|
362
|
+
|
|
363
|
+
let lastCtx: ExtensionContext | undefined;
|
|
364
|
+
|
|
365
|
+
function persist(): void {
|
|
366
|
+
saveState(runtime.root, runtime.state);
|
|
367
|
+
runtime.uiDirty = true;
|
|
368
|
+
}
|
|
369
|
+
|
|
370
|
+
/** The staleness window for `activeRun`, from `staleRunHours` (0 = keep every finished run current). */
|
|
371
|
+
function staleAfterMs(): number {
|
|
372
|
+
return Math.max(0, runtime.config.staleRunHours) * 60 * 60 * 1000;
|
|
373
|
+
}
|
|
374
|
+
|
|
375
|
+
/**
|
|
376
|
+
* The run this session works on: the active (or `/orchestra use` pinned) run, otherwise
|
|
377
|
+
* the newest run that is not stale. `undefined` in a fresh session whose previous runs
|
|
378
|
+
* finished hours ago — that is what keeps yesterday's run off today's screen.
|
|
379
|
+
*/
|
|
380
|
+
function currentRun(): Run | undefined {
|
|
381
|
+
return activeRun(runtime.state, { staleAfterMs: staleAfterMs() });
|
|
382
|
+
}
|
|
383
|
+
|
|
384
|
+
/** `ui.widget` (set by `/orchestra hide|show`) wins over the `widget` config key. */
|
|
385
|
+
function widgetMode(): "auto" | "always" | "off" {
|
|
386
|
+
return runtime.state.ui?.widget ?? runtime.config.widget;
|
|
387
|
+
}
|
|
388
|
+
|
|
389
|
+
/** Drop the widget body: used when nothing is live, when switched off, and on shutdown. */
|
|
390
|
+
function unmountWidget(ctx: ExtensionContext): void {
|
|
391
|
+
runtime.widgetMounted = false;
|
|
392
|
+
runtime.widgetTui = undefined;
|
|
393
|
+
runtime.lastWidget = undefined;
|
|
394
|
+
try {
|
|
395
|
+
ctx.ui.setWidget("orchestra", undefined);
|
|
396
|
+
} catch {
|
|
397
|
+
// Best effort: print/rpc modes have no widget surface.
|
|
398
|
+
}
|
|
399
|
+
}
|
|
400
|
+
|
|
401
|
+
function refreshUI(ctx: ExtensionContext | undefined): void {
|
|
402
|
+
if (!ctx?.hasUI) return;
|
|
403
|
+
try {
|
|
404
|
+
const mode = widgetMode();
|
|
405
|
+
const run = currentRun();
|
|
406
|
+
if (mode === "off") {
|
|
407
|
+
ctx.ui.setStatus("orchestra", undefined);
|
|
408
|
+
unmountWidget(ctx);
|
|
409
|
+
runtime.browseRepaint?.();
|
|
410
|
+
return;
|
|
411
|
+
}
|
|
412
|
+
// No current run (nothing here yet, or only older sessions' runs): leave both
|
|
413
|
+
// surfaces empty instead of summarising history that is not this session's work.
|
|
414
|
+
if (!run && !runtime.watchId) {
|
|
415
|
+
ctx.ui.setStatus("orchestra", undefined);
|
|
416
|
+
unmountWidget(ctx);
|
|
417
|
+
runtime.browseRepaint?.();
|
|
418
|
+
return;
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
ctx.ui.setStatus("orchestra", statusLine(runtime.state, run));
|
|
422
|
+
const lines = widgetText(run);
|
|
423
|
+
// `auto` mounts only while work is live; a watched transcript always shows.
|
|
424
|
+
const mounted = mode === "always" || Boolean(runtime.watchId) || hasLiveWork(runtime.state, run);
|
|
425
|
+
if (!mounted || lines.length === 0) {
|
|
426
|
+
unmountWidget(ctx);
|
|
427
|
+
} else if (ctx.mode === "tui") {
|
|
428
|
+
installWidget(ctx);
|
|
429
|
+
} else {
|
|
430
|
+
const key = lines.join("\n");
|
|
431
|
+
if (key !== runtime.lastWidget) {
|
|
432
|
+
runtime.lastWidget = key;
|
|
433
|
+
ctx.ui.setWidget("orchestra", lines);
|
|
434
|
+
}
|
|
435
|
+
}
|
|
436
|
+
runtime.browseRepaint?.();
|
|
437
|
+
} catch {
|
|
438
|
+
// UI is best effort (print/rpc modes have no widget surface).
|
|
439
|
+
}
|
|
440
|
+
}
|
|
441
|
+
|
|
442
|
+
/** The widget body: prioritised, capped and width-fitted by the render callback below. */
|
|
443
|
+
function widgetText(run: Run | undefined): string[] {
|
|
444
|
+
if (runtime.watchId) return watchLines(runtime.watchId);
|
|
445
|
+
if (!run) return [];
|
|
446
|
+
return widgetRows(runtime.state, run, {
|
|
447
|
+
maxLines: runtime.config.widgetMaxLines,
|
|
448
|
+
showSettled: runtime.config.widgetShowSettled,
|
|
449
|
+
});
|
|
450
|
+
}
|
|
451
|
+
|
|
452
|
+
/**
|
|
453
|
+
* Mount the widget once as a component so it can see the viewport width and fit
|
|
454
|
+
* rows instead of being clipped by pi. Later refreshes only invalidate + repaint.
|
|
455
|
+
*/
|
|
456
|
+
function installWidget(ctx: ExtensionContext): void {
|
|
457
|
+
if (runtime.widgetMounted) {
|
|
458
|
+
runtime.widgetTui?.requestRender();
|
|
459
|
+
return;
|
|
460
|
+
}
|
|
461
|
+
ctx.ui.setWidget("orchestra", (tui, theme) => {
|
|
462
|
+
runtime.widgetMounted = true;
|
|
463
|
+
runtime.widgetTui = tui;
|
|
464
|
+
return {
|
|
465
|
+
render(width: number) {
|
|
466
|
+
return widgetText(currentRun()).map((line) => colorizeWidget(theme, truncateToWidth(line, width)));
|
|
467
|
+
},
|
|
468
|
+
invalidate() {},
|
|
469
|
+
};
|
|
470
|
+
});
|
|
471
|
+
}
|
|
472
|
+
|
|
473
|
+
function watchLines(id: string): string[] {
|
|
474
|
+
const dispatch = runtime.state.dispatches[id];
|
|
475
|
+
if (!dispatch) return [`no dispatch ${id}`];
|
|
476
|
+
const entries = readTranscript(logPath(dispatch.id), 12);
|
|
477
|
+
return [
|
|
478
|
+
`${dispatchGlyph(dispatch)} ${dispatch.agent} ${shortId(dispatch.id)} ${dispatch.status}`,
|
|
479
|
+
...transcriptText(entries).split("\n").slice(-12),
|
|
480
|
+
];
|
|
481
|
+
}
|
|
482
|
+
|
|
483
|
+
function logPath(dispatchId: string): string {
|
|
484
|
+
return join(storePaths(runtime.root).logsDir, `${dispatchId}.jsonl`);
|
|
485
|
+
}
|
|
486
|
+
|
|
487
|
+
// -- mail / questions ---------------------------------------------------
|
|
488
|
+
|
|
489
|
+
async function pollMail(): Promise<void> {
|
|
490
|
+
if (!runtime.ready) return;
|
|
491
|
+
let changed = false;
|
|
492
|
+
for (const question of pendingQuestions(runtime.root)) {
|
|
493
|
+
if (runtime.state.gates[question.id]) continue;
|
|
494
|
+
const dispatch = runtime.state.dispatches[question.dispatchId];
|
|
495
|
+
if (!dispatch) continue;
|
|
496
|
+
const gate: Gate = {
|
|
497
|
+
id: question.id,
|
|
498
|
+
runId: dispatch.runId,
|
|
499
|
+
dispatchId: question.dispatchId,
|
|
500
|
+
question: question.question,
|
|
501
|
+
options: question.options,
|
|
502
|
+
status: "pending",
|
|
503
|
+
createdAt: question.createdAt,
|
|
504
|
+
};
|
|
505
|
+
runtime.state.gates[gate.id] = gate;
|
|
506
|
+
if (!isTerminalStatus(dispatch.status)) dispatch.status = "question";
|
|
507
|
+
changed = true;
|
|
508
|
+
wake(questionReport(gate), "orchestra-question", { gateId: gate.id, dispatchId: gate.dispatchId });
|
|
509
|
+
}
|
|
510
|
+
if (changed) persist();
|
|
511
|
+
}
|
|
512
|
+
|
|
513
|
+
function wake(content: string, customType: string, details: Record<string, unknown>): void {
|
|
514
|
+
try {
|
|
515
|
+
pi.sendMessage(
|
|
516
|
+
{ customType, content, display: true, details },
|
|
517
|
+
{ triggerTurn: true, deliverAs: "followUp" },
|
|
518
|
+
);
|
|
519
|
+
} catch {
|
|
520
|
+
// A wake-up must never break worker bookkeeping.
|
|
521
|
+
}
|
|
522
|
+
}
|
|
523
|
+
|
|
524
|
+
function answerGate(questionId: string, answer: string): Gate {
|
|
525
|
+
const gate = runtime.state.gates[questionId];
|
|
526
|
+
if (!gate) throw new Error(`Unknown question ${questionId}. Use action=gate_list to see pending questions.`);
|
|
527
|
+
if (gate.status === "answered") throw new Error(`Question ${questionId} was already answered.`);
|
|
528
|
+
writeAnswer(runtime.root, gate.dispatchId, gate.id, answer);
|
|
529
|
+
gate.status = "answered";
|
|
530
|
+
gate.answer = answer;
|
|
531
|
+
gate.answeredAt = nowIso();
|
|
532
|
+
const dispatch = runtime.state.dispatches[gate.dispatchId];
|
|
533
|
+
if (dispatch && dispatch.status === "question") dispatch.status = "running";
|
|
534
|
+
persist();
|
|
535
|
+
return gate;
|
|
536
|
+
}
|
|
537
|
+
|
|
538
|
+
// -- workers ------------------------------------------------------------
|
|
539
|
+
|
|
540
|
+
function resolveAgent(cwd: string, name?: string): ReturnType<typeof findAgent> {
|
|
541
|
+
const agentName = name?.trim() || runtime.config.defaultAgent;
|
|
542
|
+
return findAgent(cwd, agentName, runtime.agentScope);
|
|
543
|
+
}
|
|
544
|
+
|
|
545
|
+
function agentNames(cwd: string): string {
|
|
546
|
+
const names = discoverAgents(cwd, runtime.agentScope).map((agent) => agent.name);
|
|
547
|
+
return names.length > 0 ? names.join(", ") : "none (create ~/.pi/agent/agents/<name>.md)";
|
|
548
|
+
}
|
|
549
|
+
|
|
550
|
+
/** The coordinator's own model, as `{provider, id}`. */
|
|
551
|
+
function currentModel(ctx: ExtensionContext | undefined): ModelRef | undefined {
|
|
552
|
+
const model = ctx?.model as { id?: string; provider?: string } | undefined;
|
|
553
|
+
if (!model?.id) return undefined;
|
|
554
|
+
const provider = typeof model.provider === "string" ? model.provider : undefined;
|
|
555
|
+
return { provider, id: model.id };
|
|
556
|
+
}
|
|
557
|
+
|
|
558
|
+
/** Every model the coordinator can see, used to disambiguate a bare id. */
|
|
559
|
+
function knownModels(ctx: ExtensionContext | undefined): ModelRef[] {
|
|
560
|
+
try {
|
|
561
|
+
const models = ctx?.modelRegistry?.getAll() ?? [];
|
|
562
|
+
return models.map((model) => ({ provider: model.provider, id: model.id }));
|
|
563
|
+
} catch {
|
|
564
|
+
return [];
|
|
565
|
+
}
|
|
566
|
+
}
|
|
567
|
+
|
|
568
|
+
/** Extension files that make `provider` available in an isolated worker. */
|
|
569
|
+
function extensionsForProvider(provider: string | undefined, cwd: string): string[] {
|
|
570
|
+
if (!provider) return [];
|
|
571
|
+
try {
|
|
572
|
+
return providerExtensions(provider, cwd);
|
|
573
|
+
} catch {
|
|
574
|
+
return [];
|
|
575
|
+
}
|
|
576
|
+
}
|
|
577
|
+
|
|
578
|
+
/**
|
|
579
|
+
* Ask a throwaway pi process whether it can see `model` with the same flags
|
|
580
|
+
* the worker would get. Cached per model, so it costs one spawn at most.
|
|
581
|
+
*/
|
|
582
|
+
async function workerSees(model: ModelRef | undefined, extensions: string[], cwd: string): Promise<boolean> {
|
|
583
|
+
if (!model?.id) return true;
|
|
584
|
+
// Without isolation the worker loads the coordinator's extensions, so the
|
|
585
|
+
// coordinator's own registry already answers the question (and probing would
|
|
586
|
+
// mean loading this extension in a child process).
|
|
587
|
+
if (!runtime.config.workerIsolation) {
|
|
588
|
+
if (!model.provider) return true;
|
|
589
|
+
return knownModels(lastCtx).some((known) => known.id === model.id && known.provider === model.provider);
|
|
590
|
+
}
|
|
591
|
+
try {
|
|
592
|
+
const invocation = getPiInvocation(
|
|
593
|
+
probeArgs({ isolated: true, extensions }),
|
|
594
|
+
runtime.config.workerCommand,
|
|
595
|
+
);
|
|
596
|
+
return await probeModel({
|
|
597
|
+
command: invocation.command,
|
|
598
|
+
args: invocation.args,
|
|
599
|
+
cwd,
|
|
600
|
+
provider: model.provider,
|
|
601
|
+
id: model.id,
|
|
602
|
+
});
|
|
603
|
+
} catch {
|
|
604
|
+
return false;
|
|
605
|
+
}
|
|
606
|
+
}
|
|
607
|
+
|
|
608
|
+
function buildArgs(input: {
|
|
609
|
+
model?: string;
|
|
610
|
+
provider?: string;
|
|
611
|
+
thinking?: string;
|
|
612
|
+
tools?: string[];
|
|
613
|
+
systemPromptPath?: string;
|
|
614
|
+
extensions?: string[];
|
|
615
|
+
sessionId?: string;
|
|
616
|
+
}): string[] {
|
|
617
|
+
const args = ["--mode", "rpc"];
|
|
618
|
+
if (runtime.config.sessionMode === "no-session") args.push("--no-session");
|
|
619
|
+
else if (input.sessionId) args.push("--session-id", input.sessionId);
|
|
620
|
+
if (runtime.config.workerIsolation) {
|
|
621
|
+
// Load this extension only: no MCP servers, no other extensions, no interactive gates.
|
|
622
|
+
args.push("--no-extensions", "-e", selfExtensionPath());
|
|
623
|
+
for (const file of input.extensions ?? []) {
|
|
624
|
+
if (file !== selfExtensionPath()) args.push("-e", file);
|
|
625
|
+
}
|
|
626
|
+
}
|
|
627
|
+
// `--provider` first: a bare `--model deepseek/x` would otherwise be read as
|
|
628
|
+
// provider/id and silently resolve to another provider's model.
|
|
629
|
+
if (input.provider) args.push("--provider", input.provider);
|
|
630
|
+
if (input.model) args.push("--model", input.model);
|
|
631
|
+
if (input.thinking) args.push("--thinking", input.thinking);
|
|
632
|
+
if (input.tools && input.tools.length > 0) {
|
|
633
|
+
const tools = new Set(input.tools);
|
|
634
|
+
tools.add("orchestra_ask");
|
|
635
|
+
args.push("--tools", [...tools].join(","));
|
|
636
|
+
}
|
|
637
|
+
if (input.systemPromptPath) args.push("--append-system-prompt", input.systemPromptPath);
|
|
638
|
+
return args;
|
|
639
|
+
}
|
|
640
|
+
|
|
641
|
+
/** Absolute path of this extension file, used to load it explicitly into isolated workers. */
|
|
642
|
+
function selfExtensionPath(): string {
|
|
643
|
+
try {
|
|
644
|
+
return fileURLToPath(import.meta.url);
|
|
645
|
+
} catch {
|
|
646
|
+
return join(process.cwd(), "extensions", "orchestra.ts");
|
|
647
|
+
}
|
|
648
|
+
}
|
|
649
|
+
|
|
650
|
+
function clearBudgetTimers(dispatchId: string): void {
|
|
651
|
+
const timers = runtime.budgetTimers.get(dispatchId);
|
|
652
|
+
if (!timers) return;
|
|
653
|
+
for (const timer of timers) clearTimeout(timer);
|
|
654
|
+
runtime.budgetTimers.delete(dispatchId);
|
|
655
|
+
}
|
|
656
|
+
|
|
657
|
+
/** End a dispatch from the coordinator side and record why it happened. */
|
|
658
|
+
async function stopDispatch(
|
|
659
|
+
dispatch: Dispatch,
|
|
660
|
+
reason: NonNullable<Dispatch["stopReason"]>,
|
|
661
|
+
note: string,
|
|
662
|
+
): Promise<void> {
|
|
663
|
+
if (dispatch.stopReason) return;
|
|
664
|
+
dispatch.stopReason = reason;
|
|
665
|
+
dispatch.stopNote = note;
|
|
666
|
+
dispatch.error = note;
|
|
667
|
+
dispatch.endedAt = nowIso();
|
|
668
|
+
runtime.stalled.delete(dispatch.id);
|
|
669
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
670
|
+
if (worker && !worker.exited) {
|
|
671
|
+
await worker.abort().catch(() => undefined);
|
|
672
|
+
await worker.stop().catch(() => undefined);
|
|
673
|
+
}
|
|
674
|
+
persist();
|
|
675
|
+
if (lastCtx) notify(lastCtx, note, "warning");
|
|
676
|
+
}
|
|
677
|
+
|
|
678
|
+
/** Stop a worker from the browser or the command: kill it, free the task, persist. */
|
|
679
|
+
async function stopDispatchNow(dispatch: Dispatch, note = "Stopped from the browser."): Promise<void> {
|
|
680
|
+
// Record the reason before the process dies: finalize() runs from the exit
|
|
681
|
+
// handler and would otherwise classify this as a normal settle and report it
|
|
682
|
+
// that way in the wake-up.
|
|
683
|
+
dispatch.stopReason ??= "user";
|
|
684
|
+
dispatch.stopNote ??= note;
|
|
685
|
+
dispatch.endedAt ??= nowIso();
|
|
686
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
687
|
+
if (worker) {
|
|
688
|
+
await worker.abort().catch(() => undefined);
|
|
689
|
+
await worker.stop().catch(() => undefined);
|
|
690
|
+
runtime.workers.delete(dispatch.id);
|
|
691
|
+
}
|
|
692
|
+
clearBudgetTimers(dispatch.id);
|
|
693
|
+
runtime.stalled.delete(dispatch.id);
|
|
694
|
+
dispatch.status = "stopped";
|
|
695
|
+
dispatch.endedAt = nowIso();
|
|
696
|
+
const task = dispatch.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
|
|
697
|
+
if (task && task.dispatchId === dispatch.id) {
|
|
698
|
+
task.status = "pending";
|
|
699
|
+
task.dispatchId = undefined;
|
|
700
|
+
task.updatedAt = nowIso();
|
|
701
|
+
}
|
|
702
|
+
refreshTaskReadiness(runtime.state);
|
|
703
|
+
persist();
|
|
704
|
+
}
|
|
705
|
+
|
|
706
|
+
/** Cost ceiling for one worker, checked on every event it emits. */
|
|
707
|
+
function checkWorkerBudget(dispatch: Dispatch): void {
|
|
708
|
+
const budget = dispatch.budgetUsd;
|
|
709
|
+
if (!budget || budget <= 0 || dispatch.stopReason) return;
|
|
710
|
+
if (dispatch.usage.cost <= budget) return;
|
|
711
|
+
void stopDispatch(
|
|
712
|
+
dispatch,
|
|
713
|
+
"budget",
|
|
714
|
+
`Cost budget exceeded for ${dispatch.id}: $${dispatch.usage.cost.toFixed(4)} > $${budget.toFixed(2)}.`,
|
|
715
|
+
);
|
|
716
|
+
}
|
|
717
|
+
|
|
718
|
+
/**
|
|
719
|
+
* Wall-clock budget: unlike `timeoutMs` (a hard stop) this first asks the worker
|
|
720
|
+
* to wrap up, then stops it after a grace period.
|
|
721
|
+
*/
|
|
722
|
+
function startBudgetTimer(dispatch: Dispatch): void {
|
|
723
|
+
const budgetMs = dispatch.budgetMs ?? runtime.config.budgetMsPerWorker;
|
|
724
|
+
if (!budgetMs || budgetMs <= 0) return;
|
|
725
|
+
clearBudgetTimers(dispatch.id);
|
|
726
|
+
const grace = Math.max(0, runtime.config.budgetGraceMs);
|
|
727
|
+
const wrap = setTimeout(() => {
|
|
728
|
+
const current = runtime.state.dispatches[dispatch.id];
|
|
729
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
730
|
+
if (!current || !worker || worker.settled || current.stopReason) return;
|
|
731
|
+
current.stopNote = `Time budget reached (${Math.round(budgetMs / 1000)}s): asked to wrap up.`;
|
|
732
|
+
runtime.uiDirty = true;
|
|
733
|
+
void worker
|
|
734
|
+
.steer("Time budget reached. Stop starting new work, finish what you are doing, and reply with a short report now.")
|
|
735
|
+
.catch(() => undefined);
|
|
736
|
+
const hard = setTimeout(() => {
|
|
737
|
+
const latest = runtime.state.dispatches[dispatch.id];
|
|
738
|
+
if (latest && !isTerminalStatus(latest.status)) {
|
|
739
|
+
void stopDispatch(
|
|
740
|
+
latest,
|
|
741
|
+
"budget",
|
|
742
|
+
`Time budget exceeded for ${dispatch.id}: still running after ${Math.round((budgetMs + grace) / 1000)}s.`,
|
|
743
|
+
);
|
|
744
|
+
}
|
|
745
|
+
}, grace);
|
|
746
|
+
hard.unref?.();
|
|
747
|
+
runtime.budgetTimers.set(dispatch.id, [...(runtime.budgetTimers.get(dispatch.id) ?? []), hard]);
|
|
748
|
+
}, budgetMs);
|
|
749
|
+
wrap.unref?.();
|
|
750
|
+
runtime.budgetTimers.set(dispatch.id, [wrap]);
|
|
751
|
+
}
|
|
752
|
+
|
|
753
|
+
/** Once a run's cost ceiling is reached, stop its workers and refuse new ones. */
|
|
754
|
+
function checkRunBudget(run: Run): boolean {
|
|
755
|
+
const budget = run.budgetUsd ?? runtime.config.budgetUsdPerRun;
|
|
756
|
+
if (!budget || budget <= 0) return false;
|
|
757
|
+
const usage = totalUsage(runtime.state, run.id);
|
|
758
|
+
if (usage.cost <= budget) return false;
|
|
759
|
+
const ask = runtime.config.budgetAction === "ask";
|
|
760
|
+
const note = `Run budget exhausted: $${usage.cost.toFixed(4)} > $${budget.toFixed(2)}.`;
|
|
761
|
+
if (run.budgetNote === note && run.budgetPaused === ask) return true;
|
|
762
|
+
run.budgetNote = note;
|
|
763
|
+
run.updatedAt = nowIso();
|
|
764
|
+
if (ask) {
|
|
765
|
+
// Pause: live workers finish what they are doing, nothing new starts.
|
|
766
|
+
run.budgetPaused = true;
|
|
767
|
+
persist();
|
|
768
|
+
if (lastCtx) {
|
|
769
|
+
notify(
|
|
770
|
+
lastCtx,
|
|
771
|
+
`${note} Live workers keep running; new ones are paused. Raise it with orchestra action=budget usd=<n>.`,
|
|
772
|
+
"warning",
|
|
773
|
+
);
|
|
774
|
+
}
|
|
775
|
+
return true;
|
|
776
|
+
}
|
|
777
|
+
for (const dispatch of liveDispatches(runtime.state, run.id)) {
|
|
778
|
+
void stopDispatch(dispatch, "budget", note);
|
|
779
|
+
}
|
|
780
|
+
persist();
|
|
781
|
+
return true;
|
|
782
|
+
}
|
|
783
|
+
|
|
784
|
+
/** Flag (or stop) workers that have produced no events for `stallMs`. */
|
|
785
|
+
function startStallWatch(): void {
|
|
786
|
+
if (runtime.stallTimer) return;
|
|
787
|
+
runtime.stallTimer = setInterval(() => {
|
|
788
|
+
const stallMs = runtime.config.stallMs;
|
|
789
|
+
if (!stallMs || stallMs <= 0) return;
|
|
790
|
+
for (const dispatch of liveDispatches(runtime.state)) {
|
|
791
|
+
if (dispatch.status === "question" || dispatch.stalledAt) continue;
|
|
792
|
+
const last = Date.parse(dispatch.lastEventAt ?? dispatch.startedAt);
|
|
793
|
+
if (Number.isNaN(last)) continue;
|
|
794
|
+
const silent = Date.now() - last;
|
|
795
|
+
if (silent < stallMs) continue;
|
|
796
|
+
|
|
797
|
+
dispatch.stalledAt = nowIso();
|
|
798
|
+
runtime.stalled.add(dispatch.id);
|
|
799
|
+
runtime.uiDirty = true;
|
|
800
|
+
const message = `Worker ${dispatch.id} (${dispatch.agent}) has produced no events for ${Math.round(silent / 60000)}m${
|
|
801
|
+
dispatch.lastToolCall ? ` (last tool: ${dispatch.lastToolCall})` : ""
|
|
802
|
+
}.`;
|
|
803
|
+
if (runtime.config.stallAction === "abort") {
|
|
804
|
+
void stopDispatch(dispatch, "stall", `${message} Stopped by the stall watchdog.`);
|
|
805
|
+
} else {
|
|
806
|
+
persist();
|
|
807
|
+
if (lastCtx) notify(lastCtx, message, "warning");
|
|
808
|
+
}
|
|
809
|
+
}
|
|
810
|
+
}, 15_000);
|
|
811
|
+
runtime.stallTimer.unref?.();
|
|
812
|
+
}
|
|
813
|
+
|
|
814
|
+
/** Create a run and its tasks from a parsed template, wiring deps by title. */
|
|
815
|
+
function applyTemplate(template: RunTemplate, name?: string, goal?: string): { run: ReturnType<typeof createRun>; created: Task[] } {
|
|
816
|
+
const run = createRun(runtime.state, {
|
|
817
|
+
name: name ?? template.name,
|
|
818
|
+
goal: goal ?? template.goal,
|
|
819
|
+
template: template.name,
|
|
820
|
+
});
|
|
821
|
+
const ids = new Map<string, string>();
|
|
822
|
+
const created: Task[] = [];
|
|
823
|
+
for (const item of template.tasks) {
|
|
824
|
+
const deps: string[] = [];
|
|
825
|
+
for (const depTitle of item.deps) {
|
|
826
|
+
const id = ids.get(depTitle) ?? ids.get(depTitle.toLowerCase());
|
|
827
|
+
if (!id) {
|
|
828
|
+
throw new Error(
|
|
829
|
+
`Template task "${item.title}" depends on "${depTitle}", which must be defined earlier in the template.`,
|
|
830
|
+
);
|
|
831
|
+
}
|
|
832
|
+
deps.push(id);
|
|
833
|
+
}
|
|
834
|
+
const task = createTask(runtime.state, {
|
|
835
|
+
runId: run.id,
|
|
836
|
+
title: item.title,
|
|
837
|
+
description: item.description,
|
|
838
|
+
agent: item.agent ?? template.agent,
|
|
839
|
+
deps,
|
|
840
|
+
});
|
|
841
|
+
ids.set(item.title, task.id);
|
|
842
|
+
ids.set(item.title.toLowerCase(), task.id);
|
|
843
|
+
created.push(task);
|
|
844
|
+
}
|
|
845
|
+
return { run, created };
|
|
846
|
+
}
|
|
847
|
+
|
|
848
|
+
async function startWorker(input: {
|
|
849
|
+
ctx: ExtensionContext;
|
|
850
|
+
spec: string;
|
|
851
|
+
agentName?: string;
|
|
852
|
+
taskId?: string;
|
|
853
|
+
model?: string;
|
|
854
|
+
provider?: string;
|
|
855
|
+
thinking?: string;
|
|
856
|
+
tools?: string[];
|
|
857
|
+
budgetUsd?: number;
|
|
858
|
+
budgetMs?: number;
|
|
859
|
+
timeoutMs?: number;
|
|
860
|
+
timeoutMode?: "total" | "idle";
|
|
861
|
+
resumeFrom?: Dispatch;
|
|
862
|
+
retryOf?: Dispatch;
|
|
863
|
+
message?: string;
|
|
864
|
+
retries?: number;
|
|
865
|
+
}): Promise<{ dispatch: Dispatch; worker: WorkerProcess }> {
|
|
866
|
+
const cwd = runtime.cwd;
|
|
867
|
+
const live = liveDispatches(runtime.state, currentRun()?.id);
|
|
868
|
+
if (live.length >= runtime.config.maxConcurrency) {
|
|
869
|
+
throw new Error(
|
|
870
|
+
`Concurrency limit reached (${runtime.config.maxConcurrency} workers running). Wait for one to settle or raise maxConcurrency in .pi/orchestra.json.`,
|
|
871
|
+
);
|
|
872
|
+
}
|
|
873
|
+
|
|
874
|
+
const run = runOf(runtime.state, { staleAfterMs: staleAfterMs() });
|
|
875
|
+
if (checkRunBudget(run)) {
|
|
876
|
+
throw new Error(
|
|
877
|
+
run.budgetPaused
|
|
878
|
+
? `${run.budgetNote} The run is paused: raise it with orchestra action=budget usd=<n>.`
|
|
879
|
+
: `${run.budgetNote} Archive the run, raise budgetUsdPerRun, or start a new run.`,
|
|
880
|
+
);
|
|
881
|
+
}
|
|
882
|
+
let task: Task | undefined;
|
|
883
|
+
if (input.taskId) {
|
|
884
|
+
task = runtime.state.tasks[input.taskId];
|
|
885
|
+
if (!task) throw new Error(`Unknown task ${input.taskId}.`);
|
|
886
|
+
if (task.status === "running") throw new Error(`Task ${task.title} is already running (${task.dispatchId}).`);
|
|
887
|
+
if (task.status === "done" && !input.resumeFrom) throw new Error(`Task ${task.title} is already done.`);
|
|
888
|
+
if (task.status === "blocked") throw new Error(`Task ${task.title} is blocked by a failed dependency.`);
|
|
889
|
+
}
|
|
890
|
+
|
|
891
|
+
const agentName = input.agentName?.trim() || task?.agent || runtime.config.defaultAgent;
|
|
892
|
+
const agent = resolveAgent(cwd, agentName);
|
|
893
|
+
if (!agent) {
|
|
894
|
+
throw new Error(`Unknown agent "${agentName}". Available agents: ${agentNames(cwd)}.`);
|
|
895
|
+
}
|
|
896
|
+
|
|
897
|
+
const previous = input.resumeFrom ?? input.retryOf;
|
|
898
|
+
const override = runtime.config.agents[agent.name] ?? {};
|
|
899
|
+
const inherited = currentModel(input.ctx);
|
|
900
|
+
const requested: ModelRef | undefined = resolveModelChoice({
|
|
901
|
+
requested: { model: input.model ?? previous?.model, provider: input.provider ?? previous?.provider },
|
|
902
|
+
agent: {
|
|
903
|
+
model: override.model ?? agent.model,
|
|
904
|
+
provider: override.provider ?? agent.provider,
|
|
905
|
+
},
|
|
906
|
+
inherited,
|
|
907
|
+
known: knownModels(input.ctx),
|
|
908
|
+
inherit: runtime.config.inheritModel,
|
|
909
|
+
});
|
|
910
|
+
const thinking = input.thinking ?? previous?.thinking ?? override.thinking ?? agent.thinking;
|
|
911
|
+
const tools = input.tools ?? previous?.tools ?? override.tools ?? agent.tools;
|
|
912
|
+
|
|
913
|
+
// Make the provider available inside the isolated worker, then prove the worker
|
|
914
|
+
// really sees the model; otherwise use the coordinator's model instead of letting
|
|
915
|
+
// pi fuzzy-match something else.
|
|
916
|
+
const configuredExtensions = resolveExtensions(runtime.config.providerExtensions, cwd);
|
|
917
|
+
const extensionsFor = (model: ModelRef | undefined) => [
|
|
918
|
+
...new Set([...configuredExtensions, ...extensionsForProvider(model?.provider, cwd)]),
|
|
919
|
+
];
|
|
920
|
+
const picked = await pickAvailableModel({
|
|
921
|
+
requested,
|
|
922
|
+
inherited,
|
|
923
|
+
sees: (model) => workerSees(model, extensionsFor(model), cwd),
|
|
924
|
+
});
|
|
925
|
+
const model = picked.model;
|
|
926
|
+
const modelNote = picked.note;
|
|
927
|
+
const extensions = extensionsFor(model);
|
|
928
|
+
|
|
929
|
+
const spec = input.spec.trim() || input.resumeFrom?.spec.trim() || input.retryOf?.spec.trim() || "";
|
|
930
|
+
if (!spec) throw new Error("A worker needs a non-empty spec.");
|
|
931
|
+
|
|
932
|
+
// Only a stored session can be reopened; a no-session worker has nothing to resume.
|
|
933
|
+
if (input.resumeFrom && !input.resumeFrom.sessionId) {
|
|
934
|
+
throw new Error(
|
|
935
|
+
`Dispatch ${input.resumeFrom.id} has no stored session (sessionMode was "no-session"). Start a new worker, or set sessionMode: "session" so workers can be resumed.`,
|
|
936
|
+
);
|
|
937
|
+
}
|
|
938
|
+
const sessionId =
|
|
939
|
+
input.resumeFrom?.sessionId ??
|
|
940
|
+
(runtime.config.sessionMode === "session" ? `orchestra-${newId("session")}` : undefined);
|
|
941
|
+
|
|
942
|
+
const dispatch = createDispatch(runtime.state, {
|
|
943
|
+
runId: run.id,
|
|
944
|
+
taskId: task?.id,
|
|
945
|
+
agent: agent.name,
|
|
946
|
+
spec,
|
|
947
|
+
model: model?.id,
|
|
948
|
+
provider: model?.provider,
|
|
949
|
+
modelNote,
|
|
950
|
+
thinking,
|
|
951
|
+
tools,
|
|
952
|
+
budgetUsd: input.budgetUsd ?? (runtime.config.budgetUsdPerWorker || undefined),
|
|
953
|
+
budgetMs: input.budgetMs ?? (runtime.config.budgetMsPerWorker || undefined),
|
|
954
|
+
// `undefined` means "use the config"; an explicit 0 disables the limit.
|
|
955
|
+
timeoutMs: input.timeoutMs ?? input.retryOf?.timeoutMs ?? undefined,
|
|
956
|
+
timeoutMode: input.timeoutMode ?? input.retryOf?.timeoutMode ?? undefined,
|
|
957
|
+
sessionId,
|
|
958
|
+
resumedFrom: input.resumeFrom?.id,
|
|
959
|
+
retryOf: input.retryOf?.id,
|
|
960
|
+
// A retry continues the same work, so keep the original base commit.
|
|
961
|
+
baseCommit: input.retryOf?.baseCommit ?? gitHead(cwd),
|
|
962
|
+
attempt: (input.retryOf?.attempt ?? 0) + 1,
|
|
963
|
+
retries: input.retries ?? input.retryOf?.retries ?? runtime.config.retries,
|
|
964
|
+
keepOpen: runtime.config.keepOpen,
|
|
965
|
+
});
|
|
966
|
+
|
|
967
|
+
if (input.resumeFrom && task) {
|
|
968
|
+
task.status = "running";
|
|
969
|
+
task.dispatchId = dispatch.id;
|
|
970
|
+
task.updatedAt = nowIso();
|
|
971
|
+
}
|
|
972
|
+
|
|
973
|
+
let systemPromptPath: string | undefined;
|
|
974
|
+
if (agent.systemPrompt.trim()) {
|
|
975
|
+
const promptsDir = join(runtime.root, "prompts");
|
|
976
|
+
mkdirSync(promptsDir, { recursive: true });
|
|
977
|
+
systemPromptPath = join(promptsDir, `${dispatch.id}.md`);
|
|
978
|
+
writeFileSync(systemPromptPath, `${agent.systemPrompt}\n`, "utf8");
|
|
979
|
+
}
|
|
980
|
+
|
|
981
|
+
const invocation: PiInvocation = getPiInvocation(
|
|
982
|
+
buildArgs({
|
|
983
|
+
model: model?.id,
|
|
984
|
+
provider: model?.provider,
|
|
985
|
+
thinking,
|
|
986
|
+
tools,
|
|
987
|
+
systemPromptPath,
|
|
988
|
+
extensions,
|
|
989
|
+
sessionId,
|
|
990
|
+
}),
|
|
991
|
+
runtime.config.workerCommand,
|
|
992
|
+
);
|
|
993
|
+
|
|
994
|
+
const worker = new WorkerProcess({
|
|
995
|
+
cwd,
|
|
996
|
+
command: invocation.command,
|
|
997
|
+
args: invocation.args,
|
|
998
|
+
env: {
|
|
999
|
+
PI_ORCHESTRA_WORKER: "1",
|
|
1000
|
+
PI_ORCHESTRA_ROOT: runtime.root,
|
|
1001
|
+
PI_ORCHESTRA_DISPATCH: dispatch.id,
|
|
1002
|
+
PI_ORCHESTRA_RUN: run.id,
|
|
1003
|
+
PI_ORCHESTRA_COORDINATOR_PID: String(process.pid),
|
|
1004
|
+
},
|
|
1005
|
+
logPath: logPath(dispatch.id),
|
|
1006
|
+
timeoutMs: dispatch.timeoutMs ?? runtime.config.timeoutMs,
|
|
1007
|
+
timeoutMode: dispatch.timeoutMode ?? runtime.config.timeoutMode,
|
|
1008
|
+
onEvent: (event) => {
|
|
1009
|
+
const current = runtime.state.dispatches[dispatch.id];
|
|
1010
|
+
if (!current) return;
|
|
1011
|
+
if (event.type === "tool_execution_start" && typeof event.toolName === "string") {
|
|
1012
|
+
current.lastToolCall = event.toolName;
|
|
1013
|
+
}
|
|
1014
|
+
current.usage = { ...worker.usage };
|
|
1015
|
+
current.lastEventAt = nowIso();
|
|
1016
|
+
if (current.stalledAt) {
|
|
1017
|
+
current.stalledAt = undefined;
|
|
1018
|
+
runtime.stalled.delete(current.id);
|
|
1019
|
+
if (runtime.config.notifyOnSettle) {
|
|
1020
|
+
void pi.sendMessage({
|
|
1021
|
+
content: `Worker ${current.id} (${current.agent}) is producing events again after a stall.`,
|
|
1022
|
+
triggerTurn: false,
|
|
1023
|
+
}).catch(() => undefined);
|
|
1024
|
+
}
|
|
1025
|
+
}
|
|
1026
|
+
const joined = runtime.joined;
|
|
1027
|
+
if (joined && joined.dispatchId === current.id) {
|
|
1028
|
+
const blocks = chatBlockFromEvent(event);
|
|
1029
|
+
if (blocks.length > 0) {
|
|
1030
|
+
joined.blocks.push(...blocks);
|
|
1031
|
+
joined.repaint?.();
|
|
1032
|
+
}
|
|
1033
|
+
}
|
|
1034
|
+
runtime.uiDirty = true;
|
|
1035
|
+
checkWorkerBudget(current);
|
|
1036
|
+
},
|
|
1037
|
+
onSettled: () => void finalize(dispatch.id),
|
|
1038
|
+
onExit: () => void finalize(dispatch.id),
|
|
1039
|
+
onTimeout: () => {
|
|
1040
|
+
const current = runtime.state.dispatches[dispatch.id];
|
|
1041
|
+
if (current && !isTerminalStatus(current.status)) current.status = "timeout";
|
|
1042
|
+
persist();
|
|
1043
|
+
},
|
|
1044
|
+
});
|
|
1045
|
+
|
|
1046
|
+
runtime.workers.set(dispatch.id, worker);
|
|
1047
|
+
startBudgetTimer(dispatch);
|
|
1048
|
+
try {
|
|
1049
|
+
worker.start();
|
|
1050
|
+
} catch (error) {
|
|
1051
|
+
dispatch.status = "failed";
|
|
1052
|
+
dispatch.error = error instanceof Error ? error.message : String(error);
|
|
1053
|
+
dispatch.endedAt = nowIso();
|
|
1054
|
+
persist();
|
|
1055
|
+
throw error;
|
|
1056
|
+
}
|
|
1057
|
+
|
|
1058
|
+
dispatch.pid = worker.pid;
|
|
1059
|
+
dispatch.status = "running";
|
|
1060
|
+
if (worker.pid === undefined) dispatch.pid = undefined;
|
|
1061
|
+
persist();
|
|
1062
|
+
|
|
1063
|
+
const prompt = input.resumeFrom
|
|
1064
|
+
? resumePreamble(dispatch, run.name, cwd, input.resumeFrom, input.message)
|
|
1065
|
+
: input.retryOf
|
|
1066
|
+
? retryPreamble(dispatch, run.name, cwd, input.retryOf, spec, input.message)
|
|
1067
|
+
: workerPreamble(dispatch, run.name, cwd, spec);
|
|
1068
|
+
try {
|
|
1069
|
+
await worker.prompt(prompt);
|
|
1070
|
+
} catch (error) {
|
|
1071
|
+
dispatch.status = "failed";
|
|
1072
|
+
dispatch.error = error instanceof Error ? error.message : String(error);
|
|
1073
|
+
await worker.stop();
|
|
1074
|
+
persist();
|
|
1075
|
+
throw error;
|
|
1076
|
+
}
|
|
1077
|
+
|
|
1078
|
+
return { dispatch, worker };
|
|
1079
|
+
}
|
|
1080
|
+
|
|
1081
|
+
function workerPreamble(dispatch: Dispatch, runName: string, cwd: string, spec: string): string {
|
|
1082
|
+
return [
|
|
1083
|
+
`You are worker ${dispatch.id} (agent "${dispatch.agent}") in run "${runName}", dispatched by a pi orchestrator.`,
|
|
1084
|
+
`Working directory: ${cwd}`,
|
|
1085
|
+
"",
|
|
1086
|
+
"## Task",
|
|
1087
|
+
spec,
|
|
1088
|
+
"",
|
|
1089
|
+
"## Rules",
|
|
1090
|
+
"- Work autonomously; you own this task until you report back.",
|
|
1091
|
+
"- If you need a decision that belongs to the orchestrator, call `orchestra_ask` with one focused question. It blocks until the orchestrator answers.",
|
|
1092
|
+
"- Do not start other workers or delegate; report back instead.",
|
|
1093
|
+
"- Finish with a short report: what you changed, evidence (commands and key output), and anything unfinished.",
|
|
1094
|
+
].join("\n");
|
|
1095
|
+
}
|
|
1096
|
+
|
|
1097
|
+
/** Prompt for a resumed session: the context is already there, only the delta matters. */
|
|
1098
|
+
function resumePreamble(
|
|
1099
|
+
dispatch: Dispatch,
|
|
1100
|
+
runName: string,
|
|
1101
|
+
cwd: string,
|
|
1102
|
+
previous: Dispatch,
|
|
1103
|
+
message?: string,
|
|
1104
|
+
): string {
|
|
1105
|
+
return [
|
|
1106
|
+
`You are worker ${dispatch.id} (agent "${dispatch.agent}"), resuming dispatch ${previous.id} in run "${runName}".`,
|
|
1107
|
+
`Your earlier session ended as ${previous.status}${previous.error ? `: ${previous.error}` : ""}. Your context is intact; do not redo finished work.`,
|
|
1108
|
+
`Working directory: ${cwd}`,
|
|
1109
|
+
"",
|
|
1110
|
+
"## Continue with",
|
|
1111
|
+
(message ?? "Continue where you stopped, finish the task, and report what changed.").trim(),
|
|
1112
|
+
"",
|
|
1113
|
+
"## Rules",
|
|
1114
|
+
"- Work autonomously; you own this task until you report back.",
|
|
1115
|
+
"- If you need a decision that belongs to the orchestrator, call `orchestra_ask` with one focused question.",
|
|
1116
|
+
"- Finish with a short report: what you changed, evidence, and anything unfinished.",
|
|
1117
|
+
].join("\n");
|
|
1118
|
+
}
|
|
1119
|
+
|
|
1120
|
+
/** Queue a repair dispatch when the policy allows one. */
|
|
1121
|
+
function scheduleRetry(dispatch: Dispatch): void {
|
|
1122
|
+
const decision = planRetry(dispatch, runtime.config, { runExhausted: Boolean(dispatch.budgetUsd) });
|
|
1123
|
+
if (!decision.retry) return;
|
|
1124
|
+
dispatch.retryAt = new Date(Date.now() + decision.delayMs).toISOString();
|
|
1125
|
+
persist();
|
|
1126
|
+
if (lastCtx) {
|
|
1127
|
+
notify(lastCtx, `Retrying ${dispatch.id} (${decision.reason}) after ${dispatch.status}.`);
|
|
1128
|
+
}
|
|
1129
|
+
const timer = setTimeout(() => {
|
|
1130
|
+
const current = runtime.state.dispatches[dispatch.id];
|
|
1131
|
+
if (!current) return;
|
|
1132
|
+
current.retryAt = undefined;
|
|
1133
|
+
void startWorker({
|
|
1134
|
+
ctx: lastCtx as ExtensionContext,
|
|
1135
|
+
spec: current.spec,
|
|
1136
|
+
agentName: current.agent,
|
|
1137
|
+
taskId: current.taskId,
|
|
1138
|
+
model: current.model,
|
|
1139
|
+
provider: current.provider,
|
|
1140
|
+
thinking: current.thinking,
|
|
1141
|
+
tools: current.tools,
|
|
1142
|
+
budgetUsd: current.budgetUsd,
|
|
1143
|
+
budgetMs: current.budgetMs,
|
|
1144
|
+
timeoutMs: current.timeoutMs,
|
|
1145
|
+
timeoutMode: current.timeoutMode,
|
|
1146
|
+
retryOf: current,
|
|
1147
|
+
}).catch((error) => {
|
|
1148
|
+
if (lastCtx) notify(lastCtx, `Retry of ${current.id} failed: ${error instanceof Error ? error.message : String(error)}`, "error");
|
|
1149
|
+
});
|
|
1150
|
+
}, decision.delayMs);
|
|
1151
|
+
timer.unref?.();
|
|
1152
|
+
}
|
|
1153
|
+
|
|
1154
|
+
/** Prompt for a repair attempt: the old failure is part of the brief. */
|
|
1155
|
+
function retryPreamble(
|
|
1156
|
+
dispatch: Dispatch,
|
|
1157
|
+
runName: string,
|
|
1158
|
+
cwd: string,
|
|
1159
|
+
previous: Dispatch,
|
|
1160
|
+
spec: string,
|
|
1161
|
+
message?: string,
|
|
1162
|
+
): string {
|
|
1163
|
+
const report = (previous.summary ?? "").trim();
|
|
1164
|
+
return [
|
|
1165
|
+
`You are worker ${dispatch.id} (agent "${dispatch.agent}") in run "${runName}". This is a repair attempt for dispatch ${previous.id}, which ended as ${previous.status}.`,
|
|
1166
|
+
`Working directory: ${cwd}`,
|
|
1167
|
+
"",
|
|
1168
|
+
"## Previous attempt",
|
|
1169
|
+
previous.error ? `error: ${previous.error}` : "error: (none recorded)",
|
|
1170
|
+
previous.lastToolCall ? `last tool: ${previous.lastToolCall}` : "",
|
|
1171
|
+
report ? `report:\n${report.length > 2000 ? `${report.slice(0, 2000)}\n…[truncated]` : report}` : "",
|
|
1172
|
+
"",
|
|
1173
|
+
"## Task",
|
|
1174
|
+
spec,
|
|
1175
|
+
message ? `\n## Note from the orchestrator\n${message}` : "",
|
|
1176
|
+
"",
|
|
1177
|
+
"## Rules",
|
|
1178
|
+
"- Do not repeat work the previous attempt already finished; verify the tree first (git status, diff).",
|
|
1179
|
+
"- Work autonomously; you own this task until you report back.",
|
|
1180
|
+
"- If you need a decision that belongs to the orchestrator, call `orchestra_ask` with one focused question.",
|
|
1181
|
+
"- Finish with a short report: what you changed, evidence, and what is still blocking.",
|
|
1182
|
+
]
|
|
1183
|
+
.filter((line) => line !== undefined)
|
|
1184
|
+
.join("\n");
|
|
1185
|
+
}
|
|
1186
|
+
|
|
1187
|
+
async function finalize(dispatchId: string): Promise<void> {
|
|
1188
|
+
if (runtime.finalized.has(dispatchId)) return;
|
|
1189
|
+
const dispatch = runtime.state.dispatches[dispatchId];
|
|
1190
|
+
const worker = runtime.workers.get(dispatchId);
|
|
1191
|
+
if (!dispatch || !worker) return;
|
|
1192
|
+
// Wait a tick so a settle event that lands together with exit is observed first.
|
|
1193
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
1194
|
+
if (runtime.finalized.has(dispatchId)) return;
|
|
1195
|
+
runtime.finalized.add(dispatchId);
|
|
1196
|
+
|
|
1197
|
+
clearBudgetTimers(dispatchId);
|
|
1198
|
+
runtime.stalled.delete(dispatchId);
|
|
1199
|
+
const text = await worker.lastText();
|
|
1200
|
+
dispatch.usage = { ...worker.usage };
|
|
1201
|
+
dispatch.summary = text ? redact(text) : undefined;
|
|
1202
|
+
dispatch.endedAt = nowIso();
|
|
1203
|
+
dispatch.settledAt = worker.settled ? nowIso() : undefined;
|
|
1204
|
+
dispatch.exitCode = worker.exitCode;
|
|
1205
|
+
dispatch.signal = worker.exitSignal;
|
|
1206
|
+
dispatch.aborted = worker.aborted;
|
|
1207
|
+
|
|
1208
|
+
if (dispatch.stopReason === "budget" || dispatch.stopReason === "stall") {
|
|
1209
|
+
dispatch.status = "failed";
|
|
1210
|
+
dispatch.error ??= dispatch.stopNote;
|
|
1211
|
+
} else if (dispatch.stopReason === "user") {
|
|
1212
|
+
dispatch.status = "stopped";
|
|
1213
|
+
} else if (dispatch.status === "timeout") {
|
|
1214
|
+
// keep timeout
|
|
1215
|
+
} else if (worker.settled) {
|
|
1216
|
+
dispatch.status = worker.aborted ? "stopped" : "settled";
|
|
1217
|
+
} else if (worker.killed) {
|
|
1218
|
+
dispatch.status = "stopped";
|
|
1219
|
+
} else {
|
|
1220
|
+
dispatch.status = "failed";
|
|
1221
|
+
dispatch.error ??=
|
|
1222
|
+
redact(worker.getStderr().trim().split("\n").slice(-3).join("\n")) || "Worker exited before settling.";
|
|
1223
|
+
}
|
|
1224
|
+
|
|
1225
|
+
if (dispatch.taskId) {
|
|
1226
|
+
const task = runtime.state.tasks[dispatch.taskId];
|
|
1227
|
+
if (task) {
|
|
1228
|
+
if (dispatch.status === "settled") {
|
|
1229
|
+
task.status = "done";
|
|
1230
|
+
task.result = text || undefined;
|
|
1231
|
+
} else if (dispatch.status === "stopped") {
|
|
1232
|
+
task.status = "pending";
|
|
1233
|
+
task.dispatchId = undefined;
|
|
1234
|
+
} else {
|
|
1235
|
+
task.status = "failed";
|
|
1236
|
+
task.error = dispatch.error ?? dispatch.status;
|
|
1237
|
+
}
|
|
1238
|
+
task.updatedAt = nowIso();
|
|
1239
|
+
}
|
|
1240
|
+
}
|
|
1241
|
+
refreshTaskReadiness(runtime.state);
|
|
1242
|
+
persist();
|
|
1243
|
+
|
|
1244
|
+
if (!runtime.config.keepOpen) {
|
|
1245
|
+
await worker.stop();
|
|
1246
|
+
runtime.workers.delete(dispatchId);
|
|
1247
|
+
}
|
|
1248
|
+
|
|
1249
|
+
// Queue a repair dispatch before the wake-up, so the report can mention it.
|
|
1250
|
+
scheduleRetry(dispatch);
|
|
1251
|
+
|
|
1252
|
+
if (runtime.config.notifyOnSettle) {
|
|
1253
|
+
const task = dispatch.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
|
|
1254
|
+
wake(dispatchReport(dispatch, task, text), "orchestra", {
|
|
1255
|
+
dispatchId,
|
|
1256
|
+
status: dispatch.status,
|
|
1257
|
+
usage: dispatch.usage,
|
|
1258
|
+
});
|
|
1259
|
+
}
|
|
1260
|
+
}
|
|
1261
|
+
|
|
1262
|
+
// -- tools --------------------------------------------------------------
|
|
1263
|
+
|
|
1264
|
+
pi.registerTool({
|
|
1265
|
+
name: "orchestra",
|
|
1266
|
+
label: "Orchestra",
|
|
1267
|
+
description:
|
|
1268
|
+
"Orchestrate worker agents from inside pi. Manage the active run, its tasks and its worker dispatches: start workers, list/inspect/read/stop them, answer their questions, and reset state. Prefer one tool call per action. Workers run in the background: after starting one you can end your turn and you will be woken when it settles or asks a question.",
|
|
1269
|
+
promptSnippet: "Coordinate pi worker agents: runs, tasks, dispatches, questions",
|
|
1270
|
+
promptGuidelines: [
|
|
1271
|
+
"Use orchestra action=worker_start to start a pi worker agent for a self-contained task; give each worker a complete spec with a definition of done.",
|
|
1272
|
+
"Use orchestra action=worker_list before starting more workers, and keep at most 4 running unless the user asks otherwise.",
|
|
1273
|
+
"After worker_start, end your turn instead of blocking: you are woken when a worker settles or asks a question, so the user stays free to work. Use orchestra_wait only when nothing else can proceed (or the user asked you to wait).",
|
|
1274
|
+
"Never poll worker_list in a loop; a single orchestra_wait with a timeout replaces polling.",
|
|
1275
|
+
"Use orchestra_answer when a worker is blocked on a question (see action=gate_list).",
|
|
1276
|
+
"Use orchestra_send to steer a running worker or to give a settled one follow-up work.",
|
|
1277
|
+
],
|
|
1278
|
+
parameters: Type.Object({
|
|
1279
|
+
action: StringEnum(COORDINATOR_ACTIONS),
|
|
1280
|
+
runId: Type.Optional(Type.String()),
|
|
1281
|
+
name: Type.Optional(Type.String()),
|
|
1282
|
+
goal: Type.Optional(Type.String()),
|
|
1283
|
+
taskId: Type.Optional(Type.String()),
|
|
1284
|
+
title: Type.Optional(Type.String()),
|
|
1285
|
+
description: Type.Optional(Type.String()),
|
|
1286
|
+
agent: Type.Optional(Type.String()),
|
|
1287
|
+
model: Type.Optional(Type.String({ description: "Model id for the worker (default: inherit the coordinator's)." })),
|
|
1288
|
+
provider: Type.Optional(Type.String({ description: "Provider that serves `model`, when the id alone is ambiguous." })),
|
|
1289
|
+
thinking: Type.Optional(Type.String()),
|
|
1290
|
+
tools: Type.Optional(Type.Array(Type.String())),
|
|
1291
|
+
spec: Type.Optional(Type.String()),
|
|
1292
|
+
dispatch: Type.Optional(Type.String()),
|
|
1293
|
+
questionId: Type.Optional(Type.String()),
|
|
1294
|
+
answer: Type.Optional(Type.String()),
|
|
1295
|
+
status: Type.Optional(Type.String({ description: "task_update: new status." })),
|
|
1296
|
+
deps: Type.Optional(
|
|
1297
|
+
Type.Array(Type.String(), {
|
|
1298
|
+
description: "task_update: replace a task's dependencies (cycles and unknown ids are refused).",
|
|
1299
|
+
}),
|
|
1300
|
+
),
|
|
1301
|
+
timeoutMs: Type.Optional(
|
|
1302
|
+
Type.Number({ description: "worker_start: hard limit for this worker in ms (0 = no limit)." }),
|
|
1303
|
+
),
|
|
1304
|
+
timeoutMode: Type.Optional(
|
|
1305
|
+
StringEnum(["total", "idle"], {
|
|
1306
|
+
description:
|
|
1307
|
+
"worker_start: count timeoutMs from spawn (total) or restart it on every event (idle, safe for long jobs).",
|
|
1308
|
+
}),
|
|
1309
|
+
),
|
|
1310
|
+
tailLines: Type.Optional(Type.Number()),
|
|
1311
|
+
keep: Type.Optional(Type.Number({ description: "archive: how many of the newest runs to keep (default 5)." })),
|
|
1312
|
+
format: Type.Optional(
|
|
1313
|
+
StringEnum(["jsonl", "json", "md"] as const, {
|
|
1314
|
+
description: "export: file format (default jsonl); report: md writes exports/<runId>.md.",
|
|
1315
|
+
}),
|
|
1316
|
+
),
|
|
1317
|
+
days: Type.Optional(
|
|
1318
|
+
Type.Number({ description: "prune: delete archived runs and orphaned files older than this many days (default 30)." }),
|
|
1319
|
+
),
|
|
1320
|
+
dryRun: Type.Optional(Type.Boolean({ description: "prune: report what would be deleted without deleting." })),
|
|
1321
|
+
// action=budget reuses `budgetUsd`.
|
|
1322
|
+
budgetUsd: Type.Optional(
|
|
1323
|
+
Type.Number({ description: "Cost ceiling in USD for this worker (worker_start) or run (run_create)." }),
|
|
1324
|
+
),
|
|
1325
|
+
budgetMs: Type.Optional(
|
|
1326
|
+
Type.Number({ description: "Wall-clock budget in ms for this worker: wrap up, then stop after a grace period." }),
|
|
1327
|
+
),
|
|
1328
|
+
template: Type.Optional(
|
|
1329
|
+
Type.String({ description: "run_create: build the run and its tasks from .pi/orchestra/templates/<name>.md." }),
|
|
1330
|
+
),
|
|
1331
|
+
message: Type.Optional(
|
|
1332
|
+
Type.String({ description: "Message for a resumed or retried worker; on resume it defaults to 'continue where you stopped'." }),
|
|
1333
|
+
),
|
|
1334
|
+
retryOf: Type.Optional(
|
|
1335
|
+
Type.String({ description: "worker_start: repair this dispatch — reuse its spec/agent/tools and prepend the failure." }),
|
|
1336
|
+
),
|
|
1337
|
+
retries: Type.Optional(
|
|
1338
|
+
Type.Number({ description: "worker_start: extra attempts after a failure (0 = none, default from config)." }),
|
|
1339
|
+
),
|
|
1340
|
+
includeThinking: Type.Optional(
|
|
1341
|
+
Type.Boolean({ description: "chat: include the worker's thinking blocks." }),
|
|
1342
|
+
),
|
|
1343
|
+
filter: Type.Optional(
|
|
1344
|
+
Type.String({ description: "Only rows matching this text (title, id, agent or status). Used by status/task_list/worker_list." }),
|
|
1345
|
+
),
|
|
1346
|
+
limit: Type.Optional(Type.Number({ description: "Maximum rows to return (default 20 for lists)." })),
|
|
1347
|
+
offset: Type.Optional(Type.Number({ description: "Skip this many rows before returning; the footer says what is left." })),
|
|
1348
|
+
}),
|
|
1349
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1350
|
+
lastCtx = ctx;
|
|
1351
|
+
ready(ctx.cwd);
|
|
1352
|
+
|
|
1353
|
+
switch (params.action) {
|
|
1354
|
+
case "status": {
|
|
1355
|
+
const run = currentRun();
|
|
1356
|
+
if (!run) {
|
|
1357
|
+
return textResult(
|
|
1358
|
+
`orchestra: no run yet. Create one with action=run_create, then add tasks with action=task_create. Agents: ${agentNames(ctx.cwd)}.`,
|
|
1359
|
+
);
|
|
1360
|
+
}
|
|
1361
|
+
const body = [
|
|
1362
|
+
runSummary(runtime.state, run),
|
|
1363
|
+
"",
|
|
1364
|
+
"## Tasks",
|
|
1365
|
+
tasksTable(runtime.state, run.id, { filter: params.filter, limit: params.limit ?? 12, offset: params.offset }),
|
|
1366
|
+
"",
|
|
1367
|
+
"## Workers",
|
|
1368
|
+
workersTable(runtime.state, run.id, { filter: params.filter, limit: 6, offset: 0 }),
|
|
1369
|
+
"",
|
|
1370
|
+
"Use action=task_list or action=worker_list with filter/limit/offset for more.",
|
|
1371
|
+
].join("\n");
|
|
1372
|
+
return textResult(body, { runId: run.id });
|
|
1373
|
+
}
|
|
1374
|
+
|
|
1375
|
+
case "run_create": {
|
|
1376
|
+
if (params.template) {
|
|
1377
|
+
const template = findTemplate(ctx.cwd, params.template);
|
|
1378
|
+
if (!template) {
|
|
1379
|
+
const available = listTemplates(ctx.cwd).map((entry) => entry.name);
|
|
1380
|
+
throw new Error(
|
|
1381
|
+
`Unknown template "${params.template}". Available: ${available.length > 0 ? available.join(", ") : "none (add .pi/orchestra/templates/<name>.md)"}.`,
|
|
1382
|
+
);
|
|
1383
|
+
}
|
|
1384
|
+
const { run, created } = applyTemplate(template, params.name, params.goal);
|
|
1385
|
+
persist();
|
|
1386
|
+
const lines = [
|
|
1387
|
+
`Created run ${run.id} "${run.name}" from template "${template.name}" (${created.length} task(s)).`,
|
|
1388
|
+
...created.map(
|
|
1389
|
+
(task) => ` ${shortId(task.id)} ${task.status.padEnd(7)} ${task.title}${task.agent ? ` [${task.agent}]` : ""}`,
|
|
1390
|
+
),
|
|
1391
|
+
"",
|
|
1392
|
+
"Start the ready ones with action=worker_start taskId=<id>.",
|
|
1393
|
+
];
|
|
1394
|
+
return textResult(lines.join("\n"), { runId: run.id, tasks: created.map((task) => task.id) });
|
|
1395
|
+
}
|
|
1396
|
+
const run = createRun(runtime.state, {
|
|
1397
|
+
name: params.name,
|
|
1398
|
+
goal: params.goal,
|
|
1399
|
+
budgetUsd: params.budgetUsd ?? (runtime.config.budgetUsdPerRun || undefined),
|
|
1400
|
+
});
|
|
1401
|
+
persist();
|
|
1402
|
+
return textResult(
|
|
1403
|
+
`Created run ${run.id} "${run.name}"${run.budgetUsd ? ` (budget $${run.budgetUsd})` : ""}.`,
|
|
1404
|
+
{ runId: run.id },
|
|
1405
|
+
);
|
|
1406
|
+
}
|
|
1407
|
+
|
|
1408
|
+
case "run_list": {
|
|
1409
|
+
const runs = Object.values(runtime.state.runs).sort((a, b) => a.createdAt.localeCompare(b.createdAt));
|
|
1410
|
+
if (runs.length === 0) return textResult("No runs yet.");
|
|
1411
|
+
const active = runtime.state.activeRunId;
|
|
1412
|
+
const body = runs
|
|
1413
|
+
.map((run) => {
|
|
1414
|
+
const tasks = listTasks(runtime.state, run.id);
|
|
1415
|
+
const dispatches = listDispatches(runtime.state, run.id);
|
|
1416
|
+
return `${run.id === active ? "*" : " "} ${shortId(run.id)} ${run.status.padEnd(8)} ${run.name} (${
|
|
1417
|
+
tasks.length
|
|
1418
|
+
} tasks, ${dispatches.length} workers)`;
|
|
1419
|
+
})
|
|
1420
|
+
.join("\n");
|
|
1421
|
+
return textResult(body);
|
|
1422
|
+
}
|
|
1423
|
+
|
|
1424
|
+
case "run_use": {
|
|
1425
|
+
if (!params.runId || !runtime.state.runs[params.runId]) {
|
|
1426
|
+
throw new Error(`Unknown run. Use action=run_list to see runs.`);
|
|
1427
|
+
}
|
|
1428
|
+
runtime.state.activeRunId = params.runId;
|
|
1429
|
+
// Pin it: an explicitly reopened run stays current even when it is old enough
|
|
1430
|
+
// for the staleness window (see `staleRunHours`).
|
|
1431
|
+
runtime.state.ui = { ...runtime.state.ui, pinnedRunId: params.runId };
|
|
1432
|
+
persist();
|
|
1433
|
+
return textResult(`Active run is now ${params.runId}.`);
|
|
1434
|
+
}
|
|
1435
|
+
|
|
1436
|
+
case "task_create": {
|
|
1437
|
+
if (!params.title) throw new Error("task_create requires `title`.");
|
|
1438
|
+
const run = params.runId ? runtime.state.runs[params.runId] : runOf(runtime.state, { staleAfterMs: staleAfterMs() });
|
|
1439
|
+
if (!run) throw new Error(`Unknown run ${params.runId}.`);
|
|
1440
|
+
const task = createTask(runtime.state, {
|
|
1441
|
+
runId: run.id,
|
|
1442
|
+
title: params.title,
|
|
1443
|
+
description: params.description,
|
|
1444
|
+
agent: params.agent,
|
|
1445
|
+
deps: params.deps,
|
|
1446
|
+
});
|
|
1447
|
+
persist();
|
|
1448
|
+
return textResult(
|
|
1449
|
+
`Created task ${task.id} "${task.title}" (${task.status}). Start it with action=worker_start taskId=${task.id}.`,
|
|
1450
|
+
{ taskId: task.id, runId: run.id },
|
|
1451
|
+
);
|
|
1452
|
+
}
|
|
1453
|
+
|
|
1454
|
+
case "task_list": {
|
|
1455
|
+
return textResult(
|
|
1456
|
+
tasksTable(runtime.state, params.runId, {
|
|
1457
|
+
filter: params.filter,
|
|
1458
|
+
limit: params.limit,
|
|
1459
|
+
offset: params.offset,
|
|
1460
|
+
}),
|
|
1461
|
+
);
|
|
1462
|
+
}
|
|
1463
|
+
|
|
1464
|
+
case "task_update": {
|
|
1465
|
+
if (!params.taskId) throw new Error("task_update requires taskId.");
|
|
1466
|
+
const task = runtime.state.tasks[params.taskId];
|
|
1467
|
+
if (!task) throw new Error(`Unknown task ${params.taskId}.`);
|
|
1468
|
+
if (params.deps) setTaskDeps(runtime.state, task.id, params.deps);
|
|
1469
|
+
if (params.status) {
|
|
1470
|
+
const allowed = ["pending", "ready", "running", "done", "failed", "blocked"];
|
|
1471
|
+
if (!allowed.includes(params.status)) throw new Error(`status must be one of ${allowed.join(", ")}.`);
|
|
1472
|
+
task.status = params.status as Task["status"];
|
|
1473
|
+
if (task.status !== "blocked") task.error = undefined;
|
|
1474
|
+
} else if (!params.deps) {
|
|
1475
|
+
throw new Error("task_update requires status or deps.");
|
|
1476
|
+
}
|
|
1477
|
+
if (params.description) task.description = params.description;
|
|
1478
|
+
task.updatedAt = nowIso();
|
|
1479
|
+
refreshTaskReadiness(runtime.state);
|
|
1480
|
+
persist();
|
|
1481
|
+
const depsNote = params.deps ? ` deps: ${task.deps.map(shortId).join(", ") || "none"}` : "";
|
|
1482
|
+
return textResult(`Task ${task.id} is now ${task.status}.${depsNote}`);
|
|
1483
|
+
}
|
|
1484
|
+
|
|
1485
|
+
case "worker_start": {
|
|
1486
|
+
if (!params.spec && !params.taskId && !params.retryOf) {
|
|
1487
|
+
throw new Error("worker_start requires `spec` (a self-contained task), `taskId` or `retryOf`.");
|
|
1488
|
+
}
|
|
1489
|
+
const task = params.taskId ? runtime.state.tasks[params.taskId] : undefined;
|
|
1490
|
+
const spec =
|
|
1491
|
+
params.spec ??
|
|
1492
|
+
[task?.title, task?.description].filter(Boolean).join("\n\n") ??
|
|
1493
|
+
"";
|
|
1494
|
+
const { dispatch } = await startWorker({
|
|
1495
|
+
ctx,
|
|
1496
|
+
spec: spec || params.title || "",
|
|
1497
|
+
agentName: params.agent ?? task?.agent,
|
|
1498
|
+
taskId: params.taskId,
|
|
1499
|
+
model: params.model,
|
|
1500
|
+
provider: params.provider,
|
|
1501
|
+
thinking: params.thinking,
|
|
1502
|
+
tools: params.tools,
|
|
1503
|
+
budgetUsd: params.budgetUsd,
|
|
1504
|
+
budgetMs: params.budgetMs,
|
|
1505
|
+
timeoutMs: params.timeoutMs,
|
|
1506
|
+
timeoutMode: params.timeoutMode,
|
|
1507
|
+
retryOf: params.retryOf ? requireDispatch(params.retryOf) : undefined,
|
|
1508
|
+
message: params.message,
|
|
1509
|
+
retries: params.retries,
|
|
1510
|
+
});
|
|
1511
|
+
return textResult(
|
|
1512
|
+
`${dispatchGlyph(dispatch)} Started ${dispatch.agent} worker ${dispatch.id} (pid ${dispatch.pid ?? "?"}) model=${formatModel(dispatch)}.${dispatch.modelNote ? `\nNote: ${dispatch.modelNote}` : ""} End your turn or use orchestra_wait; you will be woken when it settles.`,
|
|
1513
|
+
{ dispatchId: dispatch.id, taskId: dispatch.taskId },
|
|
1514
|
+
);
|
|
1515
|
+
}
|
|
1516
|
+
|
|
1517
|
+
case "worker_list": {
|
|
1518
|
+
return textResult(
|
|
1519
|
+
workersTable(runtime.state, params.runId, {
|
|
1520
|
+
filter: params.filter,
|
|
1521
|
+
limit: params.limit,
|
|
1522
|
+
offset: params.offset,
|
|
1523
|
+
}),
|
|
1524
|
+
);
|
|
1525
|
+
}
|
|
1526
|
+
|
|
1527
|
+
case "worker_resume": {
|
|
1528
|
+
const previous = requireDispatch(params.dispatch);
|
|
1529
|
+
const live = runtime.workers.get(previous.id);
|
|
1530
|
+
if (live && !live.settled && !live.exited) {
|
|
1531
|
+
throw new Error(
|
|
1532
|
+
`${previous.id} is still running. Use orchestra_send to steer it, or worker_stop first.`,
|
|
1533
|
+
);
|
|
1534
|
+
}
|
|
1535
|
+
const { dispatch } = await startWorker({
|
|
1536
|
+
ctx,
|
|
1537
|
+
spec: previous.spec,
|
|
1538
|
+
agentName: previous.agent,
|
|
1539
|
+
taskId: previous.taskId,
|
|
1540
|
+
model: previous.model,
|
|
1541
|
+
provider: previous.provider,
|
|
1542
|
+
thinking: previous.thinking,
|
|
1543
|
+
tools: previous.tools,
|
|
1544
|
+
budgetUsd: previous.budgetUsd,
|
|
1545
|
+
budgetMs: previous.budgetMs,
|
|
1546
|
+
resumeFrom: previous,
|
|
1547
|
+
message: params.message,
|
|
1548
|
+
});
|
|
1549
|
+
return textResult(
|
|
1550
|
+
`${dispatchGlyph(dispatch)} Resumed ${previous.id} as ${dispatch.id} (session ${dispatch.sessionId ?? "?"}) model=${formatModel(dispatch)}. Use orchestra_wait; you will be woken when it settles.`,
|
|
1551
|
+
{ dispatchId: dispatch.id, resumedFrom: previous.id },
|
|
1552
|
+
);
|
|
1553
|
+
}
|
|
1554
|
+
|
|
1555
|
+
case "worker_show": {
|
|
1556
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1557
|
+
const task = dispatch.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
|
|
1558
|
+
const entries = readTranscript(logPath(dispatch.id), params.tailLines ?? 15);
|
|
1559
|
+
const body = [
|
|
1560
|
+
`dispatch ${dispatch.id} — ${dispatch.agent} — ${dispatch.status}`,
|
|
1561
|
+
`task: ${task?.title ?? "(free-form spec)"}`,
|
|
1562
|
+
`model: ${formatModel(dispatch)}${dispatch.thinking ? ` thinking=${dispatch.thinking}` : ""}${dispatch.modelNote ? `\nnote: ${dispatch.modelNote}` : ""}`,
|
|
1563
|
+
`pid: ${dispatch.pid ?? "?"} · started ${dispatch.startedAt}${dispatch.endedAt ? ` · ended ${dispatch.endedAt}` : ""}`,
|
|
1564
|
+
`usage: ${dispatch.usage.turns} turns · ${dispatch.usage.toolCalls} tools · ↑${formatTokens(
|
|
1565
|
+
dispatch.usage.input,
|
|
1566
|
+
)} ↓${formatTokens(dispatch.usage.output)} · ${formatCost(dispatch.usage.cost)}${
|
|
1567
|
+
dispatch.budgetUsd ? ` · budget $${dispatch.budgetUsd}` : ""
|
|
1568
|
+
}${dispatch.budgetMs ? ` · ${Math.round(dispatch.budgetMs / 1000)}s` : ""}`,
|
|
1569
|
+
`activity: last event ${dispatch.lastEventAt ?? "?"}${dispatch.stalledAt ? ` · ⚠ stalled since ${dispatch.stalledAt}` : ""}`,
|
|
1570
|
+
dispatch.retryAt ? `retry: queued for ${dispatch.retryAt} (attempt ${(dispatch.attempt ?? 1) + 1})` : "",
|
|
1571
|
+
dispatch.error ? `error: ${dispatch.error}` : "",
|
|
1572
|
+
"",
|
|
1573
|
+
"## Spec",
|
|
1574
|
+
dispatch.spec,
|
|
1575
|
+
"",
|
|
1576
|
+
"## Transcript (tail)",
|
|
1577
|
+
transcriptText(entries) || "(no events yet)",
|
|
1578
|
+
]
|
|
1579
|
+
.filter(Boolean)
|
|
1580
|
+
.join("\n");
|
|
1581
|
+
return textResult(body, { dispatchId: dispatch.id });
|
|
1582
|
+
}
|
|
1583
|
+
|
|
1584
|
+
case "worker_read": {
|
|
1585
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1586
|
+
const entries = readTranscript(logPath(dispatch.id), params.tailLines ?? 40);
|
|
1587
|
+
const body = [
|
|
1588
|
+
`dispatch ${dispatch.id} — ${dispatch.status} — ${formatModel(dispatch)}${dispatch.modelNote ? `\nnote: ${dispatch.modelNote}` : ""}`,
|
|
1589
|
+
transcriptText(entries) || "(no events yet)",
|
|
1590
|
+
].join("\n");
|
|
1591
|
+
return textResult(body, { dispatchId: dispatch.id });
|
|
1592
|
+
}
|
|
1593
|
+
|
|
1594
|
+
case "worker_stop": {
|
|
1595
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1596
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
1597
|
+
if (!worker && dispatch.pid && pidAlive(dispatch.pid)) {
|
|
1598
|
+
killPid(dispatch.pid, "SIGTERM");
|
|
1599
|
+
dispatch.error = `Sent SIGTERM to orphaned process ${dispatch.pid}.`;
|
|
1600
|
+
}
|
|
1601
|
+
dispatch.status = "stopped";
|
|
1602
|
+
dispatch.stopReason ??= "user";
|
|
1603
|
+
dispatch.stopNote ??= "Stopped by the coordinator.";
|
|
1604
|
+
dispatch.endedAt = nowIso();
|
|
1605
|
+
if (worker) {
|
|
1606
|
+
await worker.abort().catch(() => undefined);
|
|
1607
|
+
await worker.stop();
|
|
1608
|
+
runtime.workers.delete(dispatch.id);
|
|
1609
|
+
}
|
|
1610
|
+
if (dispatch.taskId) {
|
|
1611
|
+
const task = runtime.state.tasks[dispatch.taskId];
|
|
1612
|
+
if (task && task.status === "running") {
|
|
1613
|
+
task.status = "pending";
|
|
1614
|
+
task.dispatchId = undefined;
|
|
1615
|
+
task.updatedAt = nowIso();
|
|
1616
|
+
}
|
|
1617
|
+
}
|
|
1618
|
+
refreshTaskReadiness(runtime.state);
|
|
1619
|
+
persist();
|
|
1620
|
+
return textResult(`Stopped worker ${dispatch.id}.`);
|
|
1621
|
+
}
|
|
1622
|
+
|
|
1623
|
+
case "worker_keep_open": {
|
|
1624
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1625
|
+
dispatch.keepOpen = true;
|
|
1626
|
+
persist();
|
|
1627
|
+
return textResult(`Worker ${dispatch.id} will stay open after it settles.`);
|
|
1628
|
+
}
|
|
1629
|
+
|
|
1630
|
+
case "worker_send": {
|
|
1631
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1632
|
+
if (!params.spec && !params.description) {
|
|
1633
|
+
throw new Error("worker_send requires `spec` (the message to send).");
|
|
1634
|
+
}
|
|
1635
|
+
return sendToWorker(dispatch, params.spec ?? params.description ?? "", ctx);
|
|
1636
|
+
}
|
|
1637
|
+
|
|
1638
|
+
case "wait": {
|
|
1639
|
+
const targets = resolveWaitTargets(params.dispatch);
|
|
1640
|
+
const outcome = await waitForSettled(targets, params.timeoutMs ?? 120_000, _signal);
|
|
1641
|
+
return textResult(outcome, {});
|
|
1642
|
+
}
|
|
1643
|
+
|
|
1644
|
+
case "answer": {
|
|
1645
|
+
if (!params.questionId || params.answer === undefined) {
|
|
1646
|
+
throw new Error("answer requires questionId and answer.");
|
|
1647
|
+
}
|
|
1648
|
+
const gate = answerGate(params.questionId, params.answer);
|
|
1649
|
+
return textResult(`Answered ${gate.id} for worker ${gate.dispatchId}.`, { gateId: gate.id });
|
|
1650
|
+
}
|
|
1651
|
+
|
|
1652
|
+
case "gate_list": {
|
|
1653
|
+
const gates = Object.values(runtime.state.gates).filter((gate) => gate.status === "pending");
|
|
1654
|
+
if (gates.length === 0) return textResult("No pending questions.");
|
|
1655
|
+
return textResult(gates.map(questionReport).join("\n\n"));
|
|
1656
|
+
}
|
|
1657
|
+
|
|
1658
|
+
case "search": {
|
|
1659
|
+
const query = (params.filter ?? "").trim();
|
|
1660
|
+
if (!query) throw new Error("search requires `filter` (the text to look for in worker transcripts).");
|
|
1661
|
+
const scoped = params.runId ? [params.runId] : currentRun() ? [currentRun()?.id as string] : [];
|
|
1662
|
+
const dispatchIds =
|
|
1663
|
+
params.runId || scoped.length
|
|
1664
|
+
? Object.values(runtime.state.dispatches)
|
|
1665
|
+
.filter((dispatch) => scoped.length === 0 || scoped.includes(dispatch.runId))
|
|
1666
|
+
.map((dispatch) => dispatch.id)
|
|
1667
|
+
: undefined;
|
|
1668
|
+
const hits = searchLogs(storePaths(runtime.root).logsDir, query, {
|
|
1669
|
+
limit: params.limit ?? 30,
|
|
1670
|
+
dispatches: dispatchIds,
|
|
1671
|
+
});
|
|
1672
|
+
if (hits.length === 0) {
|
|
1673
|
+
return textResult(`No transcript matches for "${query}".`);
|
|
1674
|
+
}
|
|
1675
|
+
const byDispatch = new Map<string, typeof hits>();
|
|
1676
|
+
for (const hit of hits) {
|
|
1677
|
+
const list = byDispatch.get(hit.dispatchId) ?? [];
|
|
1678
|
+
list.push(hit);
|
|
1679
|
+
byDispatch.set(hit.dispatchId, list);
|
|
1680
|
+
}
|
|
1681
|
+
const lines = [`${hits.length} match(es) for "${query}" in ${byDispatch.size} worker(s):`];
|
|
1682
|
+
for (const [dispatchId, list] of byDispatch) {
|
|
1683
|
+
const dispatch = runtime.state.dispatches[dispatchId];
|
|
1684
|
+
const task = dispatch?.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
|
|
1685
|
+
lines.push(
|
|
1686
|
+
"",
|
|
1687
|
+
`${dispatchGlyph(dispatch ?? { status: "lost" })} ${dispatchId} — ${dispatch?.status ?? "unknown"} · ${
|
|
1688
|
+
task?.title ?? dispatch?.agent ?? "worker"
|
|
1689
|
+
}`,
|
|
1690
|
+
);
|
|
1691
|
+
for (const hit of list) lines.push(` ${hit.line}: ${hit.kind === "tool" ? "→ " : ""}${hit.text}`);
|
|
1692
|
+
}
|
|
1693
|
+
lines.push("", `Narrow it with filter="two words" or action=worker_read dispatch=<id>.`);
|
|
1694
|
+
return textResult(lines.join("\n"), { query, hits: hits.length });
|
|
1695
|
+
}
|
|
1696
|
+
|
|
1697
|
+
case "metrics": {
|
|
1698
|
+
const run = params.runId
|
|
1699
|
+
? runtime.state.runs[params.runId]
|
|
1700
|
+
: (currentRun() ?? undefined);
|
|
1701
|
+
if (!run) throw new Error("No run to measure. Pass runId or create a run first.");
|
|
1702
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
1703
|
+
return textResult(metricsTable(metrics), {
|
|
1704
|
+
runId: run.id,
|
|
1705
|
+
cost: metrics.totals.cost,
|
|
1706
|
+
turns: metrics.totals.turns,
|
|
1707
|
+
});
|
|
1708
|
+
}
|
|
1709
|
+
|
|
1710
|
+
case "diff": {
|
|
1711
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1712
|
+
const base = dispatch.baseCommit;
|
|
1713
|
+
const summary = gitDiff(ctx.cwd, base, { maxLines: params.tailLines ?? 600 });
|
|
1714
|
+
return textResult(
|
|
1715
|
+
diffReport(summary, `dispatch ${dispatch.id} (${dispatch.agent}, ${dispatch.status})`),
|
|
1716
|
+
{ dispatchId: dispatch.id, baseCommit: base, files: summary?.files ?? [] },
|
|
1717
|
+
);
|
|
1718
|
+
}
|
|
1719
|
+
|
|
1720
|
+
case "chat": {
|
|
1721
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1722
|
+
const blocks = conversationFor(dispatch);
|
|
1723
|
+
return textResult(
|
|
1724
|
+
`${dispatch.id} — ${dispatch.agent} — ${dispatch.status}\n\n${chatText(blocks, { thinking: params.includeThinking === true })}`,
|
|
1725
|
+
{ dispatchId: dispatch.id, blocks: blocks.length },
|
|
1726
|
+
);
|
|
1727
|
+
}
|
|
1728
|
+
|
|
1729
|
+
case "report": {
|
|
1730
|
+
const run = params.runId ? runtime.state.runs[params.runId] : (currentRun() ?? undefined);
|
|
1731
|
+
if (!run) throw new Error("No run to report on. Pass runId or create a run first.");
|
|
1732
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
1733
|
+
const changes: Record<string, string> = {};
|
|
1734
|
+
for (const dispatch of listDispatches(runtime.state, run.id)) {
|
|
1735
|
+
if (!dispatch.baseCommit) continue;
|
|
1736
|
+
const summary = gitDiff(ctx.cwd, dispatch.baseCommit, { maxLines: 0 });
|
|
1737
|
+
if (summary && summary.files.length > 0) changes[dispatch.id] = statText(summary);
|
|
1738
|
+
}
|
|
1739
|
+
const text = runReport(runtime.state, metrics, { changes });
|
|
1740
|
+
if (params.format === "md" || params.format === undefined) {
|
|
1741
|
+
const paths = storePaths(runtime.root);
|
|
1742
|
+
mkdirSync(paths.exportsDir, { recursive: true });
|
|
1743
|
+
const file = join(paths.exportsDir, `${run.id}.md`);
|
|
1744
|
+
writeFileSync(file, text, "utf8");
|
|
1745
|
+
return textResult(`${text}\n\n_written to ${file}_`, { path: file, runId: run.id });
|
|
1746
|
+
}
|
|
1747
|
+
return textResult(text, { runId: run.id });
|
|
1748
|
+
}
|
|
1749
|
+
|
|
1750
|
+
case "budget": {
|
|
1751
|
+
const run = params.runId ? runtime.state.runs[params.runId] : (currentRun() ?? undefined);
|
|
1752
|
+
if (!run) throw new Error("No run to budget. Pass runId or create a run first.");
|
|
1753
|
+
const usage = totalUsage(runtime.state, run.id);
|
|
1754
|
+
if (params.budgetUsd === undefined) {
|
|
1755
|
+
const ceiling = run.budgetUsd ?? runtime.config.budgetUsdPerRun;
|
|
1756
|
+
return textResult(
|
|
1757
|
+
`${run.name}: spent ${formatCost(usage.cost)}${ceiling ? ` of ${formatCost(ceiling)}` : " (no ceiling)"}${
|
|
1758
|
+
run.budgetPaused ? " · paused" : ""
|
|
1759
|
+
}${run.budgetNote ? `\n${run.budgetNote}` : ""}\nRaise it with action=budget budgetUsd=<n>.`,
|
|
1760
|
+
);
|
|
1761
|
+
}
|
|
1762
|
+
run.budgetUsd = params.budgetUsd;
|
|
1763
|
+
run.budgetPaused = false;
|
|
1764
|
+
run.budgetNote = undefined;
|
|
1765
|
+
run.updatedAt = nowIso();
|
|
1766
|
+
persist();
|
|
1767
|
+
refreshUI(ctx);
|
|
1768
|
+
return textResult(
|
|
1769
|
+
`${run.name}: ceiling is now ${formatCost(params.budgetUsd)} (spent ${formatCost(usage.cost)}).${
|
|
1770
|
+
run.budgetPaused ? "" : " New workers may start again."
|
|
1771
|
+
}`,
|
|
1772
|
+
);
|
|
1773
|
+
}
|
|
1774
|
+
|
|
1775
|
+
case "prune": {
|
|
1776
|
+
const result = pruneStore(runtime.root, runtime.state, {
|
|
1777
|
+
days: params.days,
|
|
1778
|
+
dryRun: params.dryRun,
|
|
1779
|
+
});
|
|
1780
|
+
const kb = Math.round(result.bytes / 1024);
|
|
1781
|
+
const verb = result.dryRun ? "Would remove" : "Removed";
|
|
1782
|
+
if (result.files.length === 0) {
|
|
1783
|
+
return textResult(`Nothing older than ${result.days} days to prune.`, { days: result.days });
|
|
1784
|
+
}
|
|
1785
|
+
return textResult(
|
|
1786
|
+
`${verb} ${result.files.length} item(s) (~${kb} KB) older than ${result.days} days${
|
|
1787
|
+
result.runs.length ? `, including ${result.runs.length} archived run(s)` : ""
|
|
1788
|
+
}.${result.dryRun ? " Dry run: nothing was deleted." : ""}`,
|
|
1789
|
+
{ ...result, dryRun: Boolean(params.dryRun) },
|
|
1790
|
+
);
|
|
1791
|
+
}
|
|
1792
|
+
|
|
1793
|
+
case "export": {
|
|
1794
|
+
const run = params.runId
|
|
1795
|
+
? runtime.state.runs[params.runId]
|
|
1796
|
+
: (currentRun() ?? undefined);
|
|
1797
|
+
if (!run) throw new Error("No run to export. Pass runId or create a run first.");
|
|
1798
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
1799
|
+
const format = (params.format ?? "jsonl").toLowerCase();
|
|
1800
|
+
const paths = storePaths(runtime.root);
|
|
1801
|
+
mkdirSync(paths.exportsDir, { recursive: true });
|
|
1802
|
+
const file = join(paths.exportsDir, `${run.id}.${format === "json" ? "json" : "jsonl"}`);
|
|
1803
|
+
writeFileSync(
|
|
1804
|
+
file,
|
|
1805
|
+
format === "json" ? `${JSON.stringify(metrics, null, 2)}\n` : metricsJsonl(metrics),
|
|
1806
|
+
"utf8",
|
|
1807
|
+
);
|
|
1808
|
+
return textResult(
|
|
1809
|
+
`Exported ${metrics.dispatches.length} workers and ${metrics.timeline.length} timeline points to ${file}.`,
|
|
1810
|
+
{ path: file, format, runId: run.id },
|
|
1811
|
+
);
|
|
1812
|
+
}
|
|
1813
|
+
|
|
1814
|
+
case "archive": {
|
|
1815
|
+
const result = archiveRuns(runtime.root, runtime.state, {
|
|
1816
|
+
keep: params.keep ?? 5,
|
|
1817
|
+
runIds: params.runId ? [params.runId] : undefined,
|
|
1818
|
+
});
|
|
1819
|
+
persist();
|
|
1820
|
+
if (result.archived.length === 0) {
|
|
1821
|
+
return textResult(
|
|
1822
|
+
`Nothing to archive: ${result.kept.length} run(s) live. Use keep=<n> to archive all but the newest n.`,
|
|
1823
|
+
);
|
|
1824
|
+
}
|
|
1825
|
+
const lines = [`Archived ${result.archived.length} run(s):`];
|
|
1826
|
+
for (const id of result.archived) lines.push(` ${id} → ${result.dirs[id]}`);
|
|
1827
|
+
lines.push(`${result.kept.length} run(s) left live.`);
|
|
1828
|
+
return textResult(lines.join("\n"), { archived: result.archived });
|
|
1829
|
+
}
|
|
1830
|
+
|
|
1831
|
+
case "reset": {
|
|
1832
|
+
await Promise.all(
|
|
1833
|
+
[...runtime.workers.values()].map(async (worker) => {
|
|
1834
|
+
await worker.abort().catch(() => undefined);
|
|
1835
|
+
await worker.stop().catch(() => undefined);
|
|
1836
|
+
}),
|
|
1837
|
+
);
|
|
1838
|
+
runtime.workers.clear();
|
|
1839
|
+
runtime.finalized.clear();
|
|
1840
|
+
const { archive } = archiveAndClearState(runtime.root, runtime.state);
|
|
1841
|
+
persist();
|
|
1842
|
+
runtime.watchId = undefined;
|
|
1843
|
+
refreshUI(ctx);
|
|
1844
|
+
return textResult(
|
|
1845
|
+
archive
|
|
1846
|
+
? `Reset orchestration state (archived to ${archive}).`
|
|
1847
|
+
: "Reset orchestration state (there was no state file to archive).",
|
|
1848
|
+
);
|
|
1849
|
+
}
|
|
1850
|
+
|
|
1851
|
+
default:
|
|
1852
|
+
throw new Error(`Unknown action ${params.action as string}.`);
|
|
1853
|
+
}
|
|
1854
|
+
},
|
|
1855
|
+
});
|
|
1856
|
+
|
|
1857
|
+
pi.registerTool({
|
|
1858
|
+
name: "orchestra_wait",
|
|
1859
|
+
label: "Wait for workers",
|
|
1860
|
+
description:
|
|
1861
|
+
"Block until workers settle (or a timeout fires) instead of polling. Waits for one dispatch id, or for every live worker in the run.",
|
|
1862
|
+
promptSnippet: "Block until worker agents settle instead of polling",
|
|
1863
|
+
promptGuidelines: ["Use orchestra_wait after starting workers, rather than repeatedly calling orchestra worker_list."],
|
|
1864
|
+
parameters: Type.Object({
|
|
1865
|
+
dispatch: Type.Optional(Type.String({ description: "Dispatch id, or omit to wait for all live workers." })),
|
|
1866
|
+
timeoutMs: Type.Optional(Type.Number({ description: "Maximum time to wait (default 120000)." })),
|
|
1867
|
+
}),
|
|
1868
|
+
async execute(_toolCallId, params, signal, _onUpdate, ctx) {
|
|
1869
|
+
lastCtx = ctx;
|
|
1870
|
+
ready(ctx.cwd);
|
|
1871
|
+
const targets = resolveWaitTargets(params.dispatch);
|
|
1872
|
+
if (targets.length === 0) return textResult("No live workers to wait for.");
|
|
1873
|
+
const outcome = await waitForSettled(targets, params.timeoutMs ?? 120_000, signal);
|
|
1874
|
+
return textResult(outcome);
|
|
1875
|
+
},
|
|
1876
|
+
});
|
|
1877
|
+
|
|
1878
|
+
pi.registerTool({
|
|
1879
|
+
name: "orchestra_send",
|
|
1880
|
+
label: "Message worker",
|
|
1881
|
+
description:
|
|
1882
|
+
"Send a message to a worker: steer a running worker mid-task, or give a settled worker follow-up work. The worker reports back again when it settles.",
|
|
1883
|
+
promptSnippet: "Message a worker agent (steer or follow-up)",
|
|
1884
|
+
promptGuidelines: ["Use orchestra_send to correct a running worker or to hand a settled worker follow-up work."],
|
|
1885
|
+
parameters: Type.Object({
|
|
1886
|
+
dispatch: Type.String({ description: "Dispatch id, or \"*\" to message every live worker." }),
|
|
1887
|
+
message: Type.String({ description: "What to tell the worker." }),
|
|
1888
|
+
mode: Type.Optional(StringEnum(["steer", "followUp"] as const)),
|
|
1889
|
+
}),
|
|
1890
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1891
|
+
lastCtx = ctx;
|
|
1892
|
+
ready(ctx.cwd);
|
|
1893
|
+
if (params.dispatch.trim() === "*") {
|
|
1894
|
+
const targets = liveDispatches(runtime.state, currentRun()?.id);
|
|
1895
|
+
if (targets.length === 0) return textResult("No live workers to broadcast to.");
|
|
1896
|
+
const lines: string[] = [];
|
|
1897
|
+
for (const target of targets) {
|
|
1898
|
+
try {
|
|
1899
|
+
await sendToWorker(target, params.message, ctx, params.mode);
|
|
1900
|
+
lines.push(`✓ ${shortId(target.id)} ${target.agent}`);
|
|
1901
|
+
} catch (error) {
|
|
1902
|
+
lines.push(`✗ ${shortId(target.id)} ${target.agent}: ${error instanceof Error ? error.message : String(error)}`);
|
|
1903
|
+
}
|
|
1904
|
+
}
|
|
1905
|
+
return textResult(`Broadcast to ${targets.length} worker(s):\n${lines.join("\n")}`, {
|
|
1906
|
+
dispatches: targets.map((target) => target.id),
|
|
1907
|
+
});
|
|
1908
|
+
}
|
|
1909
|
+
const dispatch = requireDispatch(params.dispatch);
|
|
1910
|
+
return sendToWorker(dispatch, params.message, ctx, params.mode);
|
|
1911
|
+
},
|
|
1912
|
+
});
|
|
1913
|
+
|
|
1914
|
+
pi.registerTool({
|
|
1915
|
+
name: "orchestra_answer",
|
|
1916
|
+
label: "Answer worker",
|
|
1917
|
+
description: "Answer a question a worker is blocked on. The worker resumes as soon as the answer is written.",
|
|
1918
|
+
promptSnippet: "Answer a blocking question from a worker agent",
|
|
1919
|
+
promptGuidelines: ["Use orchestra_answer with a questionId from orchestra action=gate_list or a question message."],
|
|
1920
|
+
parameters: Type.Object({
|
|
1921
|
+
questionId: Type.String({ description: "Question id (q_xxxxxxxx)." }),
|
|
1922
|
+
answer: Type.String({ description: "The answer, as plain text." }),
|
|
1923
|
+
}),
|
|
1924
|
+
async execute(_toolCallId, params, _signal, _onUpdate, ctx) {
|
|
1925
|
+
lastCtx = ctx;
|
|
1926
|
+
ready(ctx.cwd);
|
|
1927
|
+
const gate = answerGate(params.questionId, params.answer);
|
|
1928
|
+
return textResult(`Answered ${gate.id} for worker ${shortId(gate.dispatchId)}.`, { gateId: gate.id });
|
|
1929
|
+
},
|
|
1930
|
+
});
|
|
1931
|
+
|
|
1932
|
+
async function sendToWorker(
|
|
1933
|
+
dispatch: Dispatch,
|
|
1934
|
+
message: string,
|
|
1935
|
+
ctx: ExtensionContext,
|
|
1936
|
+
mode?: "steer" | "followUp",
|
|
1937
|
+
) {
|
|
1938
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
1939
|
+
if (!worker || worker.exited) {
|
|
1940
|
+
const options = dispatch.sessionId
|
|
1941
|
+
? `Resume it to keep its context: orchestra action=worker_resume dispatch=${dispatch.id}.`
|
|
1942
|
+
: `Set sessionMode: "session" to make settled workers resumable.`;
|
|
1943
|
+
throw new Error(
|
|
1944
|
+
`Worker ${dispatch.id} has no live process (status ${dispatch.status}). ${options} Or start a new dispatch with the previous result as context, and keepOpen=true in .pi/orchestra.json so settled workers stay reachable.`,
|
|
1945
|
+
);
|
|
1946
|
+
}
|
|
1947
|
+
dispatch.status = worker.settled ? "running" : dispatch.status;
|
|
1948
|
+
runtime.finalized.delete(dispatch.id);
|
|
1949
|
+
if (dispatch.taskId) {
|
|
1950
|
+
const task = runtime.state.tasks[dispatch.taskId];
|
|
1951
|
+
if (task && task.status === "done") {
|
|
1952
|
+
task.status = "running";
|
|
1953
|
+
task.updatedAt = nowIso();
|
|
1954
|
+
}
|
|
1955
|
+
}
|
|
1956
|
+
persist();
|
|
1957
|
+
if (mode === "followUp" || worker.settled) await worker.prompt(message);
|
|
1958
|
+
else await worker.steer(message);
|
|
1959
|
+
return textResult(
|
|
1960
|
+
`${worker.settled ? "Follow-up" : "Steering message"} delivered to ${dispatch.id} (${dispatch.agent}). You will be woken when it settles.`,
|
|
1961
|
+
{ dispatchId: dispatch.id },
|
|
1962
|
+
);
|
|
1963
|
+
}
|
|
1964
|
+
|
|
1965
|
+
function requireDispatch(id?: string): Dispatch {
|
|
1966
|
+
if (!id) throw new Error("This action needs `dispatch` (a dispatch id). Use action=worker_list.");
|
|
1967
|
+
const exact = runtime.state.dispatches[id];
|
|
1968
|
+
if (exact) return exact;
|
|
1969
|
+
const matches = Object.values(runtime.state.dispatches).filter((dispatch) => dispatch.id.endsWith(id));
|
|
1970
|
+
if (matches.length === 1) return matches[0] as Dispatch;
|
|
1971
|
+
if (matches.length > 1) throw new Error(`Ambiguous dispatch suffix "${id}". Use the full id.`);
|
|
1972
|
+
throw new Error(`Unknown dispatch "${id}". Use action=worker_list.`);
|
|
1973
|
+
}
|
|
1974
|
+
|
|
1975
|
+
/** A run by full id or unique suffix, for `/orchestra use`. */
|
|
1976
|
+
function findRun(state: OrchestraState, id: string): Run | undefined {
|
|
1977
|
+
const exact = state.runs[id];
|
|
1978
|
+
if (exact) return exact;
|
|
1979
|
+
const matches = Object.values(state.runs).filter((run) => run.id.endsWith(id));
|
|
1980
|
+
if (matches.length > 1) throw new Error(`Ambiguous run suffix "${id}". Use the full id.`);
|
|
1981
|
+
return matches[0];
|
|
1982
|
+
}
|
|
1983
|
+
|
|
1984
|
+
function resolveWaitTargets(id?: string): string[] {
|
|
1985
|
+
if (id) return [requireDispatch(id).id];
|
|
1986
|
+
return liveDispatches(runtime.state, currentRun()?.id).map((dispatch) => dispatch.id);
|
|
1987
|
+
}
|
|
1988
|
+
|
|
1989
|
+
async function waitForSettled(ids: string[], timeoutMs: number, signal?: AbortSignal): Promise<string> {
|
|
1990
|
+
const pending = ids
|
|
1991
|
+
.map((id) => runtime.workers.get(id))
|
|
1992
|
+
.filter((worker): worker is WorkerProcess => Boolean(worker));
|
|
1993
|
+
if (pending.length === 0) return "No live workers to wait for.";
|
|
1994
|
+
|
|
1995
|
+
let timer: NodeJS.Timeout | undefined;
|
|
1996
|
+
const timeout = new Promise<"timeout">((resolve) => {
|
|
1997
|
+
timer = setTimeout(() => resolve("timeout"), Math.max(1000, timeoutMs));
|
|
1998
|
+
timer.unref?.();
|
|
1999
|
+
});
|
|
2000
|
+
const abort = new Promise<"aborted">((resolve) => {
|
|
2001
|
+
if (!signal) return;
|
|
2002
|
+
if (signal.aborted) resolve("aborted");
|
|
2003
|
+
else signal.addEventListener("abort", () => resolve("aborted"), { once: true });
|
|
2004
|
+
});
|
|
2005
|
+
|
|
2006
|
+
const settled = Promise.all(pending.map((worker) => worker.whenSettled())).then(() => "settled" as const);
|
|
2007
|
+
|
|
2008
|
+
// A worker blocked on a question will never settle. Return early so the coordinator can answer.
|
|
2009
|
+
let questionTimer: NodeJS.Timeout | undefined;
|
|
2010
|
+
const question = new Promise<"question">((resolve) => {
|
|
2011
|
+
questionTimer = setInterval(() => {
|
|
2012
|
+
const blocked = Object.values(runtime.state.gates).some(
|
|
2013
|
+
(gate) => gate.status === "pending" && ids.includes(gate.dispatchId),
|
|
2014
|
+
);
|
|
2015
|
+
if (blocked) resolve("question");
|
|
2016
|
+
}, 400);
|
|
2017
|
+
questionTimer.unref?.();
|
|
2018
|
+
});
|
|
2019
|
+
|
|
2020
|
+
const outcome = await Promise.race([settled, timeout, abort, question]);
|
|
2021
|
+
if (timer) clearTimeout(timer);
|
|
2022
|
+
if (questionTimer) clearInterval(questionTimer);
|
|
2023
|
+
|
|
2024
|
+
if (outcome === "question") {
|
|
2025
|
+
const gates = Object.values(runtime.state.gates).filter(
|
|
2026
|
+
(gate) => gate.status === "pending" && ids.includes(gate.dispatchId),
|
|
2027
|
+
);
|
|
2028
|
+
return [
|
|
2029
|
+
"A worker is blocked and needs an answer before the run can continue:",
|
|
2030
|
+
"",
|
|
2031
|
+
gates.map(questionReport).join("\n\n"),
|
|
2032
|
+
"",
|
|
2033
|
+
"Answer with `orchestra_answer`, then call `orchestra_wait` again.",
|
|
2034
|
+
].join("\n");
|
|
2035
|
+
}
|
|
2036
|
+
|
|
2037
|
+
if (outcome === "timeout") {
|
|
2038
|
+
const still = ids
|
|
2039
|
+
.filter((id) => runtime.workers.get(id) && !runtime.workers.get(id)?.settled)
|
|
2040
|
+
.map((id) => shortId(id));
|
|
2041
|
+
return `Timed out after ${Math.round(timeoutMs / 1000)}s. Still running: ${still.join(", ") || "none"}. Use orchestra action=worker_read to inspect.`;
|
|
2042
|
+
}
|
|
2043
|
+
if (outcome === "aborted") return "Wait cancelled.";
|
|
2044
|
+
|
|
2045
|
+
const lines = ids.map((id) => {
|
|
2046
|
+
const dispatch = runtime.state.dispatches[id];
|
|
2047
|
+
if (!dispatch) return `${id}: unknown`;
|
|
2048
|
+
const task = dispatch.taskId ? runtime.state.tasks[dispatch.taskId] : undefined;
|
|
2049
|
+
const summary = (dispatch.summary ?? "").trim();
|
|
2050
|
+
const short = summary.length > 1200 ? `${summary.slice(0, 1200)}\n…[truncated]` : summary;
|
|
2051
|
+
return `${dispatchGlyph(dispatch)} ${dispatch.id} ${dispatch.status} — ${task?.title ?? dispatch.agent}\n${short}`;
|
|
2052
|
+
});
|
|
2053
|
+
return lines.join("\n\n");
|
|
2054
|
+
}
|
|
2055
|
+
|
|
2056
|
+
// -- interactive browser ------------------------------------------------
|
|
2057
|
+
|
|
2058
|
+
/** Text fallback for print/rpc modes, where a TUI list cannot be focused. */
|
|
2059
|
+
function browseText(scope: BrowseSession["scope"], filter: string): string {
|
|
2060
|
+
if (scope === "workers") return workersTable(runtime.state, undefined, { filter, limit: 40 });
|
|
2061
|
+
if (scope === "runs") {
|
|
2062
|
+
const rows = browseItems(runtime.state, undefined, "runs", filter);
|
|
2063
|
+
if (rows.length === 0) return "No runs yet.";
|
|
2064
|
+
return rows.map((row) => `${row.glyph} ${shortId(row.id)} ${row.status.padEnd(8)} ${row.title} · ${row.meta}`).join("\n");
|
|
2065
|
+
}
|
|
2066
|
+
return tasksTable(runtime.state, undefined, { filter, limit: 40 });
|
|
2067
|
+
}
|
|
2068
|
+
|
|
2069
|
+
function detailLines(
|
|
2070
|
+
item: { id: string; kind: string; title: string; status: string; taskId?: string; dispatchId?: string; meta: string },
|
|
2071
|
+
transcriptLimit = 60,
|
|
2072
|
+
): string[] {
|
|
2073
|
+
const lines: string[] = [];
|
|
2074
|
+
if (item.kind === "task") {
|
|
2075
|
+
const task = runtime.state.tasks[item.id];
|
|
2076
|
+
if (task) {
|
|
2077
|
+
lines.push(
|
|
2078
|
+
`status: ${item.status}`,
|
|
2079
|
+
`agent: ${task.agent ?? "(default)"}`,
|
|
2080
|
+
`created: ${task.createdAt}`,
|
|
2081
|
+
`updated: ${task.updatedAt}`,
|
|
2082
|
+
);
|
|
2083
|
+
if (task.description) lines.push("", task.description);
|
|
2084
|
+
if (task.deps.length > 0) lines.push("", `depends on: ${task.deps.join(", ")}`);
|
|
2085
|
+
if (task.error) lines.push("", `error: ${task.error}`);
|
|
2086
|
+
}
|
|
2087
|
+
}
|
|
2088
|
+
const dispatchId = item.dispatchId ?? (item.taskId ? runtime.state.tasks[item.taskId]?.dispatchId : undefined);
|
|
2089
|
+
const dispatch = dispatchId ? runtime.state.dispatches[dispatchId] : undefined;
|
|
2090
|
+
if (dispatch) {
|
|
2091
|
+
lines.push(
|
|
2092
|
+
"",
|
|
2093
|
+
`## Worker ${dispatch.id}`,
|
|
2094
|
+
`agent ${dispatch.agent} · model ${formatModel(dispatch)} · pid ${dispatch.pid ?? "?"} · ${dispatch.usage.turns} turns · ${dispatch.usage.toolCalls} tools · ${formatCost(dispatch.usage.cost)}`,
|
|
2095
|
+
`started ${dispatch.startedAt}${dispatch.endedAt ? ` · ended ${dispatch.endedAt}` : ""}`,
|
|
2096
|
+
);
|
|
2097
|
+
if (dispatch.error) lines.push(`error: ${dispatch.error}`);
|
|
2098
|
+
if (dispatch.summary) lines.push("", "## Report", dispatch.summary);
|
|
2099
|
+
if (dispatch.baseCommit) {
|
|
2100
|
+
const summary = gitDiff(runtime.cwd, dispatch.baseCommit, { maxLines: 0 });
|
|
2101
|
+
if (summary && summary.files.length > 0) {
|
|
2102
|
+
lines.push("", "## Changes (press D in the list for the diff)", summary.stat);
|
|
2103
|
+
}
|
|
2104
|
+
}
|
|
2105
|
+
const entries = readTranscript(logPath(dispatch.id), transcriptLimit);
|
|
2106
|
+
lines.push(
|
|
2107
|
+
"",
|
|
2108
|
+
`## Transcript${transcriptLimit > 200 ? " (full log)" : ""}`,
|
|
2109
|
+
transcriptText(entries) || "(no events yet)",
|
|
2110
|
+
);
|
|
2111
|
+
} else if (item.kind === "run") {
|
|
2112
|
+
const run = runtime.state.runs[item.id];
|
|
2113
|
+
if (run) {
|
|
2114
|
+
lines.push(...runSummary(runtime.state, run).split("\n"));
|
|
2115
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
2116
|
+
if (metrics.dispatches.length > 0) lines.push("", "## Cost & turns", metricsTable(metrics));
|
|
2117
|
+
}
|
|
2118
|
+
} else if (item.kind === "worker") {
|
|
2119
|
+
lines.push(`status: ${item.status}`, item.meta);
|
|
2120
|
+
}
|
|
2121
|
+
return lines;
|
|
2122
|
+
}
|
|
2123
|
+
|
|
2124
|
+
async function showDetail(
|
|
2125
|
+
ctx: ExtensionContext,
|
|
2126
|
+
item: Parameters<typeof detailLines>[0],
|
|
2127
|
+
options: { transcriptLimit?: number; lines?: () => string[]; title?: string } = {},
|
|
2128
|
+
): Promise<void> {
|
|
2129
|
+
const transcriptLimit = options.transcriptLimit ?? 60;
|
|
2130
|
+
const body = options.lines ?? (() => detailLines(item, transcriptLimit));
|
|
2131
|
+
if (ctx.mode !== "tui") {
|
|
2132
|
+
notify(ctx, body().join("\n"));
|
|
2133
|
+
return;
|
|
2134
|
+
}
|
|
2135
|
+
await ctx.ui.custom<void>((tui, theme, keybindings, done) =>
|
|
2136
|
+
createDetailComponent(
|
|
2137
|
+
tui as never,
|
|
2138
|
+
theme as never,
|
|
2139
|
+
keybindings as never,
|
|
2140
|
+
() => done(undefined),
|
|
2141
|
+
{
|
|
2142
|
+
title: options.title ?? detailTitle(item as never),
|
|
2143
|
+
lines: body,
|
|
2144
|
+
// The full-log pager opens at the tail and follows; a normal detail starts at the top.
|
|
2145
|
+
follow: transcriptLimit > 200,
|
|
2146
|
+
onMount: (repaint) => {
|
|
2147
|
+
runtime.browseRepaint = repaint;
|
|
2148
|
+
},
|
|
2149
|
+
},
|
|
2150
|
+
) as never,
|
|
2151
|
+
);
|
|
2152
|
+
runtime.browseRepaint = undefined;
|
|
2153
|
+
}
|
|
2154
|
+
|
|
2155
|
+
function dispatchFor(item: { taskId?: string; dispatchId?: string }): Dispatch | undefined {
|
|
2156
|
+
const id = item.dispatchId ?? (item.taskId ? runtime.state.tasks[item.taskId]?.dispatchId : undefined);
|
|
2157
|
+
return id ? runtime.state.dispatches[id] : undefined;
|
|
2158
|
+
}
|
|
2159
|
+
|
|
2160
|
+
/** Seed a dispatch's conversation from its log, so joining shows the history. */
|
|
2161
|
+
function conversationFor(dispatch: Dispatch): ChatBlock[] {
|
|
2162
|
+
const blocks = chatBlocks(readRecords(logPath(dispatch.id), 3000));
|
|
2163
|
+
if (blocks.length === 0) blocks.push({ kind: "note", text: "no events yet" });
|
|
2164
|
+
return blocks;
|
|
2165
|
+
}
|
|
2166
|
+
|
|
2167
|
+
/** Send typed text to a joined worker, choosing steer/prompt by its state. */
|
|
2168
|
+
async function sendToJoined(ctx: ExtensionContext, dispatch: Dispatch, text: string): Promise<string> {
|
|
2169
|
+
const joined = runtime.joined;
|
|
2170
|
+
if (joined && joined.dispatchId === dispatch.id) {
|
|
2171
|
+
joined.blocks.push({ kind: "user", text });
|
|
2172
|
+
joined.repaint?.();
|
|
2173
|
+
}
|
|
2174
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
2175
|
+
const current = runtime.state.dispatches[dispatch.id] ?? dispatch;
|
|
2176
|
+
if (!worker || worker.exited) {
|
|
2177
|
+
if (current.sessionId) {
|
|
2178
|
+
return "That worker's process is gone. Type /resume to continue it in the same session.";
|
|
2179
|
+
}
|
|
2180
|
+
return "That worker's process is gone and it kept no session. Use /retry to start a repair dispatch.";
|
|
2181
|
+
}
|
|
2182
|
+
if (current.status === "running" || current.status === "question") {
|
|
2183
|
+
await worker.steer(text);
|
|
2184
|
+
return "steered the running worker";
|
|
2185
|
+
}
|
|
2186
|
+
await worker.prompt(text);
|
|
2187
|
+
current.status = "running";
|
|
2188
|
+
persist();
|
|
2189
|
+
return "sent as a follow-up turn";
|
|
2190
|
+
}
|
|
2191
|
+
|
|
2192
|
+
/** Slash commands available in the joined composer. */
|
|
2193
|
+
async function joinCommand(
|
|
2194
|
+
ctx: ExtensionContext,
|
|
2195
|
+
dispatch: Dispatch,
|
|
2196
|
+
command: string,
|
|
2197
|
+
argument: string,
|
|
2198
|
+
exit: (target: "orchestra" | "main") => void,
|
|
2199
|
+
): Promise<string | undefined> {
|
|
2200
|
+
switch (command) {
|
|
2201
|
+
case "help":
|
|
2202
|
+
return "commands: /stop /retry /resume /diff /open /back (to the list) /exit (to your session) — ctrl+t thinking, ctrl+o tool output, ctrl+e editor";
|
|
2203
|
+
case "stop": {
|
|
2204
|
+
await stopDispatchNow(dispatch, "Stopped from the joined chat.");
|
|
2205
|
+
return "stopped the worker";
|
|
2206
|
+
}
|
|
2207
|
+
case "retry": {
|
|
2208
|
+
const { dispatch: next } = await startWorker({
|
|
2209
|
+
ctx,
|
|
2210
|
+
spec: dispatch.spec,
|
|
2211
|
+
agentName: dispatch.agent,
|
|
2212
|
+
taskId: dispatch.taskId,
|
|
2213
|
+
model: dispatch.model,
|
|
2214
|
+
provider: dispatch.provider,
|
|
2215
|
+
thinking: dispatch.thinking,
|
|
2216
|
+
tools: dispatch.tools,
|
|
2217
|
+
budgetUsd: dispatch.budgetUsd,
|
|
2218
|
+
budgetMs: dispatch.budgetMs,
|
|
2219
|
+
timeoutMs: dispatch.timeoutMs,
|
|
2220
|
+
timeoutMode: dispatch.timeoutMode,
|
|
2221
|
+
retryOf: dispatch,
|
|
2222
|
+
});
|
|
2223
|
+
exit("orchestra");
|
|
2224
|
+
return `started repair dispatch ${shortId(next.id)}`;
|
|
2225
|
+
}
|
|
2226
|
+
case "resume": {
|
|
2227
|
+
const { dispatch: next } = await startWorker({
|
|
2228
|
+
ctx,
|
|
2229
|
+
spec: dispatch.spec,
|
|
2230
|
+
agentName: dispatch.agent,
|
|
2231
|
+
taskId: dispatch.taskId,
|
|
2232
|
+
model: dispatch.model,
|
|
2233
|
+
provider: dispatch.provider,
|
|
2234
|
+
thinking: dispatch.thinking,
|
|
2235
|
+
tools: dispatch.tools,
|
|
2236
|
+
budgetUsd: dispatch.budgetUsd,
|
|
2237
|
+
budgetMs: dispatch.budgetMs,
|
|
2238
|
+
timeoutMs: dispatch.timeoutMs,
|
|
2239
|
+
timeoutMode: dispatch.timeoutMode,
|
|
2240
|
+
resumeFrom: dispatch,
|
|
2241
|
+
message: argument || undefined,
|
|
2242
|
+
});
|
|
2243
|
+
exit("orchestra");
|
|
2244
|
+
return `resumed as ${shortId(next.id)}`;
|
|
2245
|
+
}
|
|
2246
|
+
case "diff": {
|
|
2247
|
+
const summary = gitDiff(ctx.cwd, dispatch.baseCommit, { maxLines: 200 });
|
|
2248
|
+
const files = summary ? summary.files.length : 0;
|
|
2249
|
+
return summary ? `${files} changed file(s) — open the browser and press D for the patch` : "no diff available";
|
|
2250
|
+
}
|
|
2251
|
+
case "open": {
|
|
2252
|
+
exit("orchestra");
|
|
2253
|
+
return undefined;
|
|
2254
|
+
}
|
|
2255
|
+
case "back": {
|
|
2256
|
+
// /back returns to the list you came from; /exit leaves orchestra entirely.
|
|
2257
|
+
exit("orchestra");
|
|
2258
|
+
return undefined;
|
|
2259
|
+
}
|
|
2260
|
+
case "exit": {
|
|
2261
|
+
exit("main");
|
|
2262
|
+
return undefined;
|
|
2263
|
+
}
|
|
2264
|
+
default:
|
|
2265
|
+
return `unknown command /${command} — try /help`;
|
|
2266
|
+
}
|
|
2267
|
+
}
|
|
2268
|
+
|
|
2269
|
+
/**
|
|
2270
|
+
* Join a worker's chat: a full-screen conversation you can type into. Esc goes
|
|
2271
|
+
* back to the browser, ctrl+g to the main session.
|
|
2272
|
+
*/
|
|
2273
|
+
async function joinWorker(ctx: ExtensionContext, dispatch: Dispatch, options: { fromBrowser?: boolean } = {}): Promise<void> {
|
|
2274
|
+
if (ctx.mode !== "tui") {
|
|
2275
|
+
notify(ctx, chatText(conversationFor(dispatch), { thinking: true }));
|
|
2276
|
+
return;
|
|
2277
|
+
}
|
|
2278
|
+
for (;;) {
|
|
2279
|
+
const blocks = conversationFor(dispatch);
|
|
2280
|
+
const joined = { dispatchId: dispatch.id, blocks, repaint: undefined as (() => void) | undefined };
|
|
2281
|
+
runtime.joined = joined;
|
|
2282
|
+
const exit = await ctx.ui.custom<"orchestra" | "main">((tui, theme, keybindings, done) =>
|
|
2283
|
+
createJoinComponent(tui as never, theme as never, keybindings as never, done, {
|
|
2284
|
+
title: () => joinTitle(runtime.state.dispatches[dispatch.id] ?? dispatch),
|
|
2285
|
+
header: () => {
|
|
2286
|
+
const current = runtime.state.dispatches[dispatch.id];
|
|
2287
|
+
if (!current) return ["this dispatch is gone"];
|
|
2288
|
+
const task = current.taskId ? runtime.state.tasks[current.taskId] : undefined;
|
|
2289
|
+
return [
|
|
2290
|
+
`${dispatchGlyph(current)} ${current.status} · ${task?.title ?? fit(current.spec.split("\n")[0] ?? "", 60)}`,
|
|
2291
|
+
`${formatModel(current)} · ${current.usage.turns} turns · ${current.usage.toolCalls} tools · ${formatCost(current.usage.cost)}${
|
|
2292
|
+
current.budgetUsd ? ` of ${formatCost(current.budgetUsd)}` : ""
|
|
2293
|
+
}${current.retryAt ? ` · retry queued ${current.retryAt}` : ""}`,
|
|
2294
|
+
];
|
|
2295
|
+
},
|
|
2296
|
+
blocks: () => joined.blocks,
|
|
2297
|
+
send: async (text) => sendToJoined(ctx, dispatch, text),
|
|
2298
|
+
command: async (command, argument, doneExit) => joinCommand(ctx, dispatch, command, argument, doneExit),
|
|
2299
|
+
editor: async (current) => ctx.ui.editor("Message the worker", current),
|
|
2300
|
+
onMount: (repaint) => {
|
|
2301
|
+
joined.repaint = repaint;
|
|
2302
|
+
},
|
|
2303
|
+
}) as never,
|
|
2304
|
+
);
|
|
2305
|
+
runtime.joined = undefined;
|
|
2306
|
+
if (exit === "orchestra" && (options.fromBrowser ?? false)) return;
|
|
2307
|
+
if (exit === "orchestra") {
|
|
2308
|
+
await openBrowser(ctx);
|
|
2309
|
+
return;
|
|
2310
|
+
}
|
|
2311
|
+
return;
|
|
2312
|
+
}
|
|
2313
|
+
}
|
|
2314
|
+
|
|
2315
|
+
async function openBrowser(ctx: ExtensionContext, initial: Partial<BrowseSession> = {}): Promise<void> {
|
|
2316
|
+
const session: BrowseSession = {
|
|
2317
|
+
scope: initial.scope ?? "tasks",
|
|
2318
|
+
filter: initial.filter ?? "",
|
|
2319
|
+
selectedId: initial.selectedId,
|
|
2320
|
+
};
|
|
2321
|
+
if (ctx.mode !== "tui") {
|
|
2322
|
+
notify(ctx, browseText(session.scope, session.filter));
|
|
2323
|
+
return;
|
|
2324
|
+
}
|
|
2325
|
+
for (;;) {
|
|
2326
|
+
const result = await ctx.ui.custom<BrowseResult>((tui, theme, keybindings, done) =>
|
|
2327
|
+
createBrowseComponent(
|
|
2328
|
+
tui as never,
|
|
2329
|
+
theme as never,
|
|
2330
|
+
keybindings as never,
|
|
2331
|
+
done,
|
|
2332
|
+
{
|
|
2333
|
+
items: (scope, filter, sort) =>
|
|
2334
|
+
browseItems(runtime.state, currentRun(), scope, filter, sort),
|
|
2335
|
+
title: () => {
|
|
2336
|
+
const run = currentRun();
|
|
2337
|
+
return run ? `orchestra — ${run.name} (${shortId(run.id)})` : "orchestra — no run";
|
|
2338
|
+
},
|
|
2339
|
+
initial: session,
|
|
2340
|
+
onMount: (repaint) => {
|
|
2341
|
+
runtime.browseRepaint = repaint;
|
|
2342
|
+
},
|
|
2343
|
+
},
|
|
2344
|
+
) as never,
|
|
2345
|
+
);
|
|
2346
|
+
runtime.browseRepaint = undefined;
|
|
2347
|
+
if (!result || result.kind === "close") return;
|
|
2348
|
+
|
|
2349
|
+
if (result.kind === "open") {
|
|
2350
|
+
session.selectedId = result.item.id;
|
|
2351
|
+
await showDetail(ctx, result.item);
|
|
2352
|
+
continue;
|
|
2353
|
+
}
|
|
2354
|
+
if (result.kind === "log") {
|
|
2355
|
+
session.selectedId = result.item.id;
|
|
2356
|
+
await showDetail(ctx, result.item, { transcriptLimit: 5000 });
|
|
2357
|
+
continue;
|
|
2358
|
+
}
|
|
2359
|
+
if (result.kind === "diff") {
|
|
2360
|
+
session.selectedId = result.item.id;
|
|
2361
|
+
const dispatch = dispatchFor(result.item);
|
|
2362
|
+
if (!dispatch) {
|
|
2363
|
+
notify(ctx, "That item has no worker yet, so there are no changes to show.", "warning");
|
|
2364
|
+
continue;
|
|
2365
|
+
}
|
|
2366
|
+
const summary = gitDiff(ctx.cwd, dispatch.baseCommit, { maxLines: 2000 });
|
|
2367
|
+
await showDetail(ctx, result.item, {
|
|
2368
|
+
title: `diff — ${shortId(dispatch.id)} ${dispatch.agent}`,
|
|
2369
|
+
lines: () => diffReport(summary, `dispatch ${dispatch.id} (${dispatch.agent})`).split("\n"),
|
|
2370
|
+
});
|
|
2371
|
+
continue;
|
|
2372
|
+
}
|
|
2373
|
+
|
|
2374
|
+
if (result.kind === "join") {
|
|
2375
|
+
session.selectedId = result.item.id;
|
|
2376
|
+
const joinTarget = dispatchFor(result.item);
|
|
2377
|
+
if (!joinTarget) {
|
|
2378
|
+
notify(ctx, "That item has no worker to join yet.", "warning");
|
|
2379
|
+
continue;
|
|
2380
|
+
}
|
|
2381
|
+
runtime.browseRepaint = undefined;
|
|
2382
|
+
await joinWorker(ctx, joinTarget, { fromBrowser: true });
|
|
2383
|
+
continue;
|
|
2384
|
+
}
|
|
2385
|
+
if (result.kind === "copy") {
|
|
2386
|
+
const ids = result.items.map((entry) => entry.dispatchId ?? entry.id);
|
|
2387
|
+
ctx.ui.setEditorText(ids.join(" "));
|
|
2388
|
+
notify(ctx, `Put ${ids.length} id(s) in the editor: ${ids.map(shortId).join(", ")}`, "info");
|
|
2389
|
+
continue;
|
|
2390
|
+
}
|
|
2391
|
+
if (result.kind === "retry") {
|
|
2392
|
+
const lines: string[] = [];
|
|
2393
|
+
for (const entry of result.items) {
|
|
2394
|
+
const previous = dispatchFor(entry);
|
|
2395
|
+
if (!previous) {
|
|
2396
|
+
lines.push(`✗ ${entry.title}: no worker to retry`);
|
|
2397
|
+
continue;
|
|
2398
|
+
}
|
|
2399
|
+
try {
|
|
2400
|
+
const { dispatch } = await startWorker({
|
|
2401
|
+
ctx,
|
|
2402
|
+
spec: previous.spec,
|
|
2403
|
+
agentName: previous.agent,
|
|
2404
|
+
taskId: previous.taskId,
|
|
2405
|
+
model: previous.model,
|
|
2406
|
+
provider: previous.provider,
|
|
2407
|
+
thinking: previous.thinking,
|
|
2408
|
+
tools: previous.tools,
|
|
2409
|
+
budgetUsd: previous.budgetUsd,
|
|
2410
|
+
budgetMs: previous.budgetMs,
|
|
2411
|
+
retryOf: previous,
|
|
2412
|
+
});
|
|
2413
|
+
lines.push(`✓ ${shortId(previous.id)} → ${shortId(dispatch.id)}`);
|
|
2414
|
+
} catch (error) {
|
|
2415
|
+
lines.push(`✗ ${shortId(previous.id)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2416
|
+
}
|
|
2417
|
+
}
|
|
2418
|
+
notify(ctx, `Retry:\n${lines.join("\n")}`);
|
|
2419
|
+
continue;
|
|
2420
|
+
}
|
|
2421
|
+
if (result.kind === "stopMany") {
|
|
2422
|
+
const targets = result.items
|
|
2423
|
+
.map((entry) => dispatchFor(entry))
|
|
2424
|
+
.filter((entry): entry is Dispatch => Boolean(entry));
|
|
2425
|
+
if (targets.length === 0) {
|
|
2426
|
+
notify(ctx, "Nothing running in the selection.", "warning");
|
|
2427
|
+
continue;
|
|
2428
|
+
}
|
|
2429
|
+
const ok = await ctx.ui.confirm(
|
|
2430
|
+
"Stop workers",
|
|
2431
|
+
`Stop ${targets.length} worker(s): ${targets.map((entry) => shortId(entry.id)).join(", ")}?`,
|
|
2432
|
+
);
|
|
2433
|
+
if (!ok) continue;
|
|
2434
|
+
for (const target of targets) await stopDispatchNow(target);
|
|
2435
|
+
notify(ctx, `Stopped ${targets.length} worker(s).`, "info");
|
|
2436
|
+
continue;
|
|
2437
|
+
}
|
|
2438
|
+
|
|
2439
|
+
session.selectedId = result.item.id;
|
|
2440
|
+
if (result.kind === "useRun") {
|
|
2441
|
+
runtime.state.activeRunId = result.item.runId;
|
|
2442
|
+
runtime.state.ui = { ...runtime.state.ui, pinnedRunId: result.item.runId };
|
|
2443
|
+
persist();
|
|
2444
|
+
refreshUI(ctx);
|
|
2445
|
+
notify(ctx, `Active run is now ${result.item.title}.`, "info");
|
|
2446
|
+
continue;
|
|
2447
|
+
}
|
|
2448
|
+
const dispatch = dispatchFor(result.item);
|
|
2449
|
+
if (!dispatch) {
|
|
2450
|
+
notify(ctx, "That item has no worker yet. Start one with worker_start.", "warning");
|
|
2451
|
+
continue;
|
|
2452
|
+
}
|
|
2453
|
+
if (result.kind === "follow") {
|
|
2454
|
+
runtime.watchId = dispatch.id;
|
|
2455
|
+
runtime.uiDirty = true;
|
|
2456
|
+
refreshUI(ctx);
|
|
2457
|
+
notify(ctx, `Watching ${shortId(dispatch.id)}. /orchestra unwatch to stop.`, "info");
|
|
2458
|
+
continue;
|
|
2459
|
+
}
|
|
2460
|
+
if (result.kind === "message") {
|
|
2461
|
+
const message = await ctx.ui.editor(`Message ${shortId(dispatch.id)}`, "");
|
|
2462
|
+
if (!message?.trim()) continue;
|
|
2463
|
+
try {
|
|
2464
|
+
const sent = await sendToWorker(dispatch, message.trim(), ctx);
|
|
2465
|
+
notify(ctx, sent.content[0]?.text ?? "Sent.");
|
|
2466
|
+
} catch (error) {
|
|
2467
|
+
notify(ctx, error instanceof Error ? error.message : String(error), "error");
|
|
2468
|
+
}
|
|
2469
|
+
continue;
|
|
2470
|
+
}
|
|
2471
|
+
if (result.kind === "stop") {
|
|
2472
|
+
const ok = await ctx.ui.confirm("Stop worker", `Stop ${shortId(dispatch.id)} (${dispatch.agent})?`);
|
|
2473
|
+
if (!ok) continue;
|
|
2474
|
+
await stopDispatchNow(dispatch);
|
|
2475
|
+
notify(ctx, `Stopped ${shortId(dispatch.id)}.`, "info");
|
|
2476
|
+
continue;
|
|
2477
|
+
}
|
|
2478
|
+
}
|
|
2479
|
+
}
|
|
2480
|
+
|
|
2481
|
+
// -- command ------------------------------------------------------------
|
|
2482
|
+
|
|
2483
|
+
pi.registerCommand("orchestra", {
|
|
2484
|
+
description: "Show or manage pi-orchestra runs, tasks and workers",
|
|
2485
|
+
getArgumentCompletions: (prefix) =>
|
|
2486
|
+
completeOrchestraArgument(prefix, {
|
|
2487
|
+
state: runtime.ready ? runtime.state : undefined,
|
|
2488
|
+
templates: listTemplates(lastCtx?.cwd ?? runtime.cwd).map((template) => ({
|
|
2489
|
+
name: template.name,
|
|
2490
|
+
tasks: template.tasks.length,
|
|
2491
|
+
})),
|
|
2492
|
+
}),
|
|
2493
|
+
handler: async (args, ctx) => {
|
|
2494
|
+
lastCtx = ctx;
|
|
2495
|
+
ready(ctx.cwd);
|
|
2496
|
+
const [sub, ...rest] = args.trim().split(/\s+/).filter(Boolean);
|
|
2497
|
+
const arg = rest.join(" ");
|
|
2498
|
+
|
|
2499
|
+
if (!sub && ctx.mode === "tui") {
|
|
2500
|
+
await openBrowser(ctx);
|
|
2501
|
+
return;
|
|
2502
|
+
}
|
|
2503
|
+
|
|
2504
|
+
switch (sub) {
|
|
2505
|
+
case undefined:
|
|
2506
|
+
case "status": {
|
|
2507
|
+
const run = currentRun();
|
|
2508
|
+
const body = run
|
|
2509
|
+
? [
|
|
2510
|
+
runSummary(runtime.state, run),
|
|
2511
|
+
"",
|
|
2512
|
+
tasksTable(runtime.state, run.id),
|
|
2513
|
+
"",
|
|
2514
|
+
workersTable(runtime.state, run.id),
|
|
2515
|
+
].join("\n")
|
|
2516
|
+
: "No run yet. Ask the model to start one, or use /orchestra workers after a dispatch.";
|
|
2517
|
+
notify(ctx, body);
|
|
2518
|
+
const earlier = Object.values(runtime.state.runs).length;
|
|
2519
|
+
if (!run && earlier > 0) {
|
|
2520
|
+
notify(
|
|
2521
|
+
ctx,
|
|
2522
|
+
`${earlier} earlier run(s) are kept from previous sessions but are not current (/orchestra runs, then /orchestra use <id>).`,
|
|
2523
|
+
"info",
|
|
2524
|
+
);
|
|
2525
|
+
}
|
|
2526
|
+
return;
|
|
2527
|
+
}
|
|
2528
|
+
case "browse":
|
|
2529
|
+
await openBrowser(ctx, { filter: arg.trim() || undefined });
|
|
2530
|
+
return;
|
|
2531
|
+
case "find":
|
|
2532
|
+
notify(ctx, browseText("tasks", arg.trim()));
|
|
2533
|
+
return;
|
|
2534
|
+
case "open": {
|
|
2535
|
+
const needle = arg.trim();
|
|
2536
|
+
const run = currentRun();
|
|
2537
|
+
const candidates = [
|
|
2538
|
+
...browseItems(runtime.state, run, "tasks"),
|
|
2539
|
+
...browseItems(runtime.state, run, "workers"),
|
|
2540
|
+
...browseItems(runtime.state, run, "runs"),
|
|
2541
|
+
];
|
|
2542
|
+
const item =
|
|
2543
|
+
candidates.find((candidate) => candidate.id === needle) ??
|
|
2544
|
+
candidates.find((candidate) => candidate.id.endsWith(needle));
|
|
2545
|
+
if (!item) {
|
|
2546
|
+
notify(ctx, `No task, worker or run matching "${needle}". /orchestra browse to look around.`, "error");
|
|
2547
|
+
return;
|
|
2548
|
+
}
|
|
2549
|
+
await showDetail(ctx, item);
|
|
2550
|
+
return;
|
|
2551
|
+
}
|
|
2552
|
+
case "tasks":
|
|
2553
|
+
notify(ctx, tasksTable(runtime.state, undefined, { limit: 40 }));
|
|
2554
|
+
return;
|
|
2555
|
+
case "workers":
|
|
2556
|
+
notify(ctx, workersTable(runtime.state, undefined, { limit: 40 }));
|
|
2557
|
+
return;
|
|
2558
|
+
case "read": {
|
|
2559
|
+
const dispatch = requireDispatch(arg.trim());
|
|
2560
|
+
const entries = readTranscript(logPath(dispatch.id), 40);
|
|
2561
|
+
notify(ctx, `${dispatch.id} — ${dispatch.status}\n${transcriptText(entries) || "(no events yet)"}`);
|
|
2562
|
+
return;
|
|
2563
|
+
}
|
|
2564
|
+
case "watch": {
|
|
2565
|
+
const dispatch = requireDispatch(arg.trim());
|
|
2566
|
+
runtime.watchId = dispatch.id;
|
|
2567
|
+
runtime.uiDirty = true;
|
|
2568
|
+
refreshUI(ctx);
|
|
2569
|
+
notify(ctx, `Watching ${dispatch.id}. Use /orchestra unwatch to stop.`, "info");
|
|
2570
|
+
return;
|
|
2571
|
+
}
|
|
2572
|
+
case "unwatch":
|
|
2573
|
+
runtime.watchId = undefined;
|
|
2574
|
+
runtime.uiDirty = true;
|
|
2575
|
+
refreshUI(ctx);
|
|
2576
|
+
notify(ctx, "Stopped watching.", "info");
|
|
2577
|
+
return;
|
|
2578
|
+
case "hide":
|
|
2579
|
+
case "show": {
|
|
2580
|
+
const requested = arg.trim().toLowerCase();
|
|
2581
|
+
if (sub === "hide") {
|
|
2582
|
+
runtime.state.ui = { ...runtime.state.ui, widget: "off" };
|
|
2583
|
+
persist();
|
|
2584
|
+
refreshUI(ctx);
|
|
2585
|
+
notify(
|
|
2586
|
+
ctx,
|
|
2587
|
+
"Orchestra UI hidden for this project. `/orchestra show` brings the widget back; `/orchestra status` always works.",
|
|
2588
|
+
"info",
|
|
2589
|
+
);
|
|
2590
|
+
return;
|
|
2591
|
+
}
|
|
2592
|
+
if (requested && requested !== "auto" && requested !== "always" && requested !== "off") {
|
|
2593
|
+
notify(ctx, "Usage: /orchestra show [auto|always|off]", "error");
|
|
2594
|
+
return;
|
|
2595
|
+
}
|
|
2596
|
+
const mode = (requested || "auto") as "auto" | "always" | "off";
|
|
2597
|
+
runtime.state.ui = { ...runtime.state.ui, widget: mode };
|
|
2598
|
+
persist();
|
|
2599
|
+
refreshUI(ctx);
|
|
2600
|
+
notify(
|
|
2601
|
+
ctx,
|
|
2602
|
+
mode === "off"
|
|
2603
|
+
? "Orchestra UI off for this project."
|
|
2604
|
+
: mode === "always"
|
|
2605
|
+
? "Widget pinned on for this project, even when nothing is running."
|
|
2606
|
+
: "Widget back to auto: it appears while workers are live and clears when they settle.",
|
|
2607
|
+
"info",
|
|
2608
|
+
);
|
|
2609
|
+
return;
|
|
2610
|
+
}
|
|
2611
|
+
case "reset":
|
|
2612
|
+
case "clean": {
|
|
2613
|
+
const live = [...runtime.workers.keys()];
|
|
2614
|
+
if (ctx.mode === "tui" || ctx.mode === "rpc") {
|
|
2615
|
+
const counts = `${Object.keys(runtime.state.runs).length} run(s), ${Object.keys(runtime.state.tasks).length} task(s), ${live.length} live worker(s)`;
|
|
2616
|
+
const ok = await ctx.ui.confirm(
|
|
2617
|
+
"Reset orchestra state",
|
|
2618
|
+
`Archive this project's state (${counts}) and start clean? Logs stay on disk.`,
|
|
2619
|
+
);
|
|
2620
|
+
if (!ok) return;
|
|
2621
|
+
}
|
|
2622
|
+
await Promise.all(
|
|
2623
|
+
[...runtime.workers.values()].map(async (worker) => {
|
|
2624
|
+
await worker.abort().catch(() => undefined);
|
|
2625
|
+
await worker.stop().catch(() => undefined);
|
|
2626
|
+
}),
|
|
2627
|
+
);
|
|
2628
|
+
runtime.workers.clear();
|
|
2629
|
+
runtime.finalized.clear();
|
|
2630
|
+
runtime.watchId = undefined;
|
|
2631
|
+
const { archive } = archiveAndClearState(runtime.root, runtime.state);
|
|
2632
|
+
persist();
|
|
2633
|
+
refreshUI(ctx);
|
|
2634
|
+
notify(
|
|
2635
|
+
ctx,
|
|
2636
|
+
archive
|
|
2637
|
+
? `Reset. Previous state archived to ${archive}.`
|
|
2638
|
+
: "Reset. There was no state file to archive.",
|
|
2639
|
+
"info",
|
|
2640
|
+
);
|
|
2641
|
+
return;
|
|
2642
|
+
}
|
|
2643
|
+
case "stop": {
|
|
2644
|
+
const dispatch = requireDispatch(arg.trim());
|
|
2645
|
+
const worker = runtime.workers.get(dispatch.id);
|
|
2646
|
+
if (worker) {
|
|
2647
|
+
await worker.abort().catch(() => undefined);
|
|
2648
|
+
await worker.stop();
|
|
2649
|
+
runtime.workers.delete(dispatch.id);
|
|
2650
|
+
}
|
|
2651
|
+
dispatch.status = "stopped";
|
|
2652
|
+
dispatch.endedAt = nowIso();
|
|
2653
|
+
persist();
|
|
2654
|
+
notify(ctx, `Stopped ${dispatch.id}.`, "info");
|
|
2655
|
+
return;
|
|
2656
|
+
}
|
|
2657
|
+
case "retry": {
|
|
2658
|
+
const [id, ...words] = arg.trim().split(/\s+/);
|
|
2659
|
+
if (!id) {
|
|
2660
|
+
notify(ctx, "Usage: /orchestra retry <dispatch id> [note]", "error");
|
|
2661
|
+
return;
|
|
2662
|
+
}
|
|
2663
|
+
const previous = requireDispatch(id);
|
|
2664
|
+
try {
|
|
2665
|
+
const { dispatch } = await startWorker({
|
|
2666
|
+
ctx,
|
|
2667
|
+
spec: previous.spec,
|
|
2668
|
+
agentName: previous.agent,
|
|
2669
|
+
taskId: previous.taskId,
|
|
2670
|
+
model: previous.model,
|
|
2671
|
+
provider: previous.provider,
|
|
2672
|
+
thinking: previous.thinking,
|
|
2673
|
+
tools: previous.tools,
|
|
2674
|
+
budgetUsd: previous.budgetUsd,
|
|
2675
|
+
budgetMs: previous.budgetMs,
|
|
2676
|
+
retryOf: previous,
|
|
2677
|
+
message: words.join(" ") || undefined,
|
|
2678
|
+
});
|
|
2679
|
+
notify(ctx, `Retrying ${previous.id} as ${dispatch.id}.`, "info");
|
|
2680
|
+
} catch (error) {
|
|
2681
|
+
notify(ctx, error instanceof Error ? error.message : String(error), "error");
|
|
2682
|
+
}
|
|
2683
|
+
return;
|
|
2684
|
+
}
|
|
2685
|
+
case "resume": {
|
|
2686
|
+
const [id, ...words] = arg.trim().split(/\s+/);
|
|
2687
|
+
if (!id) {
|
|
2688
|
+
notify(ctx, "Usage: /orchestra resume <dispatch id> [message]", "error");
|
|
2689
|
+
return;
|
|
2690
|
+
}
|
|
2691
|
+
const previous = requireDispatch(id);
|
|
2692
|
+
try {
|
|
2693
|
+
const { dispatch } = await startWorker({
|
|
2694
|
+
ctx,
|
|
2695
|
+
spec: previous.spec,
|
|
2696
|
+
agentName: previous.agent,
|
|
2697
|
+
taskId: previous.taskId,
|
|
2698
|
+
model: previous.model,
|
|
2699
|
+
provider: previous.provider,
|
|
2700
|
+
thinking: previous.thinking,
|
|
2701
|
+
tools: previous.tools,
|
|
2702
|
+
budgetUsd: previous.budgetUsd,
|
|
2703
|
+
budgetMs: previous.budgetMs,
|
|
2704
|
+
resumeFrom: previous,
|
|
2705
|
+
message: words.join(" ") || undefined,
|
|
2706
|
+
});
|
|
2707
|
+
notify(ctx, `Resumed ${previous.id} as ${dispatch.id} (${formatModel(dispatch)}).`, "info");
|
|
2708
|
+
} catch (error) {
|
|
2709
|
+
notify(ctx, error instanceof Error ? error.message : String(error), "error");
|
|
2710
|
+
}
|
|
2711
|
+
return;
|
|
2712
|
+
}
|
|
2713
|
+
case "runs": {
|
|
2714
|
+
const runs = Object.values(runtime.state.runs).sort((a, b) => b.createdAt.localeCompare(a.createdAt));
|
|
2715
|
+
notify(
|
|
2716
|
+
ctx,
|
|
2717
|
+
runs.length === 0
|
|
2718
|
+
? "No runs yet. Ask the model to start one, or create a task."
|
|
2719
|
+
: runs
|
|
2720
|
+
.map((run) => {
|
|
2721
|
+
const marker = run.id === runtime.state.activeRunId ? "→" : " ";
|
|
2722
|
+
const counts = Object.values(runtime.state.tasks).filter((task) => task.runId === run.id).length;
|
|
2723
|
+
return `${marker} ${shortId(run.id)} ${run.status.padEnd(9)} ${run.name ?? run.goal ?? ""} · ${counts} task(s)${run.budgetPaused ? " · ⏸ budget paused" : ""}`;
|
|
2724
|
+
})
|
|
2725
|
+
.join("\n"),
|
|
2726
|
+
);
|
|
2727
|
+
return;
|
|
2728
|
+
}
|
|
2729
|
+
case "use": {
|
|
2730
|
+
const runId = arg.trim();
|
|
2731
|
+
const run = runId ? findRun(runtime.state, runId) : undefined;
|
|
2732
|
+
if (!run) {
|
|
2733
|
+
notify(ctx, runId ? `Unknown run ${runId} — /orchestra runs lists them.` : "Usage: /orchestra use <run id>", "error");
|
|
2734
|
+
return;
|
|
2735
|
+
}
|
|
2736
|
+
runtime.state.activeRunId = run.id;
|
|
2737
|
+
runtime.state.ui = { ...runtime.state.ui, pinnedRunId: run.id };
|
|
2738
|
+
persist();
|
|
2739
|
+
refreshUI(ctx);
|
|
2740
|
+
notify(ctx, `Active run is now ${run.id}${run.name ? ` — ${run.name}` : ""}.`);
|
|
2741
|
+
return;
|
|
2742
|
+
}
|
|
2743
|
+
case "templates": {
|
|
2744
|
+
const templates = listTemplates(ctx.cwd);
|
|
2745
|
+
notify(
|
|
2746
|
+
ctx,
|
|
2747
|
+
templates.length === 0
|
|
2748
|
+
? "No templates. Add .pi/orchestra/templates/<name>.md (or ~/.pi/agent/orchestra/templates/)."
|
|
2749
|
+
: templates.map((template) => `${template.name} — ${template.tasks.length} task(s) · ${template.path}`).join("\n"),
|
|
2750
|
+
);
|
|
2751
|
+
return;
|
|
2752
|
+
}
|
|
2753
|
+
case "template": {
|
|
2754
|
+
const name = arg.trim();
|
|
2755
|
+
if (!name) {
|
|
2756
|
+
const templates = listTemplates(ctx.cwd);
|
|
2757
|
+
notify(
|
|
2758
|
+
ctx,
|
|
2759
|
+
templates.length === 0
|
|
2760
|
+
? "No templates. Add .pi/orchestra/templates/<name>.md."
|
|
2761
|
+
: `Usage: /orchestra template <name>\n${templates.map((template) => ` ${template.name} (${template.tasks.length} tasks)`).join("\n")}`,
|
|
2762
|
+
);
|
|
2763
|
+
return;
|
|
2764
|
+
}
|
|
2765
|
+
const template = findTemplate(ctx.cwd, name);
|
|
2766
|
+
if (!template) {
|
|
2767
|
+
notify(ctx, `Unknown template "${name}". /orchestra templates to list them.`, "error");
|
|
2768
|
+
return;
|
|
2769
|
+
}
|
|
2770
|
+
const { run, created } = applyTemplate(template);
|
|
2771
|
+
persist();
|
|
2772
|
+
notify(
|
|
2773
|
+
ctx,
|
|
2774
|
+
`Created run "${run.name}" with ${created.length} task(s): ${created.map((task) => task.title).join(" · ")}`,
|
|
2775
|
+
);
|
|
2776
|
+
refreshUI(ctx);
|
|
2777
|
+
return;
|
|
2778
|
+
}
|
|
2779
|
+
case "export": {
|
|
2780
|
+
const run = currentRun();
|
|
2781
|
+
if (!run) {
|
|
2782
|
+
notify(ctx, "No active run to export.", "warning");
|
|
2783
|
+
return;
|
|
2784
|
+
}
|
|
2785
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
2786
|
+
const format = (rest[0] ?? "jsonl").toLowerCase() === "json" ? "json" : "jsonl";
|
|
2787
|
+
const paths = storePaths(runtime.root);
|
|
2788
|
+
mkdirSync(paths.exportsDir, { recursive: true });
|
|
2789
|
+
const file = join(paths.exportsDir, `${run.id}.${format}`);
|
|
2790
|
+
writeFileSync(
|
|
2791
|
+
file,
|
|
2792
|
+
format === "json" ? `${JSON.stringify(metrics, null, 2)}\n` : metricsJsonl(metrics),
|
|
2793
|
+
"utf8",
|
|
2794
|
+
);
|
|
2795
|
+
notify(ctx, `Exported ${run.name} to ${file}`);
|
|
2796
|
+
return;
|
|
2797
|
+
}
|
|
2798
|
+
case "metrics": {
|
|
2799
|
+
const run = currentRun();
|
|
2800
|
+
if (!run) {
|
|
2801
|
+
notify(ctx, "No active run to measure.", "warning");
|
|
2802
|
+
return;
|
|
2803
|
+
}
|
|
2804
|
+
notify(ctx, metricsTable(runMetrics(runtime.state, run.id)));
|
|
2805
|
+
return;
|
|
2806
|
+
}
|
|
2807
|
+
case "broadcast": {
|
|
2808
|
+
const message = arg.trim();
|
|
2809
|
+
if (!message) {
|
|
2810
|
+
notify(ctx, "Usage: /orchestra broadcast <message>", "error");
|
|
2811
|
+
return;
|
|
2812
|
+
}
|
|
2813
|
+
const targets = liveDispatches(runtime.state, currentRun()?.id);
|
|
2814
|
+
if (targets.length === 0) {
|
|
2815
|
+
notify(ctx, "No live workers to broadcast to.", "warning");
|
|
2816
|
+
return;
|
|
2817
|
+
}
|
|
2818
|
+
const lines: string[] = [];
|
|
2819
|
+
for (const target of targets) {
|
|
2820
|
+
try {
|
|
2821
|
+
await sendToWorker(target, message, ctx);
|
|
2822
|
+
lines.push(`✓ ${shortId(target.id)} ${target.agent}`);
|
|
2823
|
+
} catch (error) {
|
|
2824
|
+
lines.push(`✗ ${shortId(target.id)}: ${error instanceof Error ? error.message : String(error)}`);
|
|
2825
|
+
}
|
|
2826
|
+
}
|
|
2827
|
+
notify(ctx, `Broadcast to ${targets.length} worker(s):\n${lines.join("\n")}`);
|
|
2828
|
+
return;
|
|
2829
|
+
}
|
|
2830
|
+
case "join": {
|
|
2831
|
+
const target = arg.trim();
|
|
2832
|
+
if (!target) {
|
|
2833
|
+
notify(ctx, "Usage: /orchestra join <dispatch id>", "error");
|
|
2834
|
+
return;
|
|
2835
|
+
}
|
|
2836
|
+
const dispatch = requireDispatch(target);
|
|
2837
|
+
await joinWorker(ctx, dispatch);
|
|
2838
|
+
return;
|
|
2839
|
+
}
|
|
2840
|
+
case "back": {
|
|
2841
|
+
// Symmetry for people who type it instead of pressing esc in a joined chat.
|
|
2842
|
+
notify(ctx, "Back in the coordinator session.");
|
|
2843
|
+
return;
|
|
2844
|
+
}
|
|
2845
|
+
case "chat": {
|
|
2846
|
+
const target = arg.trim();
|
|
2847
|
+
if (!target) {
|
|
2848
|
+
notify(ctx, "Usage: /orchestra chat <dispatch id>", "error");
|
|
2849
|
+
return;
|
|
2850
|
+
}
|
|
2851
|
+
const dispatch = requireDispatch(target);
|
|
2852
|
+
notify(ctx, chatText(conversationFor(dispatch), { thinking: true }));
|
|
2853
|
+
return;
|
|
2854
|
+
}
|
|
2855
|
+
case "grep": {
|
|
2856
|
+
const query = arg.trim();
|
|
2857
|
+
if (!query) {
|
|
2858
|
+
notify(ctx, "Usage: /orchestra grep <text>", "error");
|
|
2859
|
+
return;
|
|
2860
|
+
}
|
|
2861
|
+
const hits = searchLogs(storePaths(runtime.root).logsDir, query, { limit: 30 });
|
|
2862
|
+
notify(
|
|
2863
|
+
ctx,
|
|
2864
|
+
hits.length === 0
|
|
2865
|
+
? `No transcript matches for "${query}".`
|
|
2866
|
+
: hits
|
|
2867
|
+
.map(
|
|
2868
|
+
(hit) =>
|
|
2869
|
+
`${shortId(hit.dispatchId)}:${hit.line} ${hit.kind === "tool" ? "→ " : ""}${hit.text}`,
|
|
2870
|
+
)
|
|
2871
|
+
.join("\n"),
|
|
2872
|
+
);
|
|
2873
|
+
return;
|
|
2874
|
+
}
|
|
2875
|
+
case "diff": {
|
|
2876
|
+
const target = arg.trim();
|
|
2877
|
+
if (!target) {
|
|
2878
|
+
notify(ctx, "Usage: /orchestra diff <dispatch id>", "error");
|
|
2879
|
+
return;
|
|
2880
|
+
}
|
|
2881
|
+
const dispatch = requireDispatch(target);
|
|
2882
|
+
const summary = gitDiff(ctx.cwd, dispatch.baseCommit);
|
|
2883
|
+
notify(ctx, diffReport(summary, `dispatch ${dispatch.id} (${dispatch.agent}, ${dispatch.status})`));
|
|
2884
|
+
return;
|
|
2885
|
+
}
|
|
2886
|
+
|
|
2887
|
+
case "report": {
|
|
2888
|
+
const run = currentRun();
|
|
2889
|
+
if (!run) {
|
|
2890
|
+
notify(ctx, "No active run to report on.", "warning");
|
|
2891
|
+
return;
|
|
2892
|
+
}
|
|
2893
|
+
const metrics = runMetrics(runtime.state, run.id);
|
|
2894
|
+
const changes: Record<string, string> = {};
|
|
2895
|
+
for (const dispatch of listDispatches(runtime.state, run.id)) {
|
|
2896
|
+
if (!dispatch.baseCommit) continue;
|
|
2897
|
+
const summary = gitDiff(ctx.cwd, dispatch.baseCommit, { maxLines: 0 });
|
|
2898
|
+
if (summary && summary.files.length > 0) changes[dispatch.id] = statText(summary);
|
|
2899
|
+
}
|
|
2900
|
+
const text = runReport(runtime.state, metrics, { changes });
|
|
2901
|
+
const paths = storePaths(runtime.root);
|
|
2902
|
+
mkdirSync(paths.exportsDir, { recursive: true });
|
|
2903
|
+
const file = join(paths.exportsDir, `${run.id}.md`);
|
|
2904
|
+
writeFileSync(file, text, "utf8");
|
|
2905
|
+
notify(ctx, text, undefined);
|
|
2906
|
+
notify(ctx, `Report written to ${file}`);
|
|
2907
|
+
return;
|
|
2908
|
+
}
|
|
2909
|
+
case "budget": {
|
|
2910
|
+
const run = currentRun();
|
|
2911
|
+
if (!run) {
|
|
2912
|
+
notify(ctx, "No active run to budget.", "warning");
|
|
2913
|
+
return;
|
|
2914
|
+
}
|
|
2915
|
+
const usage = totalUsage(runtime.state, run.id);
|
|
2916
|
+
const ceiling = Number(arg.trim());
|
|
2917
|
+
if (!arg.trim() || !Number.isFinite(ceiling) || ceiling <= 0) {
|
|
2918
|
+
notify(
|
|
2919
|
+
ctx,
|
|
2920
|
+
`${run.name}: spent ${formatCost(usage.cost)}${run.budgetUsd ? ` of ${formatCost(run.budgetUsd)}` : " (no ceiling)"}${
|
|
2921
|
+
run.budgetPaused ? " · paused" : ""
|
|
2922
|
+
}\nUsage: /orchestra budget <usd>`,
|
|
2923
|
+
);
|
|
2924
|
+
return;
|
|
2925
|
+
}
|
|
2926
|
+
run.budgetUsd = ceiling;
|
|
2927
|
+
run.budgetPaused = false;
|
|
2928
|
+
run.budgetNote = undefined;
|
|
2929
|
+
run.updatedAt = nowIso();
|
|
2930
|
+
persist();
|
|
2931
|
+
refreshUI(ctx);
|
|
2932
|
+
notify(ctx, `${run.name}: ceiling is now ${formatCost(ceiling)} (spent ${formatCost(usage.cost)}).`);
|
|
2933
|
+
return;
|
|
2934
|
+
}
|
|
2935
|
+
case "prune": {
|
|
2936
|
+
const dryRun = /--dry-run|dry/.test(arg);
|
|
2937
|
+
const days = Number(arg.replace(/--\S+/g, "").trim() || 30);
|
|
2938
|
+
const result = pruneStore(runtime.root, runtime.state, {
|
|
2939
|
+
days: Number.isFinite(days) ? days : 30,
|
|
2940
|
+
dryRun,
|
|
2941
|
+
});
|
|
2942
|
+
notify(
|
|
2943
|
+
ctx,
|
|
2944
|
+
result.files.length === 0
|
|
2945
|
+
? `Nothing older than ${result.days} days.`
|
|
2946
|
+
: `${dryRun ? "Would remove" : "Removed"} ${result.files.length} item(s) (~${Math.round(result.bytes / 1024)} KB) older than ${result.days} days.`,
|
|
2947
|
+
);
|
|
2948
|
+
return;
|
|
2949
|
+
}
|
|
2950
|
+
case "archive": {
|
|
2951
|
+
const keep = Number(arg.trim() || 5);
|
|
2952
|
+
const result = archiveRuns(runtime.root, runtime.state, { keep: Number.isFinite(keep) ? keep : 5 });
|
|
2953
|
+
persist();
|
|
2954
|
+
notify(
|
|
2955
|
+
ctx,
|
|
2956
|
+
result.archived.length
|
|
2957
|
+
? `Archived ${result.archived.length} run(s) to ${storePaths(runtime.root).archiveDir}. ${result.kept.length} live.`
|
|
2958
|
+
: `Nothing to archive (${result.kept.length} run(s) live).`,
|
|
2959
|
+
);
|
|
2960
|
+
return;
|
|
2961
|
+
}
|
|
2962
|
+
case "questions": {
|
|
2963
|
+
const gates = Object.values(runtime.state.gates).filter((gate) => gate.status === "pending");
|
|
2964
|
+
notify(ctx, gates.length > 0 ? gates.map(questionReport).join("\n\n") : "No pending questions.");
|
|
2965
|
+
return;
|
|
2966
|
+
}
|
|
2967
|
+
case "config": {
|
|
2968
|
+
const { sources } = loadConfig(ctx.cwd);
|
|
2969
|
+
notify(
|
|
2970
|
+
ctx,
|
|
2971
|
+
[
|
|
2972
|
+
`state: ${runtime.root}`,
|
|
2973
|
+
`config: ${sources.length > 0 ? sources.join(", ") : "(defaults only)"}`,
|
|
2974
|
+
"",
|
|
2975
|
+
JSON.stringify(runtime.config, null, 2),
|
|
2976
|
+
].join("\n"),
|
|
2977
|
+
);
|
|
2978
|
+
return;
|
|
2979
|
+
}
|
|
2980
|
+
default:
|
|
2981
|
+
notify(
|
|
2982
|
+
ctx,
|
|
2983
|
+
`Usage: /orchestra ${ORCHESTRA_COMMANDS.map((command) =>
|
|
2984
|
+
command.takes === "none" ? command.name : `${command.name} <${command.takes === "free" ? "text" : command.takes === "either" ? "id" : command.takes}>`,
|
|
2985
|
+
).join(" | ")}`,
|
|
2986
|
+
"error",
|
|
2987
|
+
);
|
|
2988
|
+
}
|
|
2989
|
+
},
|
|
2990
|
+
});
|
|
2991
|
+
|
|
2992
|
+
// -- rendering ----------------------------------------------------------
|
|
2993
|
+
|
|
2994
|
+
pi.registerMessageRenderer("orchestra", (message, options, theme) => {
|
|
2995
|
+
const details = (message.details ?? {}) as { status?: string };
|
|
2996
|
+
const color = details.status === "settled" ? "success" : details.status === "failed" || details.status === "timeout" ? "error" : "dim";
|
|
2997
|
+
const content = typeof message.content === "string" ? message.content : "";
|
|
2998
|
+
return new Text(theme.fg(color, content), options.outputPad, 0);
|
|
2999
|
+
});
|
|
3000
|
+
|
|
3001
|
+
pi.registerMessageRenderer("orchestra-question", (message, options, theme) => {
|
|
3002
|
+
const content = typeof message.content === "string" ? message.content : "";
|
|
3003
|
+
return new Text(theme.fg("warning", content), options.outputPad, 0);
|
|
3004
|
+
});
|
|
3005
|
+
|
|
3006
|
+
// -- lifecycle ----------------------------------------------------------
|
|
3007
|
+
|
|
3008
|
+
pi.on("session_start", async (_event, ctx) => {
|
|
3009
|
+
lastCtx = ctx;
|
|
3010
|
+
ready(ctx.cwd);
|
|
3011
|
+
refreshUI(ctx);
|
|
3012
|
+
});
|
|
3013
|
+
|
|
3014
|
+
pi.on("session_shutdown", async () => {
|
|
3015
|
+
stopTimers();
|
|
3016
|
+
await Promise.all(
|
|
3017
|
+
[...runtime.workers.values()].map(async (worker) => {
|
|
3018
|
+
await worker.abort().catch(() => undefined);
|
|
3019
|
+
await worker.stop().catch(() => undefined);
|
|
3020
|
+
}),
|
|
3021
|
+
);
|
|
3022
|
+
runtime.workers.clear();
|
|
3023
|
+
});
|
|
3024
|
+
|
|
3025
|
+
pi.on("before_agent_start", async (event) => {
|
|
3026
|
+
const run = currentRun();
|
|
3027
|
+
if (!run) return;
|
|
3028
|
+
const live = liveDispatches(runtime.state, run.id);
|
|
3029
|
+
if (live.length === 0) return;
|
|
3030
|
+
try {
|
|
3031
|
+
event.systemPromptOptions.sections.orchestra = [
|
|
3032
|
+
`run ${run.id} "${run.name}" has ${live.length} live worker(s):`,
|
|
3033
|
+
...live.map(
|
|
3034
|
+
(dispatch) =>
|
|
3035
|
+
`- ${dispatch.id} (${dispatch.agent}) ${dispatch.status}${dispatch.lastToolCall ? ` in ${dispatch.lastToolCall}` : ""}`,
|
|
3036
|
+
),
|
|
3037
|
+
"Use orchestra action=worker_list / worker_read and orchestra_wait. Do not poll with sleep loops.",
|
|
3038
|
+
].join("\n");
|
|
3039
|
+
} catch {
|
|
3040
|
+
// sections are best effort across pi versions
|
|
3041
|
+
}
|
|
3042
|
+
});
|
|
3043
|
+
}
|