master-orchestrator 0.0.0-stage → 0.2.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (50) hide show
  1. package/CHANGELOG.md +19 -0
  2. package/LICENSE +21 -0
  3. package/README.md +176 -2
  4. package/package.json +56 -4
  5. package/src/adapters/agy.ts +285 -0
  6. package/src/adapters/claude.ts +317 -0
  7. package/src/adapters/codex.ts +162 -0
  8. package/src/adapters/common.ts +211 -0
  9. package/src/adapters/dsh.ts +356 -0
  10. package/src/adapters/fake-agent.mjs +50 -0
  11. package/src/adapters/fake.ts +88 -0
  12. package/src/adapters/gemini.ts +239 -0
  13. package/src/adapters/grok.ts +328 -0
  14. package/src/adapters/omp.ts +119 -0
  15. package/src/adapters/opencode.ts +228 -0
  16. package/src/adapters/pi.ts +284 -0
  17. package/src/adapters/registry.ts +27 -0
  18. package/src/adapters/types.ts +201 -0
  19. package/src/config/load.ts +290 -0
  20. package/src/config/profiles.ts +64 -0
  21. package/src/config/schema.ts +158 -0
  22. package/src/config/write.ts +83 -0
  23. package/src/engine/artifacts.ts +145 -0
  24. package/src/engine/baseline.ts +132 -0
  25. package/src/engine/execute.ts +437 -0
  26. package/src/engine/git.ts +32 -0
  27. package/src/engine/hostenv.ts +54 -0
  28. package/src/engine/registry.ts +280 -0
  29. package/src/engine/runner.ts +249 -0
  30. package/src/engine/types.ts +55 -0
  31. package/src/engine/verify.ts +100 -0
  32. package/src/index.ts +602 -0
  33. package/src/prompts/envelope.ts +29 -0
  34. package/src/prompts/templates.ts +389 -0
  35. package/src/ui/configure.ts +174 -0
  36. package/src/ui/dialogs.ts +88 -0
  37. package/src/ui/doctor.ts +120 -0
  38. package/src/ui/format.ts +94 -0
  39. package/src/ui/host.ts +100 -0
  40. package/src/ui/render.ts +86 -0
  41. package/src/ui/widget.ts +70 -0
  42. package/src/workflows/budget.ts +66 -0
  43. package/src/workflows/common.ts +100 -0
  44. package/src/workflows/debate.ts +488 -0
  45. package/src/workflows/host.ts +78 -0
  46. package/src/workflows/plan-exec.ts +807 -0
  47. package/src/workflows/plan.ts +407 -0
  48. package/src/workflows/planfile.ts +380 -0
  49. package/src/workflows/planstate.ts +229 -0
  50. package/src/workflows/verdict.ts +74 -0
package/src/index.ts ADDED
@@ -0,0 +1,602 @@
1
+ import { randomUUID } from "node:crypto";
2
+ import { StringEnum } from "@earendil-works/pi-ai";
3
+ import { CONFIG_DIR_NAME, getAgentDir, type ExtensionAPI, type ExtensionContext } from "@earendil-works/pi-coding-agent";
4
+ import { Type } from "typebox";
5
+ import { adapterMap, BUILTIN_ADAPTERS } from "./adapters/registry.ts";
6
+ import type { AgentAdapter, Mode } from "./adapters/types.ts";
7
+ import { formatConfigErrors, loadConfig, type LoadedConfig } from "./config/load.ts";
8
+ import { describeProfile, roleProfiles } from "./config/profiles.ts";
9
+ import { defaultConfig, ROLE_NAMES, type OrchestratorConfig, type RoleName } from "./config/schema.ts";
10
+ import { readUserConfig, starterConfig, writeUserConfig } from "./config/write.ts";
11
+ import { pruneArtifacts, listRecentRuns } from "./engine/artifacts.ts";
12
+ import { currentDepth, Engine } from "./engine/execute.ts";
13
+ import { liveInstances, RunRegistry } from "./engine/registry.ts";
14
+ import type { RunResult } from "./engine/types.ts";
15
+ import { Templates } from "./prompts/templates.ts";
16
+ import { formatDuration, formatRunResult } from "./ui/format.ts";
17
+ import { configureInteractively } from "./ui/configure.ts";
18
+ import { pickProfile, pickRoleProfiles } from "./ui/dialogs.ts";
19
+ import { doctorReport } from "./ui/doctor.ts";
20
+ import { createPiHost, sendHostMessage, setToolActive, VERDICT_TOOL } from "./ui/host.ts";
21
+ import { renderDelegateCall, renderDelegateResult, renderWorkflowMessage, type DelegateDetails } from "./ui/render.ts";
22
+ import { WidgetController } from "./ui/widget.ts";
23
+ import { runDebate } from "./workflows/debate.ts";
24
+ import { MESSAGE_TYPES, WorkflowStopped, type WorkflowDeps } from "./workflows/host.ts";
25
+ import { abortPlan, executePlan, planStatus, resumePlan } from "./workflows/plan-exec.ts";
26
+ import { runPlanning } from "./workflows/plan.ts";
27
+ import { listPlans } from "./workflows/planstate.ts";
28
+ import { VerdictBroker } from "./workflows/verdict.ts";
29
+
30
+ export interface ExtensionOptions {
31
+ adapters?: readonly AgentAdapter[];
32
+ agentDir?: string;
33
+ configDirName?: string;
34
+ }
35
+
36
+ /** One extension instance: created on `session_start`, torn down on `session_shutdown`. */
37
+ interface Runtime {
38
+ ctx: ExtensionContext;
39
+ alive: boolean;
40
+ instanceId: string;
41
+ loaded: LoadedConfig;
42
+ templates: Templates;
43
+ registry: RunRegistry;
44
+ engine: Engine;
45
+ verdicts: VerdictBroker;
46
+ widget: WidgetController;
47
+ }
48
+
49
+ const DELEGATE_GUIDELINES = [
50
+ "Use delegate_task when another coding agent adds value: an independent second opinion, a parallel investigation, or a large implementation that can run in isolation. Do small edits yourself.",
51
+ "Write the delegate_task assignment so it stands on its own: the worker sees none of this conversation. Include the goal, the relevant files, constraints and what the answer must contain.",
52
+ "Use delegate_task mode implement only with a scope listing the paths the worker may change; several analyze calls can run in parallel.",
53
+ "After delegate_task returns, check material claims yourself, inspect the changed files, and look at any unexpected or out-of-scope changes it reports before telling the user the work is done.",
54
+ "Pass followUpRunId to delegate_task to continue the session of an earlier run instead of starting over.",
55
+ ];
56
+
57
+ const VERDICT_GUIDELINES = [
58
+ "Use plan_verdict only when an executing plan asks for the verdict on a block: inspect the diff, run the validation you consider necessary, then call plan_verdict once with the block id.",
59
+ ];
60
+
61
+ function output(ctx: ExtensionContext, text: string, level: "info" | "warning" | "error" = "info"): void {
62
+ if (ctx.hasUI) ctx.ui.notify(text, level);
63
+ else process.stderr.write(`${text}\n`);
64
+ }
65
+
66
+ function errorMessage(error: unknown): string {
67
+ return error instanceof Error ? error.message : String(error);
68
+ }
69
+
70
+ function stripAt(path: string): string {
71
+ return path.startsWith("@") ? path.slice(1) : path;
72
+ }
73
+
74
+ export function createExtension(options: ExtensionOptions = {}) {
75
+ return function masterOrchestrator(pi: ExtensionAPI): void {
76
+ // A worker started by this package (a pi or omp child with the package installed) registers nothing.
77
+ if (currentDepth(process.env) >= 1) return;
78
+
79
+ const adapters = adapterMap(options.adapters ?? BUILTIN_ADAPTERS);
80
+ const configDirName = options.configDirName ?? CONFIG_DIR_NAME;
81
+ const agentDir = () => options.agentDir ?? getAgentDir();
82
+ let runtime: Runtime | undefined;
83
+
84
+ const config = (): OrchestratorConfig => runtime?.loaded.config ?? defaultConfig();
85
+
86
+ const requireRuntime = (): Runtime => {
87
+ if (!runtime?.alive) throw new Error("master-orchestrator is not ready: no active session.");
88
+ return runtime;
89
+ };
90
+
91
+ /** Delegation and workflows are disabled while the configuration is invalid. */
92
+ const requireValid = (): Runtime => {
93
+ const rt = requireRuntime();
94
+ if (rt.loaded.errors.length > 0) {
95
+ throw new Error(`master-orchestrator configuration is invalid; fix it or run /orchestrator doctor:\n${formatConfigErrors(rt.loaded.errors)}`);
96
+ }
97
+ return rt;
98
+ };
99
+
100
+ const reloadConfig = async (rt: Runtime): Promise<void> => {
101
+ rt.loaded = await loadConfig({ agentDir: agentDir(), cwd: rt.ctx.cwd, configDirName, projectTrusted: rt.ctx.isProjectTrusted(), adapters });
102
+ rt.templates = new Templates(rt.loaded.config.prompts.dir);
103
+ rt.engine.clearDetections();
104
+ };
105
+
106
+ const workflowDeps = (rt: Runtime, workspace: string): WorkflowDeps => ({
107
+ engine: rt.engine,
108
+ getConfig: () => rt.loaded.config,
109
+ getTemplates: () => rt.templates,
110
+ registry: rt.registry,
111
+ agentDir: agentDir(),
112
+ configDirName,
113
+ host: createPiHost(
114
+ pi,
115
+ {
116
+ ctx: () => rt.ctx,
117
+ alive: () => rt.alive && runtime === rt,
118
+ pickRoleProfiles: (role) => pickRoleProfiles(rt.ctx, rt.engine, rt.loaded.config, agentDir(), role, () => reloadConfig(rt)),
119
+ },
120
+ workspace,
121
+ ),
122
+ instanceId: rt.instanceId,
123
+ sessionId: () => rt.ctx.sessionManager.getSessionId(),
124
+ verdicts: rt.verdicts,
125
+ });
126
+
127
+ /** Runs a command's work in the background and reports a failure. */
128
+ const background = (rt: Runtime, label: string, work: () => Promise<unknown>) => {
129
+ void work().catch((error) => {
130
+ if (error instanceof WorkflowStopped || !rt.alive) return;
131
+ output(rt.ctx, `${label} failed: ${errorMessage(error)}`, "error");
132
+ });
133
+ };
134
+
135
+ // ------------------------------------------------------------------------------------------------------------
136
+ // Lifecycle
137
+
138
+ pi.on("session_start", async (_event, ctx) => {
139
+ const instanceId = randomUUID();
140
+ liveInstances().add(instanceId);
141
+ const loaded = await loadConfig({ agentDir: agentDir(), cwd: ctx.cwd, configDirName, projectTrusted: ctx.isProjectTrusted(), adapters });
142
+ const registry = new RunRegistry(() => rt.loaded.config.defaults.maxParallel);
143
+ const rt: Runtime = {
144
+ ctx,
145
+ alive: true,
146
+ instanceId,
147
+ loaded,
148
+ templates: new Templates(loaded.config.prompts.dir),
149
+ registry,
150
+ engine: undefined as unknown as Engine,
151
+ verdicts: new VerdictBroker(),
152
+ widget: new WidgetController(registry, () => (runtime === rt && rt.alive ? rt.ctx : undefined)),
153
+ };
154
+ rt.engine = new Engine({
155
+ agentDir: agentDir(),
156
+ getConfig: () => rt.loaded.config,
157
+ adapters,
158
+ registry,
159
+ getTemplates: () => rt.templates,
160
+ projectTrusted: () => rt.ctx.isProjectTrusted(),
161
+ instanceId,
162
+ sessionId: () => rt.ctx.sessionManager.getSessionId(),
163
+ depth: currentDepth(process.env),
164
+ });
165
+ runtime = rt;
166
+ rt.widget.start();
167
+
168
+ if (loaded.errors.length > 0) {
169
+ output(ctx, `master-orchestrator configuration is invalid; delegation and workflows are disabled:\n${formatConfigErrors(loaded.errors)}`, "error");
170
+ }
171
+ for (const warning of loaded.warnings) output(ctx, `master-orchestrator: ${warning}`, "warning");
172
+
173
+ // Housekeeping that must not delay the session.
174
+ void pruneArtifacts(agentDir(), loaded.config.defaults.artifactRetentionDays).catch(() => undefined);
175
+ void listPlans(ctx.cwd, configDirName)
176
+ .then((plans) => {
177
+ const open = plans.filter((plan) => plan.state && (plan.state.status === "paused" || plan.state.status === "executing"));
178
+ if (open.length > 0 && rt.alive && ctx.hasUI) {
179
+ const names = open.map((plan) => `${plan.id} (${plan.state?.status === "executing" ? "interrupted" : "paused"})`).join(", ");
180
+ ctx.ui.notify(`Unfinished plan${open.length === 1 ? "" : "s"}: ${names}. Continue with /plan resume.`, "info");
181
+ }
182
+ })
183
+ .catch(() => undefined);
184
+ });
185
+
186
+ pi.on("session_shutdown", async () => {
187
+ const rt = runtime;
188
+ if (!rt) return;
189
+ rt.alive = false;
190
+ runtime = undefined;
191
+ rt.widget.stop();
192
+ rt.verdicts.cancel();
193
+ rt.registry.shutdown();
194
+ liveInstances().delete(rt.instanceId);
195
+ });
196
+
197
+ // A block verdict turn that ends without plan_verdict is reminded once, then the plan pauses.
198
+ pi.on("agent_settled", async (event) => {
199
+ const rt = runtime;
200
+ if (!rt?.alive) return;
201
+ const waiting = rt.verdicts.waiting;
202
+ if (!waiting) return;
203
+ if (event.aborted) {
204
+ rt.verdicts.cancel();
205
+ return;
206
+ }
207
+ if (rt.verdicts.settled() === "remind") {
208
+ sendHostMessage(
209
+ pi,
210
+ { customType: MESSAGE_TYPES.notice, content: rt.templates.render("planVerdictReminder", { planId: waiting.planId, blockId: waiting.blockId }), display: true },
211
+ true,
212
+ );
213
+ }
214
+ });
215
+
216
+ // ------------------------------------------------------------------------------------------------------------
217
+ // Tools
218
+
219
+ const delegateParameters = Type.Object({
220
+ task: Type.String({ description: "Self-contained assignment. The worker sees none of this conversation." }),
221
+ profile: Type.Optional(Type.String({ description: "Profile name or agent id (codex, claude, opencode, ...)" })),
222
+ role: Type.Optional(StringEnum(ROLE_NAMES, { description: "Alternative to profile: the role's fallback chain" })),
223
+ mode: Type.Optional(StringEnum(["analyze", "implement"] as const, { description: "analyze (default) or implement" })),
224
+ scope: Type.Optional(Type.Array(Type.String(), { description: "Editable paths and globs for implement, relative to the workspace" })),
225
+ followUpRunId: Type.Optional(Type.String({ description: "Continue the session of an earlier run" })),
226
+ });
227
+
228
+ pi.registerTool<typeof delegateParameters, DelegateDetails>({
229
+ name: "delegate_task",
230
+ label: "Delegate",
231
+ description:
232
+ "Run one assignment with another coding agent (Codex, Claude Code, OpenCode, pi, ...) in this workspace and return its report together with what it actually changed.",
233
+ promptSnippet: "Delegate an assignment to another coding agent",
234
+ promptGuidelines: DELEGATE_GUIDELINES,
235
+ parameters: delegateParameters,
236
+ async execute(_toolCallId, params, signal, onUpdate, ctx) {
237
+ const rt = requireValid();
238
+ const mode: Mode = params.mode ?? "analyze";
239
+ const workspace = ctx.cwd;
240
+ let profiles: string[];
241
+ let followUp: { sessionId: string } | undefined;
242
+
243
+ if (params.followUpRunId) {
244
+ const meta = await rt.engine.findRun(workspace, params.followUpRunId);
245
+ if (!meta) throw new Error(`Run ${params.followUpRunId} was not found in this workspace.`);
246
+ if (!meta.sessionId) throw new Error(`Run ${params.followUpRunId} has no session to continue; start a new assignment instead.`);
247
+ if (params.profile && params.profile !== meta.profile) {
248
+ throw new Error(`Run ${params.followUpRunId} ran on profile ${meta.profile}; a follow-up continues on the same profile.`);
249
+ }
250
+ profiles = [meta.profile];
251
+ followUp = { sessionId: meta.sessionId };
252
+ } else if (params.profile) {
253
+ if (!rt.engine.resolve(params.profile)) {
254
+ throw new Error(`Unknown profile "${params.profile}". Known: ${[...Object.keys(rt.loaded.config.profiles), ...adapters.keys()].join(", ")}.`);
255
+ }
256
+ profiles = [params.profile];
257
+ } else if (params.role) {
258
+ const chain = roleProfiles(rt.loaded.config, params.role as RoleName);
259
+ if (!chain) throw new Error(`The role "${params.role}" is not configured. Pass a profile instead, or ask the user to configure roles.${params.role}.`);
260
+ profiles = chain;
261
+ } else {
262
+ throw new Error(`Pass a profile or a role. Profiles: ${[...Object.keys(rt.loaded.config.profiles), ...adapters.keys()].join(", ")}.`);
263
+ }
264
+
265
+ const scope = params.scope?.map(stripAt);
266
+ if (mode === "implement" && rt.loaded.config.approval.implementFromTool === "ask") {
267
+ const refusal = "Do not retry this call or a variant of it; ask the user how to proceed.";
268
+ if (!ctx.hasUI) throw new Error(`implement runs need the user's confirmation and there is no UI. ${refusal}`);
269
+ const profile = rt.engine.resolve(profiles[0]);
270
+ const confirmed = await ctx.ui.confirm(
271
+ "Delegate an implement run?",
272
+ [`Profile: ${profile ? describeProfile(profile) : profiles[0]}`, `Scope: ${scope?.join(", ") || "(none given)"}`, "", params.task].join("\n"),
273
+ );
274
+ if (!confirmed) throw new Error(`The user declined the implement run. ${refusal}`);
275
+ }
276
+
277
+ const startedAt = Date.now();
278
+ let runId: string | undefined;
279
+ const report = () => {
280
+ const active = runId ? rt.registry.get(runId) : undefined;
281
+ onUpdate?.({
282
+ content: [{ type: "text", text: `running${active ? ` on ${active.profile}` : ""} · ${formatDuration(Date.now() - startedAt)}` }],
283
+ details: { progress: { runId, profile: active?.profile, elapsedMs: Date.now() - startedAt, lastActivity: active?.lastActivity } },
284
+ });
285
+ };
286
+ const timer = onUpdate ? setInterval(report, 1_000) : undefined;
287
+ let result: RunResult;
288
+ try {
289
+ result = await rt.engine.run({
290
+ task: params.task,
291
+ mode,
292
+ scope,
293
+ workspace,
294
+ profiles,
295
+ followUp,
296
+ label: "delegate_task",
297
+ signal,
298
+ onEvent: (id, event) => {
299
+ runId = id;
300
+ if (event.type === "activity") report();
301
+ },
302
+ });
303
+ } finally {
304
+ if (timer) clearInterval(timer);
305
+ }
306
+ return { content: [{ type: "text", text: formatRunResult(result) }], details: result };
307
+ },
308
+ renderCall: (args, theme) => renderDelegateCall(args, theme),
309
+ renderResult: (result, renderOptions, theme, context) =>
310
+ renderDelegateResult(result.details, renderOptions, theme, context.keyHint("app.tools.expand", "to expand")),
311
+ });
312
+
313
+ const verdictParameters = Type.Object({
314
+ blockId: Type.String({ description: "Id of the block that is waiting for the verdict, for example \"2\"" }),
315
+ verdict: StringEnum(["accepted", "needs_fix", "blocked"] as const, { description: "accepted, needs_fix or blocked" }),
316
+ feedback: Type.String({ description: "What must change (needs_fix) or what blocks the block (blocked); may be empty for accepted" }),
317
+ });
318
+
319
+ pi.registerTool<typeof verdictParameters, undefined>({
320
+ name: VERDICT_TOOL,
321
+ label: "Plan verdict",
322
+ description: "Give the verdict on a block of the executing plan after inspecting its changes and review.",
323
+ promptSnippet: "Give the verdict on a plan block",
324
+ promptGuidelines: VERDICT_GUIDELINES,
325
+ parameters: verdictParameters,
326
+ defaultActive: false,
327
+ async execute(_toolCallId, params) {
328
+ const rt = requireRuntime();
329
+ const outcome = rt.verdicts.submit({ blockId: params.blockId, verdict: params.verdict, feedback: params.feedback });
330
+ if (!outcome.ok) throw new Error(outcome.message);
331
+ return { content: [{ type: "text", text: outcome.message }], details: undefined };
332
+ },
333
+ });
334
+
335
+ // ------------------------------------------------------------------------------------------------------------
336
+ // Message renderers
337
+
338
+ const kinds: Record<string, string> = {
339
+ [MESSAGE_TYPES.delegate]: "delegate",
340
+ [MESSAGE_TYPES.debate]: "debate",
341
+ [MESSAGE_TYPES.plan]: "plan",
342
+ [MESSAGE_TYPES.block]: "block",
343
+ [MESSAGE_TYPES.notice]: "orchestrator",
344
+ };
345
+ for (const [customType, kind] of Object.entries(kinds)) {
346
+ pi.registerMessageRenderer(customType, (message, renderOptions, theme) =>
347
+ renderWorkflowMessage(
348
+ kind,
349
+ typeof message.content === "string" ? message.content : message.content.flatMap((part) => (part.type === "text" ? [part.text] : [])).join("\n"),
350
+ message.details,
351
+ renderOptions,
352
+ theme,
353
+ renderOptions.keyHint("app.tools.expand", "to expand"),
354
+ ),
355
+ );
356
+ }
357
+
358
+ // ------------------------------------------------------------------------------------------------------------
359
+ // Commands
360
+
361
+ pi.registerCommand("delegate", {
362
+ description: "Run one assignment with another agent: /delegate [profile] [--implement] <task>",
363
+ getArgumentCompletions: (prefix) => {
364
+ const names = [...Object.keys(config().profiles), ...adapters.keys()];
365
+ const items = names.filter((name) => name.startsWith(prefix)).map((name) => ({ value: name, label: name }));
366
+ return items.length > 0 ? items : null;
367
+ },
368
+ handler: async (args, ctx) => {
369
+ let rt: Runtime;
370
+ try {
371
+ rt = requireValid();
372
+ } catch (error) {
373
+ output(ctx, errorMessage(error), "error");
374
+ return;
375
+ }
376
+ let text = args.trim();
377
+ let mode: Mode = "analyze";
378
+ let profile: string | undefined;
379
+ const first = text.split(/\s+/)[0] ?? "";
380
+ if (first && rt.engine.resolve(first)) {
381
+ profile = first;
382
+ text = text.slice(first.length).trim();
383
+ }
384
+ if (/^(--implement|-i)(\s|$)/.test(text)) {
385
+ mode = "implement";
386
+ text = text.replace(/^(--implement|-i)\s*/, "");
387
+ }
388
+ let scope: string[] | undefined;
389
+ if (!text) {
390
+ if (!ctx.hasUI) {
391
+ output(ctx, "Usage: /delegate [profile] [--implement] <task>", "error");
392
+ return;
393
+ }
394
+ profile ??= await pickProfile(ctx, rt.engine, rt.loaded.config, "Delegate to which profile?");
395
+ if (!profile) return;
396
+ const pickedMode = await ctx.ui.select("Mode", ["analyze (read-only investigation)", "implement (may change files)"]);
397
+ if (!pickedMode) return;
398
+ mode = pickedMode.startsWith("implement") ? "implement" : "analyze";
399
+ const task = await ctx.ui.editor(`Assignment for ${profile} (${mode})`, "");
400
+ if (!task?.trim()) return;
401
+ text = task.trim();
402
+ if (mode === "implement") {
403
+ const answer = await ctx.ui.input("Editable scope (comma-separated paths or globs, empty for none)", "src/**");
404
+ scope = answer?.split(",").map((entry) => stripAt(entry.trim())).filter(Boolean);
405
+ }
406
+ } else if (!profile) {
407
+ if (!ctx.hasUI) {
408
+ output(ctx, `Name a profile: /delegate <profile> <task>. Profiles: ${[...Object.keys(rt.loaded.config.profiles), ...adapters.keys()].join(", ")}`, "error");
409
+ return;
410
+ }
411
+ profile = await pickProfile(ctx, rt.engine, rt.loaded.config, "Delegate to which profile?");
412
+ if (!profile) return;
413
+ }
414
+ const workspace = ctx.cwd;
415
+ const chosen = profile;
416
+ const task = text;
417
+ output(ctx, `Delegating to ${chosen} (${mode}); the result arrives as a message.`);
418
+ background(rt, "Delegation", async () => {
419
+ const result = await rt.engine.run({ task, mode, scope, workspace, profiles: [chosen], label: "/delegate" });
420
+ if (!rt.alive) return;
421
+ sendHostMessage(pi, { customType: MESSAGE_TYPES.delegate, content: formatRunResult(result), details: result, display: true }, false);
422
+ });
423
+ },
424
+ });
425
+
426
+ pi.registerCommand("debate", {
427
+ description: "Start a debate between agents: /debate <question>",
428
+ handler: async (args, ctx) => {
429
+ let rt: Runtime;
430
+ try {
431
+ rt = requireValid();
432
+ } catch (error) {
433
+ output(ctx, errorMessage(error), "error");
434
+ return;
435
+ }
436
+ let question = args.trim();
437
+ if (!question && ctx.hasUI) question = (await ctx.ui.editor("Debate question", ""))?.trim() ?? "";
438
+ if (!question) {
439
+ output(ctx, "Usage: /debate <question>", "error");
440
+ return;
441
+ }
442
+ const deps = workflowDeps(rt, ctx.cwd);
443
+ background(rt, "Debate", () => runDebate(deps, question));
444
+ },
445
+ });
446
+
447
+ pi.registerCommand("plan", {
448
+ description: "Plan with agents: /plan <goal> | resume [id] | status | abort [id]",
449
+ getArgumentCompletions: (prefix) => {
450
+ const items = ["resume", "status", "abort"].filter((name) => name.startsWith(prefix)).map((name) => ({ value: name, label: name }));
451
+ return items.length > 0 ? items : null;
452
+ },
453
+ handler: async (args, ctx) => {
454
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
455
+ const argument = rest.join(" ").trim() || undefined;
456
+ let rt: Runtime;
457
+ try {
458
+ rt = sub === "status" ? requireRuntime() : requireValid();
459
+ } catch (error) {
460
+ output(ctx, errorMessage(error), "error");
461
+ return;
462
+ }
463
+ const deps = workflowDeps(rt, ctx.cwd);
464
+ if (sub === "status") {
465
+ output(ctx, await planStatus(deps));
466
+ return;
467
+ }
468
+ if (sub === "abort") {
469
+ output(ctx, await abortPlan(deps, argument));
470
+ return;
471
+ }
472
+ if (sub === "resume") {
473
+ background(rt, "Plan", () => resumePlan(deps, argument));
474
+ return;
475
+ }
476
+ let goal = args.trim();
477
+ if (!goal && ctx.hasUI) goal = (await ctx.ui.editor("Goal of the plan", ""))?.trim() ?? "";
478
+ if (!goal) {
479
+ output(ctx, "Usage: /plan <goal> | resume [id] | status | abort [id]", "error");
480
+ return;
481
+ }
482
+ background(rt, "Plan", async () => {
483
+ const result = await runPlanning(deps, goal);
484
+ if (result.status === "approved" && result.planId && rt.alive) await executePlan(deps, result.planId);
485
+ });
486
+ },
487
+ });
488
+
489
+ const SUBCOMMANDS = ["doctor", "init", "config", "runs", "cancel"];
490
+ pi.registerCommand("orchestrator", {
491
+ description: "master-orchestrator: doctor | init | config | runs | cancel [runId|all]",
492
+ getArgumentCompletions: (prefix) => {
493
+ const items = SUBCOMMANDS.filter((name) => name.startsWith(prefix)).map((name) => ({ value: name, label: name }));
494
+ return items.length > 0 ? items : null;
495
+ },
496
+ handler: async (args, ctx) => {
497
+ const [sub = "", ...rest] = args.trim().split(/\s+/);
498
+ const argument = rest.join(" ").trim();
499
+ let rt: Runtime;
500
+ try {
501
+ rt = requireRuntime();
502
+ } catch (error) {
503
+ output(ctx, errorMessage(error), "error");
504
+ return;
505
+ }
506
+ switch (sub) {
507
+ case "doctor": {
508
+ rt.engine.clearDetections();
509
+ await reloadConfig(rt);
510
+ output(ctx, await doctorReport(rt.engine, rt.loaded, ctx.cwd, ctx.isProjectTrusted()));
511
+ return;
512
+ }
513
+ case "init": {
514
+ const file = await readUserConfig(agentDir());
515
+ if (file.present) {
516
+ output(ctx, `${file.path} already exists; edit it or use /orchestrator config.`, "warning");
517
+ return;
518
+ }
519
+ const detected: string[] = [];
520
+ for (const id of adapters.keys()) {
521
+ if ((await rt.engine.availability(id)).ok) detected.push(id);
522
+ }
523
+ let value = starterConfig(detected);
524
+ if (ctx.hasUI) {
525
+ const edited = await ctx.ui.editor(`Starter configuration for ${file.path} (review, then save; empty to cancel)`, `${JSON.stringify(value, null, 2)}\n`);
526
+ if (!edited?.trim()) return;
527
+ try {
528
+ value = JSON.parse(edited);
529
+ } catch (error) {
530
+ output(ctx, `Not saved: invalid JSON: ${errorMessage(error)}`, "error");
531
+ return;
532
+ }
533
+ }
534
+ try {
535
+ const path = await writeUserConfig(agentDir(), value, adapters);
536
+ await reloadConfig(rt);
537
+ output(ctx, `Wrote ${path} (${detected.length} detected agent${detected.length === 1 ? "" : "s"}: ${detected.join(", ") || "none"}).`);
538
+ } catch (error) {
539
+ output(ctx, `Not saved:\n${errorMessage(error)}`, "error");
540
+ }
541
+ return;
542
+ }
543
+ case "config": {
544
+ if (!ctx.hasUI) {
545
+ output(ctx, "/orchestrator config needs a UI; edit the configuration file instead.", "error");
546
+ return;
547
+ }
548
+ await configureInteractively(ctx, rt.engine, rt.loaded.config, agentDir(), () => reloadConfig(rt));
549
+ return;
550
+ }
551
+ case "runs": {
552
+ const active = rt.registry.list();
553
+ const recent = await listRecentRuns(agentDir(), ctx.cwd, 15);
554
+ const lines = ["Active runs:"];
555
+ if (active.length === 0) lines.push(" (none)");
556
+ for (const run of active) {
557
+ lines.push(` ${run.runId} · ${run.profile} · ${run.mode}${run.label ? ` · ${run.label}` : ""} · ${formatDuration(Date.now() - run.startedAt)}${run.lastActivity ? ` · ${run.lastActivity}` : ""}`);
558
+ }
559
+ for (const workflow of rt.registry.listWorkflows()) lines.push(` ${workflow.id} · ${workflow.header}`);
560
+ lines.push("", "Recent runs in this workspace:");
561
+ if (recent.length === 0) lines.push(" (none)");
562
+ for (const run of recent) lines.push(` ${run.runId} · ${run.profile} · ${run.mode} · ${run.status ?? "running or interrupted"} · ${run.dir}`);
563
+ output(ctx, lines.join("\n"));
564
+ return;
565
+ }
566
+ case "cancel": {
567
+ let target = argument;
568
+ if (!target) {
569
+ const candidates = [
570
+ ...rt.registry.listWorkflows().map((workflow) => ({ id: workflow.id, label: `${workflow.id} · ${workflow.header}` })),
571
+ ...rt.registry.list().map((run) => ({ id: run.runId, label: `${run.runId} · ${run.profile}${run.label ? ` · ${run.label}` : ""}` })),
572
+ ];
573
+ if (candidates.length === 0) {
574
+ output(ctx, "Nothing is running.");
575
+ return;
576
+ }
577
+ if (candidates.length === 1) target = candidates[0].id;
578
+ else if (ctx.hasUI) {
579
+ const picked = await ctx.ui.select("Cancel what?", ["Everything", ...candidates.map((candidate) => candidate.label)]);
580
+ if (!picked) return;
581
+ target = picked === "Everything" ? "all" : (candidates.find((candidate) => candidate.label === picked)?.id ?? "");
582
+ } else {
583
+ output(ctx, `Name what to cancel: /orchestrator cancel <id|all>. Active: ${candidates.map((candidate) => candidate.id).join(", ")}`, "error");
584
+ return;
585
+ }
586
+ }
587
+ const cancelled = rt.registry.cancel(target);
588
+ output(ctx, cancelled.length > 0 ? `Cancelling ${cancelled.join(", ")}.` : `Nothing named ${target} is running.`, cancelled.length > 0 ? "info" : "warning");
589
+ return;
590
+ }
591
+ default:
592
+ output(ctx, "Usage: /orchestrator doctor | init | config | runs | cancel [runId|all]", sub ? "error" : "info");
593
+ }
594
+ },
595
+ });
596
+
597
+ // Keep the verdict tool out of the active set until a plan executes.
598
+ pi.on("session_start", async () => setToolActive(pi, VERDICT_TOOL, false));
599
+ };
600
+ }
601
+
602
+ export default createExtension();
@@ -0,0 +1,29 @@
1
+ import type { Mode } from "../adapters/types.ts";
2
+ import type { Templates } from "./templates.ts";
3
+
4
+ export interface EnvelopeInput {
5
+ task: string;
6
+ mode: Mode;
7
+ scope?: readonly string[];
8
+ workspace: string;
9
+ scratch: string;
10
+ }
11
+
12
+ /** Wraps an assignment in the standard envelope: mode, scratch directory, no questions, no delegation, Git, evidence. */
13
+ export function buildEnvelope(templates: Templates, input: EnvelopeInput): string {
14
+ let modeRules: string;
15
+ if (input.mode === "analyze") modeRules = templates.get("modeAnalyze");
16
+ else if (input.scope && input.scope.length > 0) {
17
+ modeRules = templates.render("modeImplementScoped", {
18
+ scopeList: input.scope.map((entry) => ` - ${entry}`).join("\n"),
19
+ });
20
+ } else modeRules = templates.get("modeImplementOpen");
21
+
22
+ return templates.render("envelope", {
23
+ task: input.task.trim(),
24
+ modeRules,
25
+ workspace: input.workspace,
26
+ scratch: input.scratch,
27
+ evidence: templates.get(input.mode === "analyze" ? "evidenceAnalyze" : "evidenceImplement"),
28
+ });
29
+ }