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
@@ -0,0 +1,488 @@
1
+ import { writeFile } from "node:fs/promises";
2
+ import { join } from "node:path";
3
+ import type { Usage } from "../adapters/types.ts";
4
+ import { createWorkflowDir, newWorkflowId } from "../engine/artifacts.ts";
5
+ import { diffBaseline, takeBaseline } from "../engine/baseline.ts";
6
+ import type { RunResult } from "../engine/types.ts";
7
+ import { fitParts, resultPath } from "./budget.ts";
8
+ import {
9
+ costGate,
10
+ ensureAlive,
11
+ errorText,
12
+ frameBrief,
13
+ lastJsonBlock,
14
+ profileLabel,
15
+ resolveRole,
16
+ titleOf,
17
+ withoutTrailingJson,
18
+ } from "./common.ts";
19
+ import { ENTRY_TYPE, MESSAGE_TYPES, WorkflowStopped, type WorkflowDeps } from "./host.ts";
20
+
21
+ export interface Disagreement {
22
+ with?: string;
23
+ point?: string;
24
+ evidence?: string;
25
+ }
26
+
27
+ export interface Stance {
28
+ position: string;
29
+ confidence?: string;
30
+ changed: boolean;
31
+ disagreements: Disagreement[];
32
+ /** False when the block was missing or invalid: counts as changed, with unknown disagreements. */
33
+ valid: boolean;
34
+ }
35
+
36
+ export interface RoundEntry {
37
+ round: number;
38
+ runId?: string;
39
+ status: string;
40
+ reason?: string;
41
+ answer?: string;
42
+ stance?: Stance;
43
+ artifactsDir?: string;
44
+ durationMs?: number;
45
+ usage?: Usage;
46
+ resumed: boolean;
47
+ /** Session of the run, when the adapter can continue it. */
48
+ sessionId?: string;
49
+ }
50
+
51
+ export interface Participant {
52
+ label: string;
53
+ profile: string;
54
+ description: string;
55
+ active: boolean;
56
+ droppedAfterRound?: number;
57
+ rounds: RoundEntry[];
58
+ }
59
+
60
+ export type DebateStatus = "framing" | "running" | "converged" | "round_limit" | "partial" | "failed" | "cancelled" | "stopped";
61
+
62
+ export interface DebateRecord {
63
+ id: string;
64
+ kind: "debate";
65
+ title: string;
66
+ question: string;
67
+ brief: string;
68
+ status: DebateStatus;
69
+ maxRounds: number;
70
+ anonymize: boolean;
71
+ roundsRun: number;
72
+ startedAt: string;
73
+ endedAt?: string;
74
+ participants: Participant[];
75
+ roundChanges: Array<{ round: number; changed: string[]; note: string }>;
76
+ excluded: Array<{ profile: string; reason: string }>;
77
+ error?: string;
78
+ dir: string;
79
+ }
80
+
81
+ export const STANCE_SCHEMA = {
82
+ type: "object",
83
+ additionalProperties: false,
84
+ required: ["answer", "position", "confidence", "changed", "disagreements"],
85
+ properties: {
86
+ answer: { type: "string" },
87
+ position: { type: "string" },
88
+ confidence: { type: "string", enum: ["low", "medium", "high"] },
89
+ changed: { type: "boolean" },
90
+ disagreements: {
91
+ type: "array",
92
+ items: {
93
+ type: "object",
94
+ additionalProperties: false,
95
+ required: ["with", "point", "evidence"],
96
+ properties: { with: { type: "string" }, point: { type: "string" }, evidence: { type: "string" } },
97
+ },
98
+ },
99
+ },
100
+ } as const;
101
+
102
+ /** Reads the stance of an answer: native structured output first, then the last fenced JSON block. */
103
+ export function parseStance(result: { finalText?: string; structuredOutput?: unknown }): { stance: Stance; answer: string } {
104
+ const structured = result.structuredOutput;
105
+ const source = isRecord(structured) ? structured : lastJsonBlock(result.finalText);
106
+ const text = result.finalText ?? "";
107
+ const answer = isRecord(structured) && typeof structured.answer === "string" ? structured.answer : withoutTrailingJson(text) || text;
108
+ if (!isRecord(source) || typeof source.position !== "string" || !source.position.trim()) {
109
+ return { stance: { position: "", changed: true, disagreements: [], valid: false }, answer };
110
+ }
111
+ const disagreements = Array.isArray(source.disagreements)
112
+ ? source.disagreements.filter(isRecord).map((entry) => ({
113
+ with: typeof entry.with === "string" ? entry.with : undefined,
114
+ point: typeof entry.point === "string" ? entry.point : undefined,
115
+ evidence: typeof entry.evidence === "string" ? entry.evidence : undefined,
116
+ }))
117
+ : [];
118
+ return {
119
+ stance: {
120
+ position: source.position.trim(),
121
+ confidence: typeof source.confidence === "string" ? source.confidence : undefined,
122
+ changed: source.changed !== false,
123
+ disagreements,
124
+ valid: Array.isArray(source.disagreements) && typeof source.changed === "boolean",
125
+ },
126
+ answer,
127
+ };
128
+ }
129
+
130
+ function isRecord(value: unknown): value is Record<string, unknown> {
131
+ return typeof value === "object" && value !== null && !Array.isArray(value);
132
+ }
133
+
134
+ const LETTERS = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
135
+
136
+ /** Runs a debate from the user's question to the synthesis turn. Never throws for run failures. */
137
+ export async function runDebate(deps: WorkflowDeps, question: string): Promise<DebateRecord | undefined> {
138
+ const config = deps.getConfig();
139
+ const { host } = deps;
140
+ const settings = config.debate;
141
+
142
+ const names = [...new Set(await resolveRole(deps, "debater", true))];
143
+ if (names.length < settings.minParticipants) {
144
+ throw new Error(`A debate needs at least ${settings.minParticipants} debaters; roles.debater lists ${names.length}.`);
145
+ }
146
+ const usable: string[] = [];
147
+ const excluded: Array<{ profile: string; reason: string }> = [];
148
+ for (const name of names) {
149
+ const profile = deps.engine.resolve(name);
150
+ if (!profile) {
151
+ excluded.push({ profile: name, reason: "unknown profile" });
152
+ continue;
153
+ }
154
+ const availability = await deps.engine.availability(profile.agent);
155
+ if (availability.ok) usable.push(name);
156
+ else excluded.push({ profile: name, reason: availability.reason });
157
+ }
158
+ if (usable.length < settings.minParticipants) {
159
+ const reasons = excluded.map((entry) => `${entry.profile}: ${entry.reason}`).join("; ");
160
+ throw new Error(`Only ${usable.length} debaters can run (at least ${settings.minParticipants} needed). ${reasons}`);
161
+ }
162
+
163
+ const id = newWorkflowId("debate");
164
+ const controller = new AbortController();
165
+ const signal = controller.signal;
166
+ deps.registry.addWorkflow({ id, kind: "debate", header: "debate · framing", controller });
167
+ const record: DebateRecord = {
168
+ id,
169
+ kind: "debate",
170
+ title: titleOf(question),
171
+ question,
172
+ brief: "",
173
+ status: "framing",
174
+ maxRounds: settings.maxRounds,
175
+ anonymize: settings.anonymize,
176
+ roundsRun: 0,
177
+ startedAt: new Date().toISOString(),
178
+ participants: usable.map((profile, index) => ({
179
+ label: settings.anonymize ? `Participant ${LETTERS[index]}` : profile,
180
+ profile,
181
+ description: profileLabel(deps, profile),
182
+ active: true,
183
+ rounds: [],
184
+ })),
185
+ roundChanges: [],
186
+ excluded,
187
+ dir: "",
188
+ };
189
+
190
+ try {
191
+ const brief = await frameBrief(deps, question, "independent coding agents who will debate it", "Debate", signal);
192
+ if (!brief) {
193
+ host.notify("Debate cancelled.", "info");
194
+ return undefined;
195
+ }
196
+ record.brief = brief;
197
+ const runsBound = usable.length * (1 + settings.maxRounds);
198
+ const gate = await costGate(deps, "Start the debate?", [
199
+ `Participants (${usable.length}):`,
200
+ ...record.participants.map((participant) => ` ${participant.label}: ${participant.description}`),
201
+ ...excluded.map((entry) => ` excluded ${entry.profile}: ${entry.reason}`),
202
+ `Rounds: opening + up to ${settings.maxRounds} rebuttal round(s)`,
203
+ `Upper bound: ${runsBound} runs (analyze mode, full access, in ${host.workspace})`,
204
+ ]);
205
+ if (!gate) {
206
+ host.notify("Debate cancelled.", "info");
207
+ return undefined;
208
+ }
209
+
210
+ record.dir = await createWorkflowDir(deps.agentDir, host.workspace, id);
211
+ record.status = "running";
212
+ await writeRecord(record);
213
+ ensureAlive(deps);
214
+ host.appendEntry(ENTRY_TYPE, { kind: "debate", id, dir: record.dir, title: record.title, startedAt: record.startedAt });
215
+ host.notify(`Debate ${id} started with ${usable.length} participants.`, "info");
216
+
217
+ for (let round = 0; round <= settings.maxRounds; round++) {
218
+ const active = record.participants.filter((participant) => participant.active);
219
+ deps.registry.setWorkflowHeader(id, round === 0 ? `debate · opening (round 0/${settings.maxRounds})` : `debate · round ${round}/${settings.maxRounds}`);
220
+ const before = await takeBaseline(host.workspace);
221
+ await Promise.all(active.map((participant) => runTurn(deps, record, participant, round, signal)));
222
+ const changes = await diffBaseline(host.workspace, before);
223
+ if (changes.changed.length > 0 || !changes.git) record.roundChanges.push({ round, changed: changes.changed, note: changes.note });
224
+ record.roundsRun = round + 1;
225
+
226
+ if (signal.aborted) {
227
+ record.status = "cancelled";
228
+ break;
229
+ }
230
+ for (const participant of active) {
231
+ const entry = participant.rounds.at(-1);
232
+ if (entry?.status !== "completed") {
233
+ participant.active = false;
234
+ participant.droppedAfterRound = round;
235
+ }
236
+ }
237
+ await writeRecord(record);
238
+ const remaining = record.participants.filter((participant) => participant.active);
239
+ if (remaining.length < 2) {
240
+ record.status = remaining.length === 0 && !hasPosition(record) ? "failed" : "partial";
241
+ break;
242
+ }
243
+ if (round > 0 && remaining.every((participant) => converged(participant.rounds.at(-1)))) {
244
+ record.status = "converged";
245
+ break;
246
+ }
247
+ if (round === settings.maxRounds) record.status = "round_limit";
248
+ }
249
+ } catch (error) {
250
+ if (!record.dir) {
251
+ // Nothing started yet: framing or the cost gate failed. The command reports it.
252
+ deps.registry.removeWorkflow(id);
253
+ if (error instanceof WorkflowStopped || signal.aborted) return undefined;
254
+ throw error;
255
+ }
256
+ if (error instanceof WorkflowStopped || signal.aborted) record.status = signal.aborted ? "cancelled" : "stopped";
257
+ else {
258
+ record.status = "failed";
259
+ record.error = errorText(error);
260
+ }
261
+ } finally {
262
+ deps.registry.removeWorkflow(id);
263
+ }
264
+
265
+ record.endedAt = new Date().toISOString();
266
+ if (record.dir) await writeRecord(record).catch(() => undefined);
267
+ if (!host.alive() || record.status === "stopped") return record;
268
+
269
+ if (record.status === "cancelled") {
270
+ host.notify(`Debate ${id} cancelled. Record: ${record.dir || "(not written)"}`, "warning");
271
+ return record;
272
+ }
273
+ if (record.status === "failed" || !hasPosition(record)) {
274
+ record.status = "failed";
275
+ const reason = record.error ?? "no participant produced a position";
276
+ host.sendMessage(
277
+ {
278
+ customType: MESSAGE_TYPES.debate,
279
+ content: `The debate "${record.title}" ended without a synthesis: ${reason}.${record.dir ? ` Record: ${record.dir}` : ""}`,
280
+ details: summary(record),
281
+ display: true,
282
+ },
283
+ false,
284
+ );
285
+ return record;
286
+ }
287
+ host.sendMessage({ customType: MESSAGE_TYPES.debate, content: synthesisMessage(deps, record), details: summary(record), display: true }, true);
288
+ return record;
289
+ }
290
+
291
+ async function runTurn(deps: WorkflowDeps, record: DebateRecord, participant: Participant, round: number, signal: AbortSignal): Promise<void> {
292
+ const templates = deps.getTemplates();
293
+ const profile = deps.engine.resolve(participant.profile);
294
+ const structured = Boolean(profile && deps.engine.adapters.get(profile.agent)?.capabilities.structuredOutput);
295
+ const stanceFormat = templates.get(structured ? "stanceStructured" : "stanceFormat");
296
+ const previous = [...participant.rounds].reverse().find((entry) => entry.status === "completed");
297
+ const lastRun = participant.rounds.at(-1);
298
+ const resume = round > 0 && lastRun?.status === "completed" && lastRun.sessionId ? lastRun : undefined;
299
+
300
+ let task: string;
301
+ if (round === 0) {
302
+ task = templates.render("debateOpening", { brief: record.brief, stanceFormat });
303
+ } else {
304
+ const others = record.participants
305
+ .filter((other) => other !== participant && other.active)
306
+ .map((other) => {
307
+ const latest = [...other.rounds].reverse().find((entry) => entry.status === "completed");
308
+ return {
309
+ title: other.label,
310
+ text: latest ? `${latest.answer ?? ""}\n\nSummary: ${latest.stance?.position || "(no summary)"}` : "(no position)",
311
+ fullPath: latest?.artifactsDir ? resultPath(latest.artifactsDir) : undefined,
312
+ };
313
+ });
314
+ const ownPrevious = resume || !previous ? "" : `\n## Your previous position\n\n${previous.answer ?? previous.stance?.position ?? ""}\n`;
315
+ task = templates.render("debateRebuttal", {
316
+ round,
317
+ maxRounds: record.maxRounds,
318
+ brief: record.brief,
319
+ ownPrevious,
320
+ others: fitParts(others, "", 40 * 1024, 1500),
321
+ stanceFormat,
322
+ });
323
+ }
324
+
325
+ const entry: RoundEntry = { round, status: "running", resumed: Boolean(resume) };
326
+ participant.rounds.push(entry);
327
+ let result: RunResult;
328
+ try {
329
+ result = await deps.engine.run({
330
+ task,
331
+ mode: "analyze",
332
+ workspace: deps.host.workspace,
333
+ profiles: [participant.profile],
334
+ followUp: resume?.sessionId ? { sessionId: resume.sessionId } : undefined,
335
+ outputSchema: structured ? STANCE_SCHEMA : undefined,
336
+ label: `${participant.label} · round ${round}/${record.maxRounds}`,
337
+ workflowId: record.id,
338
+ signal,
339
+ });
340
+ } catch (error) {
341
+ entry.status = signal.aborted ? "cancelled" : "failed";
342
+ entry.reason = errorText(error);
343
+ return;
344
+ }
345
+ entry.runId = result.runId;
346
+ entry.status = result.status;
347
+ entry.reason = result.reason;
348
+ entry.artifactsDir = result.artifactsDir;
349
+ entry.durationMs = result.durationMs;
350
+ entry.usage = result.usage;
351
+ if (result.resumable && result.sessionId) entry.sessionId = result.sessionId;
352
+ if (result.status === "completed") {
353
+ const parsed = parseStance(result);
354
+ entry.stance = parsed.stance;
355
+ entry.answer = parsed.answer;
356
+ } else {
357
+ entry.answer = result.finalText;
358
+ }
359
+ }
360
+
361
+ function converged(entry: RoundEntry | undefined): boolean {
362
+ return Boolean(entry?.stance?.valid && !entry.stance.changed && entry.stance.disagreements.length === 0);
363
+ }
364
+
365
+ function hasPosition(record: DebateRecord): boolean {
366
+ return record.participants.some((participant) => participant.rounds.some((entry) => entry.status === "completed"));
367
+ }
368
+
369
+ function outcomeText(record: DebateRecord): string {
370
+ switch (record.status) {
371
+ case "converged":
372
+ return `converged after round ${record.roundsRun - 1}`;
373
+ case "round_limit":
374
+ return `round limit reached (${record.maxRounds} rebuttal round(s))`;
375
+ case "partial":
376
+ return "partial: fewer than two participants remained";
377
+ default:
378
+ return record.status;
379
+ }
380
+ }
381
+
382
+ function synthesisMessage(deps: WorkflowDeps, record: DebateRecord): string {
383
+ const templates = deps.getTemplates();
384
+ const parts = record.participants.flatMap((participant) => {
385
+ const latest = [...participant.rounds].reverse().find((entry) => entry.status === "completed");
386
+ if (!latest) return [];
387
+ const state = participant.active ? "" : ` · dropped after round ${participant.droppedAfterRound}`;
388
+ return [
389
+ {
390
+ title: `${participant.label} (${participant.description}) · round ${latest.round} · confidence ${latest.stance?.confidence ?? "unknown"}${state}`,
391
+ text: `${latest.answer ?? ""}\n\nPosition: ${latest.stance?.position || "(no structured position)"}\nOpen disagreements: ${
392
+ latest.stance?.valid ? formatDisagreements(latest.stance.disagreements) : "unknown (no valid stance block)"
393
+ }`,
394
+ fullPath: latest.artifactsDir ? resultPath(latest.artifactsDir) : undefined,
395
+ },
396
+ ];
397
+ });
398
+ const recordLines = [
399
+ `Record: ${join(record.dir, "debate.md")} and ${join(record.dir, "debate.json")}`,
400
+ ...record.participants
401
+ .filter((participant) => !participant.active)
402
+ .map((participant) => {
403
+ const last = participant.rounds.at(-1);
404
+ return `- ${participant.label} dropped after round ${participant.droppedAfterRound}: ${last?.status} ${last?.reason ?? ""}`.trimEnd();
405
+ }),
406
+ ...record.excluded.map((entry) => `- ${entry.profile} did not take part: ${entry.reason}`),
407
+ ...record.roundChanges.map((change) =>
408
+ change.changed.length > 0
409
+ ? `- Round ${change.round} left changes in the workspace (analyze runs): ${change.changed.join(", ")}`
410
+ : `- Round ${change.round}: ${change.note}`,
411
+ ),
412
+ ].join("\n");
413
+ const vars = { title: record.title, outcome: outcomeText(record), brief: record.brief, record: recordLines };
414
+ const fixed = templates.render("debateSynthesis", { ...vars, positions: "" });
415
+ return templates.render("debateSynthesis", { ...vars, positions: fitParts(parts, fixed) });
416
+ }
417
+
418
+ function formatDisagreements(list: Disagreement[]): string {
419
+ if (list.length === 0) return "none";
420
+ return list.map((item) => `${item.with ?? "?"}: ${item.point ?? "?"}${item.evidence ? ` (${item.evidence})` : ""}`).join("; ");
421
+ }
422
+
423
+ function summary(record: DebateRecord) {
424
+ return {
425
+ id: record.id,
426
+ title: record.title,
427
+ status: record.status,
428
+ roundsRun: record.roundsRun,
429
+ dir: record.dir,
430
+ participants: record.participants.map((participant) => ({
431
+ label: participant.label,
432
+ profile: participant.profile,
433
+ active: participant.active,
434
+ lastStatus: participant.rounds.at(-1)?.status,
435
+ })),
436
+ };
437
+ }
438
+
439
+ async function writeRecord(record: DebateRecord): Promise<void> {
440
+ if (!record.dir) return;
441
+ await writeFile(join(record.dir, "debate.json"), `${JSON.stringify(record, null, 2)}\n`);
442
+ await writeFile(join(record.dir, "debate.md"), transcript(record));
443
+ }
444
+
445
+ export function transcript(record: DebateRecord): string {
446
+ const lines = [
447
+ `# Debate: ${record.title}`,
448
+ "",
449
+ `- Id: ${record.id}`,
450
+ `- Status: ${record.status}`,
451
+ `- Started: ${record.startedAt}${record.endedAt ? ` · ended ${record.endedAt}` : ""}`,
452
+ `- Rounds run: ${record.roundsRun} of ${record.maxRounds + 1}`,
453
+ "",
454
+ "## Participants",
455
+ "",
456
+ ...record.participants.map(
457
+ (participant) =>
458
+ `- ${participant.label}: ${participant.description}${participant.active ? "" : ` (dropped after round ${participant.droppedAfterRound})`}`,
459
+ ),
460
+ ...record.excluded.map((entry) => `- excluded ${entry.profile}: ${entry.reason}`),
461
+ "",
462
+ "## Brief",
463
+ "",
464
+ record.brief || "(not written)",
465
+ ];
466
+ for (let round = 0; round < record.roundsRun; round++) {
467
+ lines.push("", `## Round ${round}${round === 0 ? " (opening)" : ""}`);
468
+ for (const participant of record.participants) {
469
+ const entry = participant.rounds.find((item) => item.round === round);
470
+ if (!entry) continue;
471
+ lines.push("", `### ${participant.label} · ${entry.status}${entry.reason ? ` · ${entry.reason}` : ""}`, "");
472
+ if (entry.answer) lines.push(entry.answer.trim());
473
+ if (entry.stance) {
474
+ lines.push(
475
+ "",
476
+ `Position: ${entry.stance.position || "(none)"}`,
477
+ `Confidence: ${entry.stance.confidence ?? "unknown"} · changed: ${entry.stance.changed} · valid stance: ${entry.stance.valid}`,
478
+ `Disagreements: ${formatDisagreements(entry.stance.disagreements)}`,
479
+ );
480
+ }
481
+ if (entry.artifactsDir) lines.push(`Artifacts: ${entry.artifactsDir}`);
482
+ }
483
+ const change = record.roundChanges.find((item) => item.round === round);
484
+ if (change) lines.push("", `Workspace changes in this round: ${change.changed.length > 0 ? change.changed.join(", ") : change.note}`);
485
+ }
486
+ if (record.error) lines.push("", `## Error`, "", record.error);
487
+ return `${lines.join("\n")}\n`;
488
+ }
@@ -0,0 +1,78 @@
1
+ import type { AgentAdapter, Detection } from "../adapters/types.ts";
2
+ import type { ResolvedProfile } from "../config/profiles.ts";
3
+ import type { OrchestratorConfig, RoleName } from "../config/schema.ts";
4
+ import type { RunRegistry } from "../engine/registry.ts";
5
+ import type { Executor } from "../engine/types.ts";
6
+ import type { Templates } from "../prompts/templates.ts";
7
+ import type { VerdictBroker } from "./verdict.ts";
8
+
9
+ export type Availability = { ok: true; detection: Detection; warnings: string[] } | { ok: false; reason: string };
10
+
11
+ /** The parts of the engine a workflow uses. */
12
+ export interface WorkflowEngine extends Executor {
13
+ readonly adapters: ReadonlyMap<string, AgentAdapter>;
14
+ resolve(name: string): ResolvedProfile | undefined;
15
+ availability(agent: string): Promise<Availability>;
16
+ }
17
+
18
+ export interface HostMessage {
19
+ customType: string;
20
+ content: string;
21
+ details?: unknown;
22
+ display?: boolean;
23
+ }
24
+
25
+ /** The pi session as a workflow sees it. Tests provide a scripted host. */
26
+ export interface WorkflowHost {
27
+ readonly workspace: string;
28
+ readonly hasUI: boolean;
29
+ /** False once the extension instance was torn down; the workflow then stops without touching pi. */
30
+ alive(): boolean;
31
+ /** Calls the moderator (pi's active model). */
32
+ complete(systemPrompt: string, prompt: string, signal: AbortSignal): Promise<string>;
33
+ /** Recent conversation text, for framing. */
34
+ conversation(): string;
35
+ editor(title: string, text: string): Promise<string | undefined>;
36
+ confirm(title: string, message: string): Promise<boolean>;
37
+ select(title: string, options: string[]): Promise<string | undefined>;
38
+ input(title: string, placeholder?: string): Promise<string | undefined>;
39
+ notify(message: string, level: "info" | "warning" | "error"): void;
40
+ /** Adds a message to the session; with `triggerTurn` the pi agent answers it. */
41
+ sendMessage(message: HostMessage, triggerTurn: boolean): void;
42
+ appendEntry(customType: string, data: unknown): void;
43
+ /** Activates or withdraws the plan_verdict tool. */
44
+ setVerdictTool(active: boolean): void;
45
+ /** Lets the user pick profiles for a role that is not configured; undefined when cancelled or without UI. */
46
+ pickRoleProfiles(role: RoleName, multiple: boolean): Promise<string[] | undefined>;
47
+ }
48
+
49
+ export interface WorkflowDeps {
50
+ engine: WorkflowEngine;
51
+ getConfig(): OrchestratorConfig;
52
+ getTemplates(): Templates;
53
+ registry: RunRegistry;
54
+ agentDir: string;
55
+ configDirName: string;
56
+ host: WorkflowHost;
57
+ /** Owner of write locks taken by plans. */
58
+ instanceId: string;
59
+ sessionId(): string | undefined;
60
+ verdicts: VerdictBroker;
61
+ }
62
+
63
+ export class WorkflowStopped extends Error {
64
+ constructor(message = "workflow stopped") {
65
+ super(message);
66
+ this.name = "WorkflowStopped";
67
+ }
68
+ }
69
+
70
+ export const MESSAGE_TYPES = {
71
+ delegate: "master-orchestrator.delegate",
72
+ debate: "master-orchestrator.debate",
73
+ plan: "master-orchestrator.plan",
74
+ block: "master-orchestrator.block",
75
+ notice: "master-orchestrator.notice",
76
+ } as const;
77
+
78
+ export const ENTRY_TYPE = "master-orchestrator.workflow";