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,120 @@
1
+ import type { AgentAdapter, AuthStatus } from "../adapters/types.ts";
2
+ import { formatConfigErrors, type LoadedConfig } from "../config/load.ts";
3
+ import { listProfiles } from "../config/profiles.ts";
4
+ import { ROLE_NAMES, type OrchestratorConfig } from "../config/schema.ts";
5
+ import { clip } from "../adapters/common.ts";
6
+ import type { Engine } from "../engine/execute.ts";
7
+
8
+ const PROBE_TIMEOUT_MS = 20_000;
9
+
10
+ function withTimeout<T>(promise: Promise<T>, fallback: T): Promise<T> {
11
+ return new Promise((resolve) => {
12
+ const timer = setTimeout(() => resolve(fallback), PROBE_TIMEOUT_MS);
13
+ timer.unref?.();
14
+ promise.then(
15
+ (value) => {
16
+ clearTimeout(timer);
17
+ resolve(value);
18
+ },
19
+ () => {
20
+ clearTimeout(timer);
21
+ resolve(fallback);
22
+ },
23
+ );
24
+ });
25
+ }
26
+
27
+ export interface AgentReport {
28
+ id: string;
29
+ lines: string[];
30
+ available: boolean;
31
+ }
32
+
33
+ function trustLine(adapter: AgentAdapter, config: OrchestratorConfig, projectTrusted: boolean): string {
34
+ if (adapter.id === "grok") {
35
+ if (!projectTrusted) return "project rules: the pi session does not trust this project; grok applies its own trust settings";
36
+ return config.agents.grok?.persistTrust
37
+ ? "project rules: passes --trust (persists the grant in grok's configuration)"
38
+ : "project rules: grok applies its own trust settings (set agents.grok.persistTrust to pass --trust)";
39
+ }
40
+ if (!adapter.trustFlag) return "project rules: the agent decides from its own configuration";
41
+ return projectTrusted
42
+ ? `project rules: loaded (passes ${adapter.trustFlag})`
43
+ : `project rules: may be skipped (the pi session does not trust this project, ${adapter.trustFlag} is not passed)`;
44
+ }
45
+
46
+ async function agentReport(engine: Engine, adapter: AgentAdapter, config: OrchestratorConfig, cwd: string, projectTrusted: boolean): Promise<AgentReport> {
47
+ const settings = config.agents[adapter.id] ?? {};
48
+ const head = `${adapter.displayName} (${adapter.id})`;
49
+ if (settings.enabled === false) return { id: adapter.id, available: false, lines: [`○ ${head}: disabled in configuration`] };
50
+ const detection = await engine.detect(adapter.id, cwd);
51
+ if (!detection.available) {
52
+ return { id: adapter.id, available: false, lines: [`✗ ${head}: not found (${detection.error ?? `${settings.bin ?? adapter.binary} is not on PATH`})`] };
53
+ }
54
+ const version =
55
+ detection.version === undefined
56
+ ? `version unknown (tested ${adapter.testedVersions})`
57
+ : detection.inTestedRange === false
58
+ ? `${detection.version} outside the tested range ${adapter.testedVersions}${settings.allowUntestedVersion === false ? " (blocked: allowUntestedVersion is false)" : " (runs with a warning)"}`
59
+ : `${detection.version} (tested ${adapter.testedVersions})`;
60
+ const experimental =
61
+ adapter.stability !== "experimental"
62
+ ? ""
63
+ : adapter.liveChecked
64
+ ? ` (verification pass incomplete; live-checked with ${adapter.liveChecked})`
65
+ : " (adapter not yet verified against real runs)";
66
+ const lines = [`✓ ${head}: ${version} · ${adapter.stability}${experimental}`];
67
+ lines.push(` binary: ${detection.path ?? settings.bin ?? adapter.binary}`);
68
+
69
+ const env = engine.hostEnv(adapter.id, cwd);
70
+ const [auth, models] = await Promise.all([
71
+ adapter.checkAuth ? withTimeout<AuthStatus>(adapter.checkAuth(env), { state: "unknown", detail: "status check timed out" }) : Promise.resolve(undefined),
72
+ adapter.listModels ? withTimeout<string[] | undefined>(adapter.listModels(env), undefined) : Promise.resolve(undefined),
73
+ ]);
74
+ if (auth) lines.push(` auth: ${auth.state}${auth.detail ? ` (${clip(auth.detail, 160)})` : ""}`);
75
+ else lines.push(" auth: no status command; failures show up as auth_required on the first run");
76
+ if (models) {
77
+ const preview = models.slice(0, 8).join(", ");
78
+ lines.push(` models: ${models.length}${models.length > 0 ? ` (${preview}${models.length > 8 ? ", …" : ""})` : ""}`);
79
+ for (const [name, profile] of Object.entries(config.profiles)) {
80
+ if (profile.agent === adapter.id && profile.model && !models.includes(profile.model)) {
81
+ lines.push(` ⚠ profile ${name}: model "${profile.model}" is not in the agent's model list`);
82
+ }
83
+ }
84
+ } else if (adapter.listModels) lines.push(" models: the list could not be read");
85
+ lines.push(` ${trustLine(adapter, config, projectTrusted)}`);
86
+ return { id: adapter.id, available: true, lines };
87
+ }
88
+
89
+ /** `/orchestrator doctor`: what is installed and how it is configured. Starts no agent turn. */
90
+ export async function doctorReport(engine: Engine, loaded: LoadedConfig, cwd: string, projectTrusted: boolean): Promise<string> {
91
+ const config = loaded.config;
92
+ const out: string[] = ["# master-orchestrator doctor", ""];
93
+ out.push("## Configuration");
94
+ for (const source of loaded.sources) {
95
+ out.push(`- ${source.scope}: ${source.path} ${source.ignored ? `(ignored: ${source.ignored})` : source.present ? "" : "(absent)"}`.trimEnd());
96
+ }
97
+ if (loaded.errors.length > 0) {
98
+ out.push("", "Errors (delegation and workflows are disabled until they are fixed):", formatConfigErrors(loaded.errors));
99
+ }
100
+ for (const warning of loaded.warnings) out.push(`- warning: ${warning}`);
101
+
102
+ out.push("", "## Agents");
103
+ const reports = await Promise.all([...engine.adapters.values()].map((adapter) => agentReport(engine, adapter, config, cwd, projectTrusted)));
104
+ for (const report of reports) out.push(...report.lines);
105
+
106
+ const available = new Set(reports.filter((report) => report.available).map((report) => report.id));
107
+ out.push("", "## Profiles");
108
+ for (const profile of listProfiles(config, engine.adapters)) {
109
+ if (profile.implicit && !available.has(profile.agent)) continue;
110
+ const parts = [profile.agent, profile.model, profile.effort ? `effort ${profile.effort}` : undefined, profile.timeoutMinutes ? `${profile.timeoutMinutes} min` : undefined].filter(Boolean);
111
+ const mark = available.has(profile.agent) ? "" : " (agent not available)";
112
+ out.push(`- ${profile.name}: ${profile.implicit ? "agent defaults" : parts.join(", ")}${mark}`);
113
+ }
114
+ out.push("", "## Roles");
115
+ for (const role of ROLE_NAMES) {
116
+ const list = config.roles[role];
117
+ out.push(`- ${role}: ${list && list.length > 0 ? list.join(" → ") : "not configured (the command asks when it needs it)"}`);
118
+ }
119
+ return out.join("\n");
120
+ }
@@ -0,0 +1,94 @@
1
+ import type { RunStatus } from "../adapters/types.ts";
2
+ import type { ActiveRun, WorkflowEntry } from "../engine/registry.ts";
3
+ import type { RunResult } from "../engine/types.ts";
4
+ import { fitOne, resultPath } from "../workflows/budget.ts";
5
+
6
+ export function formatDuration(ms: number): string {
7
+ const seconds = Math.max(0, Math.round(ms / 1000));
8
+ if (seconds < 60) return `${seconds}s`;
9
+ const minutes = Math.floor(seconds / 60);
10
+ if (minutes < 60) return `${minutes}m${String(seconds % 60).padStart(2, "0")}s`;
11
+ return `${Math.floor(minutes / 60)}h${String(minutes % 60).padStart(2, "0")}m`;
12
+ }
13
+
14
+ export const STATUS_ICON: Record<RunStatus, string> = {
15
+ completed: "✓",
16
+ failed: "✗",
17
+ denied: "⊘",
18
+ quota: "$",
19
+ auth_required: "🔑",
20
+ unavailable: "∅",
21
+ timeout: "⏱",
22
+ cancelled: "■",
23
+ };
24
+
25
+ /** One line per workflow header and active run, for the widget above the editor. */
26
+ export function widgetLines(runs: readonly ActiveRun[], workflows: readonly WorkflowEntry[], now = Date.now()): string[] {
27
+ const lines: string[] = [];
28
+ for (const workflow of workflows) lines.push(`◆ ${workflow.header}`);
29
+ for (const run of runs) {
30
+ const parts = [`${run.mode === "implement" ? "✎" : "⌕"} ${run.profile}`];
31
+ if (run.label) parts.push(run.label);
32
+ parts.push(formatDuration(now - run.startedAt));
33
+ if (run.lastActivity) parts.push(run.lastActivity);
34
+ lines.push(` ${parts.join(" · ")}`);
35
+ }
36
+ return lines;
37
+ }
38
+
39
+ export function statusText(runs: readonly ActiveRun[]): string | undefined {
40
+ if (runs.length === 0) return undefined;
41
+ return `⚙ ${runs.length} run${runs.length === 1 ? "" : "s"}`;
42
+ }
43
+
44
+ function list(title: string, items: readonly string[]): string[] {
45
+ return items.length > 0 ? [`${title}:`, ...items.map((item) => `- ${item}`)] : [];
46
+ }
47
+
48
+ /** The text the pi model receives for a run (within the 50 KB / 2000 lines budget). */
49
+ export function formatRunResult(result: RunResult): string {
50
+ const header = [
51
+ `Run ${result.runId}: ${result.status}${result.reason ? ` (${result.reason})` : ""}`,
52
+ `Profile: ${result.profile} · agent ${result.agent}${result.model ? ` · model ${result.model}` : ""} · ${result.mode} · ${formatDuration(result.durationMs)}`,
53
+ ];
54
+ if (result.attempts.length > 0) {
55
+ header.push(`Fallback: ${result.attempts.map((attempt) => `${attempt.profile} ${attempt.status}${attempt.reason ? ` (${attempt.reason})` : ""}`).join(" → ")} → ${result.profile}`);
56
+ }
57
+ const facts = [
58
+ ...list("Changed files", result.changedFiles),
59
+ ...list("Unexpected changes (an analyze run left these changes in the workspace)", result.unexpectedChanges),
60
+ ...list("Out-of-scope changes", result.outOfScopeChanges),
61
+ ...list("Git policy departures", result.gitPolicyDepartures),
62
+ ...list("Denied actions", result.deniedActions),
63
+ ...list("Warnings", result.warnings),
64
+ result.changeNote,
65
+ result.usage ? `Usage: ${formatUsage(result.usage)}` : "",
66
+ `Artifacts: ${result.artifactsDir}`,
67
+ result.resumable ? `Follow-up: pass followUpRunId "${result.runId}" to continue this session.` : "",
68
+ ].filter(Boolean);
69
+ const answer = result.finalText?.trim() ? result.finalText.trim() : "(no final answer)";
70
+ const fixed = `${header.join("\n")}\n\n## Final answer\n\n\n\n${facts.join("\n")}`;
71
+ const budgetBytes = 50 * 1024 - Buffer.byteLength(fixed, "utf8");
72
+ const budgetLines = 2000 - fixed.split("\n").length;
73
+ return `${header.join("\n")}\n\n## Final answer\n\n${fitOne(answer, resultPath(result.artifactsDir), Math.max(2048, budgetBytes), Math.max(50, budgetLines))}\n\n${facts.join("\n")}`;
74
+ }
75
+
76
+ export function formatUsage(usage: NonNullable<RunResult["usage"]>): string {
77
+ const parts: string[] = [];
78
+ if (usage.inputTokens !== undefined) parts.push(`${usage.inputTokens} in`);
79
+ if (usage.outputTokens !== undefined) parts.push(`${usage.outputTokens} out`);
80
+ if (usage.turns !== undefined) parts.push(`${usage.turns} turn${usage.turns === 1 ? "" : "s"}`);
81
+ if (usage.costUsd !== undefined) parts.push(`$${usage.costUsd.toFixed(4)}`);
82
+ return parts.join(", ") || "reported without totals";
83
+ }
84
+
85
+ /** One-line summary of a run, for collapsed views. */
86
+ export function runSummaryLine(result: RunResult): string {
87
+ const changes = result.changedFiles.length;
88
+ const flags = [
89
+ result.unexpectedChanges.length > 0 ? `${result.unexpectedChanges.length} unexpected` : "",
90
+ result.outOfScopeChanges.length > 0 ? `${result.outOfScopeChanges.length} out of scope` : "",
91
+ result.deniedActions.length > 0 ? `${result.deniedActions.length} denied` : "",
92
+ ].filter(Boolean);
93
+ return `${STATUS_ICON[result.status] ?? "?"} ${result.status} · ${result.profile} · ${formatDuration(result.durationMs)} · ${changes} file${changes === 1 ? "" : "s"} changed${flags.length > 0 ? ` · ${flags.join(", ")}` : ""}`;
94
+ }
package/src/ui/host.ts ADDED
@@ -0,0 +1,100 @@
1
+ import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { RoleName } from "../config/schema.ts";
3
+ import type { HostMessage, WorkflowHost } from "../workflows/host.ts";
4
+
5
+ const CONVERSATION_BYTES = 24 * 1024;
6
+ const CONVERSATION_ENTRIES = 16;
7
+
8
+ /** What the pi host needs from the live extension instance. */
9
+ export interface HostRuntime {
10
+ /** The context of the current session; replaced on every `session_start`. */
11
+ ctx(): ExtensionContext;
12
+ alive(): boolean;
13
+ pickRoleProfiles(role: RoleName, multiple: boolean): Promise<string[] | undefined>;
14
+ }
15
+
16
+ export const VERDICT_TOOL = "plan_verdict";
17
+
18
+ function textOf(content: unknown): string {
19
+ if (typeof content === "string") return content;
20
+ if (!Array.isArray(content)) return "";
21
+ return content
22
+ .flatMap((part) => (part && typeof part === "object" && (part as { type?: string }).type === "text" ? [(part as { text: string }).text] : []))
23
+ .join("\n");
24
+ }
25
+
26
+ /** The last user and assistant texts of the current branch, newest last, within a byte budget. */
27
+ export function recentConversation(ctx: ExtensionContext): string {
28
+ const parts: string[] = [];
29
+ let bytes = 0;
30
+ const branch = ctx.sessionManager.getBranch();
31
+ for (let index = branch.length - 1; index >= 0 && parts.length < CONVERSATION_ENTRIES; index--) {
32
+ const entry = branch[index] as { type: string; message?: { role?: string; content?: unknown } };
33
+ if (entry.type !== "message" || !entry.message) continue;
34
+ const role = entry.message.role;
35
+ if (role !== "user" && role !== "assistant") continue;
36
+ const text = textOf(entry.message.content).trim();
37
+ if (!text) continue;
38
+ const block = `[${role}]\n${text}`;
39
+ bytes += Buffer.byteLength(block, "utf8");
40
+ if (bytes > CONVERSATION_BYTES) break;
41
+ parts.unshift(block);
42
+ }
43
+ return parts.join("\n\n");
44
+ }
45
+
46
+ /** Calls pi's active model with one user message and returns its text. */
47
+ export async function completeWithModel(ctx: ExtensionContext, systemPrompt: string, prompt: string, signal?: AbortSignal): Promise<string> {
48
+ const model = ctx.model;
49
+ if (!model) throw new Error("No model is selected in pi.");
50
+ const response = await ctx.modelRegistry.complete(
51
+ model,
52
+ { systemPrompt, messages: [{ role: "user", content: [{ type: "text", text: prompt }], timestamp: Date.now() }] },
53
+ { signal },
54
+ );
55
+ if (response.stopReason === "aborted") throw new Error("aborted");
56
+ if (response.stopReason === "error") throw new Error(response.errorMessage ?? "the model call failed");
57
+ return response.content.flatMap((block) => (block.type === "text" ? [block.text] : [])).join("\n");
58
+ }
59
+
60
+ /** Activates or withdraws a tool without touching the rest of the active set. */
61
+ export function setToolActive(pi: ExtensionAPI, name: string, active: boolean): void {
62
+ const current = pi.getActiveTools();
63
+ const has = current.includes(name);
64
+ if (active && !has) pi.setActiveTools([...current, name]);
65
+ else if (!active && has) pi.setActiveTools(current.filter((tool) => tool !== name));
66
+ }
67
+
68
+ /** Sends a custom message; a message that asks for a turn waits for the current one to finish. */
69
+ export function sendHostMessage(pi: ExtensionAPI, message: HostMessage, triggerTurn: boolean): void {
70
+ pi.sendMessage(
71
+ { customType: message.customType, content: message.content, display: message.display ?? true, details: message.details },
72
+ triggerTurn ? { triggerTurn: true, deliverAs: "followUp" } : undefined,
73
+ );
74
+ }
75
+
76
+ /** The pi session as a workflow sees it. The workspace is fixed when the workflow starts. */
77
+ export function createPiHost(pi: ExtensionAPI, runtime: HostRuntime, workspace: string): WorkflowHost {
78
+ return {
79
+ workspace,
80
+ get hasUI() {
81
+ return runtime.ctx().hasUI;
82
+ },
83
+ alive: () => runtime.alive(),
84
+ complete: (systemPrompt, prompt, signal) => completeWithModel(runtime.ctx(), systemPrompt, prompt, signal),
85
+ conversation: () => recentConversation(runtime.ctx()),
86
+ editor: (title, text) => runtime.ctx().ui.editor(title, text),
87
+ confirm: (title, message) => runtime.ctx().ui.confirm(title, message),
88
+ select: (title, options) => runtime.ctx().ui.select(title, options),
89
+ input: (title, placeholder) => runtime.ctx().ui.input(title, placeholder),
90
+ notify(message, level) {
91
+ const ctx = runtime.ctx();
92
+ if (ctx.hasUI) ctx.ui.notify(message, level);
93
+ else process.stderr.write(`[master-orchestrator] ${message}\n`);
94
+ },
95
+ sendMessage: (message, triggerTurn) => sendHostMessage(pi, message, triggerTurn),
96
+ appendEntry: (customType, data) => pi.appendEntry(customType, data),
97
+ setVerdictTool: (active) => setToolActive(pi, VERDICT_TOOL, active),
98
+ pickRoleProfiles: (role, multiple) => runtime.pickRoleProfiles(role, multiple),
99
+ };
100
+ }
@@ -0,0 +1,86 @@
1
+ import { getMarkdownTheme, type Theme } from "@earendil-works/pi-coding-agent";
2
+ import { Container, Markdown, Text } from "@earendil-works/pi-tui";
3
+ import type { RunResult } from "../engine/types.ts";
4
+ import { formatDuration, formatUsage, runSummaryLine, STATUS_ICON } from "./format.ts";
5
+
6
+ export interface DelegateArgs {
7
+ task?: string;
8
+ profile?: string;
9
+ role?: string;
10
+ mode?: string;
11
+ scope?: string[];
12
+ followUpRunId?: string;
13
+ }
14
+
15
+ /** Tool details: the run result, or the progress of a run that is still going. */
16
+ export type DelegateDetails = RunResult | { progress: { runId?: string; profile?: string; elapsedMs: number; lastActivity?: string } } | undefined;
17
+
18
+ function isRunResult(details: DelegateDetails): details is RunResult {
19
+ return Boolean(details && "runId" in details && "status" in details);
20
+ }
21
+
22
+ export function renderDelegateCall(args: DelegateArgs, theme: Theme): Text {
23
+ const target = args.profile ?? (args.role ? `role ${args.role}` : "default");
24
+ const mode = args.mode ?? "analyze";
25
+ const firstLine = (args.task ?? "").split("\n").find((line) => line.trim())?.trim() ?? "";
26
+ const task = firstLine.length > 80 ? `${firstLine.slice(0, 79)}…` : firstLine;
27
+ let text = `${theme.fg("toolTitle", theme.bold("delegate "))}${theme.fg("accent", target)} ${theme.fg("muted", mode)}`;
28
+ if (args.followUpRunId) text += theme.fg("dim", ` follow-up ${args.followUpRunId}`);
29
+ if (task) text += `\n${theme.fg("dim", task)}`;
30
+ return new Text(text, 0, 0);
31
+ }
32
+
33
+ export function renderDelegateResult(
34
+ details: DelegateDetails,
35
+ options: { expanded: boolean; isPartial: boolean },
36
+ theme: Theme,
37
+ expandHint: string,
38
+ ): Container | Text {
39
+ if (!isRunResult(details)) {
40
+ const progress = details && "progress" in details ? details.progress : undefined;
41
+ const parts = [progress?.profile, progress ? formatDuration(progress.elapsedMs) : undefined, progress?.lastActivity].filter(Boolean);
42
+ return new Text(theme.fg("warning", `⚙ running${parts.length > 0 ? ` · ${parts.join(" · ")}` : ""}`), 0, 0);
43
+ }
44
+ const color = details.status === "completed" ? "success" : details.status === "cancelled" ? "muted" : "error";
45
+ const summary = theme.fg(color, runSummaryLine(details));
46
+ if (!options.expanded) return new Text(`${summary} ${theme.fg("dim", `(${expandHint})`)}`, 0, 0);
47
+
48
+ const container = new Container();
49
+ container.addChild(new Text(summary, 0, 0));
50
+ if (details.reason) container.addChild(new Text(theme.fg("muted", details.reason), 0, 0));
51
+ const answer = details.finalText?.trim();
52
+ if (answer) container.addChild(new Markdown(answer, 0, 1, getMarkdownTheme()));
53
+ const section = (title: string, items: string[], tone: "warning" | "error" | "muted") => {
54
+ if (items.length === 0) return;
55
+ container.addChild(new Text(`${theme.fg(tone, `${title}:`)}\n${items.map((item) => ` ${item}`).join("\n")}`, 0, 0));
56
+ };
57
+ section("Changed files", details.changedFiles, "muted");
58
+ section("Unexpected changes", details.unexpectedChanges, "warning");
59
+ section("Out of scope", details.outOfScopeChanges, "warning");
60
+ section("Git policy departures", details.gitPolicyDepartures, "warning");
61
+ section("Denied", details.deniedActions, "error");
62
+ section("Warnings", details.warnings, "warning");
63
+ const footer = [details.usage ? `usage ${formatUsage(details.usage)}` : "", `artifacts ${details.artifactsDir}`].filter(Boolean).join(" · ");
64
+ container.addChild(new Text(theme.fg("dim", footer), 0, 0));
65
+ return container;
66
+ }
67
+
68
+ /** Workflow messages: a one-line header when collapsed, the Markdown body when expanded. */
69
+ export function renderWorkflowMessage(
70
+ kind: string,
71
+ content: string,
72
+ details: unknown,
73
+ options: { expanded: boolean; outputPad: number },
74
+ theme: Theme,
75
+ expandHint: string,
76
+ ): Container | Text {
77
+ const firstLine = content.split("\n").find((line) => line.trim())?.replace(/^#+\s*/, "").trim() ?? kind;
78
+ const status = (details as { status?: string } | undefined)?.status;
79
+ const icon = status && status in STATUS_ICON ? STATUS_ICON[status as keyof typeof STATUS_ICON] : "◆";
80
+ const header = `${theme.fg("accent", theme.bold(`${icon} ${kind}`))} ${firstLine}`;
81
+ if (!options.expanded) return new Text(`${header} ${theme.fg("dim", `(${expandHint})`)}`, options.outputPad, 0);
82
+ const container = new Container();
83
+ container.addChild(new Text(header, options.outputPad, 0));
84
+ container.addChild(new Markdown(content, options.outputPad, 1, getMarkdownTheme()));
85
+ return container;
86
+ }
@@ -0,0 +1,70 @@
1
+ import type { ExtensionContext } from "@earendil-works/pi-coding-agent";
2
+ import type { RunRegistry } from "../engine/registry.ts";
3
+ import { statusText, widgetLines } from "./format.ts";
4
+
5
+ const KEY = "master-orchestrator";
6
+ const TICK_MS = 1_000;
7
+
8
+ /** Keeps the widget above the editor and the footer status in step with the registry. */
9
+ export class WidgetController {
10
+ private readonly registry: RunRegistry;
11
+ private readonly ctx: () => ExtensionContext | undefined;
12
+ private timer: NodeJS.Timeout | undefined;
13
+ private unsubscribe: (() => void) | undefined;
14
+ private shown = false;
15
+
16
+ constructor(registry: RunRegistry, ctx: () => ExtensionContext | undefined) {
17
+ this.registry = registry;
18
+ this.ctx = ctx;
19
+ }
20
+
21
+ start(): void {
22
+ this.unsubscribe = this.registry.onChange(() => this.refresh());
23
+ this.refresh();
24
+ }
25
+
26
+ refresh(): void {
27
+ const ctx = this.ctx();
28
+ if (!ctx?.hasUI) return;
29
+ const runs = this.registry.list();
30
+ const workflows = this.registry.listWorkflows();
31
+ const active = runs.length > 0 || workflows.length > 0;
32
+ try {
33
+ if (active) {
34
+ ctx.ui.setWidget(KEY, widgetLines(runs, workflows));
35
+ ctx.ui.setStatus(KEY, statusText(runs) ?? `◆ ${workflows.length} workflow${workflows.length === 1 ? "" : "s"}`);
36
+ this.shown = true;
37
+ } else if (this.shown) {
38
+ ctx.ui.setWidget(KEY, undefined);
39
+ ctx.ui.setStatus(KEY, undefined);
40
+ this.shown = false;
41
+ }
42
+ } catch {
43
+ // The session was replaced; the next instance draws its own widget.
44
+ }
45
+ if (active && !this.timer) {
46
+ this.timer = setInterval(() => this.refresh(), TICK_MS);
47
+ this.timer.unref?.();
48
+ } else if (!active && this.timer) {
49
+ clearInterval(this.timer);
50
+ this.timer = undefined;
51
+ }
52
+ }
53
+
54
+ stop(): void {
55
+ this.unsubscribe?.();
56
+ this.unsubscribe = undefined;
57
+ if (this.timer) clearInterval(this.timer);
58
+ this.timer = undefined;
59
+ const ctx = this.ctx();
60
+ if (this.shown && ctx?.hasUI) {
61
+ try {
62
+ ctx.ui.setWidget(KEY, undefined);
63
+ ctx.ui.setStatus(KEY, undefined);
64
+ } catch {
65
+ // Already torn down.
66
+ }
67
+ }
68
+ this.shown = false;
69
+ }
70
+ }
@@ -0,0 +1,66 @@
1
+ import { join } from "node:path";
2
+
3
+ export const MAX_BYTES = 50 * 1024;
4
+ export const MAX_LINES = 2000;
5
+
6
+ export interface BudgetPart {
7
+ /** Heading printed before the part. */
8
+ title: string;
9
+ text: string;
10
+ /** Where the full text lives, listed when the part is cut. */
11
+ fullPath?: string;
12
+ }
13
+
14
+ /**
15
+ * Cuts `text` to at most `maxBytes` and `maxLines`, keeping the end (the conclusion).
16
+ * Returns the text and whether it was cut.
17
+ */
18
+ export function keepTail(text: string, maxBytes: number, maxLines: number): { text: string; cut: boolean } {
19
+ const lines = text.split("\n");
20
+ let bytes = 0;
21
+ let start = lines.length;
22
+ while (start > 0) {
23
+ const size = Buffer.byteLength(lines[start - 1], "utf8") + 1;
24
+ if (lines.length - start + 1 > maxLines || bytes + size > maxBytes) break;
25
+ bytes += size;
26
+ start--;
27
+ }
28
+ if (start === 0) return { text, cut: false };
29
+ if (start === lines.length) {
30
+ // A single line longer than the budget: keep its last bytes.
31
+ const last = Buffer.from(lines.at(-1) ?? "", "utf8");
32
+ return { text: last.subarray(Math.max(0, last.length - maxBytes)).toString("utf8"), cut: true };
33
+ }
34
+ return { text: lines.slice(start).join("\n"), cut: true };
35
+ }
36
+
37
+ /** Same cut for one result returned to the model. */
38
+ export function fitOne(text: string, fullPath?: string, maxBytes = MAX_BYTES, maxLines = MAX_LINES): string {
39
+ const reserve = fullPath ? 2 : 0;
40
+ const { text: kept, cut } = keepTail(text, maxBytes - 300, maxLines - reserve);
41
+ if (!cut) return text;
42
+ return `[Earlier part omitted to fit the output limit${fullPath ? `; full text: ${fullPath}` : ""}]\n\n${kept}`;
43
+ }
44
+
45
+ /**
46
+ * Joins several results into one message within the budget: the budget left after the fixed text is divided among
47
+ * the parts, each part is cut to its share from the end backwards, and the path of every full result is listed.
48
+ */
49
+ export function fitParts(parts: BudgetPart[], fixed = "", maxBytes = MAX_BYTES, maxLines = MAX_LINES): string {
50
+ if (parts.length === 0) return "";
51
+ const overheadBytes = Buffer.byteLength(fixed, "utf8") + parts.length * 400;
52
+ const overheadLines = fixed.split("\n").length + parts.length * 6;
53
+ const shareBytes = Math.max(512, Math.floor((maxBytes - overheadBytes) / parts.length));
54
+ const shareLines = Math.max(10, Math.floor((maxLines - overheadLines) / parts.length));
55
+ const rendered = parts.map((part) => {
56
+ const { text, cut } = keepTail(part.text.trim(), shareBytes, shareLines);
57
+ const note = cut ? `[Earlier part omitted to fit the message limit${part.fullPath ? `; full text: ${part.fullPath}` : ""}]\n\n` : "";
58
+ const path = part.fullPath ? `\n\nFull result: ${part.fullPath}` : "";
59
+ return `### ${part.title}\n\n${note}${text || "(empty)"}${path}`;
60
+ });
61
+ return rendered.join("\n\n");
62
+ }
63
+
64
+ export function resultPath(artifactsDir: string): string {
65
+ return join(artifactsDir, "result.md");
66
+ }
@@ -0,0 +1,100 @@
1
+ import { describeProfile, roleProfiles } from "../config/profiles.ts";
2
+ import type { RoleName } from "../config/schema.ts";
3
+ import { WorkflowStopped, type WorkflowDeps } from "./host.ts";
4
+
5
+ /** Parses the last fenced JSON block of a text (or the whole text when it is JSON). */
6
+ export function lastJsonBlock(text: string | undefined): unknown {
7
+ if (!text) return undefined;
8
+ const blocks = [...text.matchAll(/```(?:json)?[ \t]*\n([\s\S]*?)\n[ \t]*```/g)].map((match) => match[1]);
9
+ for (const candidate of blocks.reverse()) {
10
+ try {
11
+ return JSON.parse(candidate);
12
+ } catch {
13
+ // Try the previous block.
14
+ }
15
+ }
16
+ try {
17
+ return JSON.parse(text.trim());
18
+ } catch {
19
+ return undefined;
20
+ }
21
+ }
22
+
23
+ /** Text before the last fenced JSON block. */
24
+ export function withoutTrailingJson(text: string): string {
25
+ return text.replace(/\n*```json[ \t]*\n[\s\S]*?\n[ \t]*```\s*$/i, "").trimEnd();
26
+ }
27
+
28
+ /** Profiles of a role; asks the user when the role is not configured. */
29
+ export async function resolveRole(deps: WorkflowDeps, role: RoleName, multiple: boolean): Promise<string[]> {
30
+ const configured = roleProfiles(deps.getConfig(), role);
31
+ if (configured) return configured;
32
+ const picked = deps.host.hasUI ? await deps.host.pickRoleProfiles(role, multiple) : undefined;
33
+ if (!picked || picked.length === 0) {
34
+ throw new Error(`The role "${role}" is not configured. Add roles.${role} to master-orchestrator.json or run /orchestrator config.`);
35
+ }
36
+ return picked;
37
+ }
38
+
39
+ export function profileLabel(deps: WorkflowDeps, name: string): string {
40
+ const profile = deps.engine.resolve(name);
41
+ return profile ? describeProfile(profile) : `${name} (unknown profile)`;
42
+ }
43
+
44
+ /** The moderator writes a self-contained brief; the user reviews it. Undefined when the user cancels. */
45
+ export async function frameBrief(
46
+ deps: WorkflowDeps,
47
+ request: string,
48
+ audience: string,
49
+ title: string,
50
+ signal: AbortSignal,
51
+ ): Promise<string | undefined> {
52
+ const templates = deps.getTemplates();
53
+ const prompt = templates.render("framing", {
54
+ audience,
55
+ workspace: deps.host.workspace,
56
+ request,
57
+ conversation: deps.host.conversation() || "(none)",
58
+ });
59
+ let brief: string;
60
+ try {
61
+ brief = (await deps.host.complete(templates.get("framingSystem"), prompt, signal)).trim();
62
+ } catch (error) {
63
+ if (signal.aborted) throw new WorkflowStopped("cancelled");
64
+ throw new Error(`The moderator could not write the brief: ${(error as Error).message}`);
65
+ }
66
+ ensureAlive(deps);
67
+ if (!brief) brief = request;
68
+ if (!deps.host.hasUI) return brief;
69
+ const edited = await deps.host.editor(`${title}: review the brief (save to continue, empty to cancel)`, brief);
70
+ ensureAlive(deps);
71
+ return edited?.trim() ? edited.trim() : undefined;
72
+ }
73
+
74
+ /** The cost gate: true to continue. Without UI and with `workflowStart: "ask"` it refuses. */
75
+ export async function costGate(deps: WorkflowDeps, title: string, lines: string[]): Promise<boolean> {
76
+ if (deps.getConfig().approval.workflowStart === "auto") return true;
77
+ if (!deps.host.hasUI) {
78
+ throw new Error(`${title} needs a confirmation and there is no UI. Set approval.workflowStart to "auto" to start without one.`);
79
+ }
80
+ const confirmed = await deps.host.confirm(title, lines.join("\n"));
81
+ ensureAlive(deps);
82
+ return confirmed;
83
+ }
84
+
85
+ export function ensureAlive(deps: WorkflowDeps): void {
86
+ if (!deps.host.alive()) throw new WorkflowStopped("extension instance replaced");
87
+ }
88
+
89
+ export function errorText(error: unknown): string {
90
+ return error instanceof Error ? error.message : String(error);
91
+ }
92
+
93
+ export function titleOf(text: string, max = 60): string {
94
+ const line = text.split("\n").find((entry) => entry.trim())?.trim() ?? "untitled";
95
+ return line.length > max ? `${line.slice(0, max - 1)}…` : line;
96
+ }
97
+
98
+ export function formatList(items: string[], empty = "(none)"): string {
99
+ return items.length > 0 ? items.map((item) => `- ${item}`).join("\n") : empty;
100
+ }