@loka1/pi-orchestra 0.0.0-stage → 0.5.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.
@@ -0,0 +1,115 @@
1
+ /**
2
+ * `/orchestra` argument completion.
3
+ *
4
+ * Lives here rather than in the extension so the command table is one list that
5
+ * the help text, the completer and the tests all read.
6
+ */
7
+
8
+ import type { AutocompleteItem } from "@earendil-works/pi-tui";
9
+ import { fit } from "./format.ts";
10
+ import { shortId } from "./format.ts";
11
+ import type { OrchestraState } from "./types.ts";
12
+
13
+ export interface OrchestraCommand {
14
+ name: string;
15
+ description: string;
16
+ /** What the argument is, so the completer knows what to suggest. */
17
+ takes: "none" | "dispatch" | "task" | "run" | "either" | "template" | "free";
18
+ }
19
+
20
+ export const ORCHESTRA_COMMANDS: OrchestraCommand[] = [
21
+ { name: "browse", description: "Interactive list of tasks, workers and runs", takes: "free" },
22
+ { name: "join", description: "Open a worker's conversation and type into it", takes: "dispatch" },
23
+ { name: "chat", description: "The same conversation as text", takes: "dispatch" },
24
+ { name: "open", description: "Detail of one task, worker or run", takes: "either" },
25
+ { name: "status", description: "Run summary, tasks and workers", takes: "none" },
26
+ { name: "tasks", description: "Task table for the active run", takes: "none" },
27
+ { name: "workers", description: "Worker table for the active run", takes: "none" },
28
+ { name: "read", description: "Worker transcript (tail)", takes: "dispatch" },
29
+ { name: "watch", description: "Pin a worker's transcript into the widget", takes: "dispatch" },
30
+ { name: "unwatch", description: "Unpin the transcript", takes: "none" },
31
+ { name: "stop", description: "Stop a worker", takes: "dispatch" },
32
+ { name: "retry", description: "Repair dispatch seeded with the failure", takes: "dispatch" },
33
+ { name: "resume", description: "Continue a worker in its own session", takes: "dispatch" },
34
+ { name: "diff", description: "git diff since that worker started", takes: "dispatch" },
35
+ { name: "find", description: "Filter tasks, workers and runs", takes: "free" },
36
+ { name: "grep", description: "Search every worker transcript", takes: "free" },
37
+ { name: "runs", description: "List runs, newest first", takes: "none" },
38
+ { name: "use", description: "Make a run the active one", takes: "run" },
39
+ { name: "templates", description: "List run templates", takes: "none" },
40
+ { name: "template", description: "Start a run from a template", takes: "template" },
41
+ { name: "broadcast", description: "Message every live worker", takes: "free" },
42
+ { name: "metrics", description: "Cost and turns for the active run", takes: "none" },
43
+ { name: "report", description: "Write exports/<runId>.md", takes: "none" },
44
+ { name: "export", description: "Export the run as JSONL or JSON", takes: "free" },
45
+ { name: "budget", description: "Lift a pause and set the run budget", takes: "free" },
46
+ { name: "prune", description: "Delete old runs, logs and archives", takes: "free" },
47
+ { name: "archive", description: "Archive finished runs", takes: "free" },
48
+ { name: "questions", description: "Pending gates", takes: "none" },
49
+ { name: "config", description: "Show the resolved configuration", takes: "none" },
50
+ { name: "back", description: "Return to the coordinator session", takes: "none" },
51
+ ];
52
+
53
+
54
+ export interface CompletionContext {
55
+ state?: OrchestraState;
56
+ templates?: Array<{ name: string; tasks: number }>;
57
+ }
58
+
59
+ /** Tab-completion for `/orchestra …`: commands, then live ids for the argument. */
60
+ export function completeOrchestraArgument(prefix: string, context: CompletionContext = {}): AutocompleteItem[] | null {
61
+ const match = /^(\S*)(?:\s+(.*))?$/.exec(prefix);
62
+ const head = match?.[1] ?? "";
63
+ const rest = match?.[2];
64
+
65
+ if (rest === undefined) {
66
+ const items = ORCHESTRA_COMMANDS.filter((command) => command.name.startsWith(head)).map((command) => ({
67
+ value: command.name,
68
+ label: command.name,
69
+ description: command.description,
70
+ }));
71
+ return items.length > 0 ? items : null;
72
+ }
73
+
74
+ const command = ORCHESTRA_COMMANDS.find((entry) => entry.name === head);
75
+ if (!command || command.takes === "none" || command.takes === "free") return null;
76
+ const state = context.state;
77
+ if (!state && command.takes !== "template") return null;
78
+
79
+ const partial = rest.trim().toLowerCase();
80
+ const items: AutocompleteItem[] = [];
81
+ const add = (id: string, label: string, description: string) => {
82
+ // Match the id, the status/model part of the label and the title, so both
83
+ // "dispatch_9c4e" and "port" find the same row.
84
+ const haystack = `${id} ${label} ${description}`.toLowerCase();
85
+ if (partial && !haystack.includes(partial)) return;
86
+ items.push({ value: id, label, description });
87
+ };
88
+
89
+ if (state && (command.takes === "dispatch" || command.takes === "either")) {
90
+ for (const dispatch of Object.values(state.dispatches)) {
91
+ const task = dispatch.taskId ? state.tasks[dispatch.taskId] : undefined;
92
+ add(
93
+ dispatch.id,
94
+ `${shortId(dispatch.id)} ${dispatch.agent} ${dispatch.status}`,
95
+ task?.title ?? fit(dispatch.spec.split("\n")[0] ?? "", 60),
96
+ );
97
+ }
98
+ }
99
+ if (state && (command.takes === "task" || command.takes === "either")) {
100
+ for (const task of Object.values(state.tasks)) {
101
+ add(task.id, `${shortId(task.id)} ${task.status}`, task.title);
102
+ }
103
+ }
104
+ if (state && command.takes === "run") {
105
+ for (const run of Object.values(state.runs)) {
106
+ add(run.id, `${shortId(run.id)} ${run.status}`, run.name ?? run.goal ?? "");
107
+ }
108
+ }
109
+ if (command.takes === "template") {
110
+ for (const template of context.templates ?? []) {
111
+ add(template.name, template.name, `${template.tasks} task(s)`);
112
+ }
113
+ }
114
+ return items.length > 0 ? items : null;
115
+ }
@@ -0,0 +1,219 @@
1
+ /**
2
+ * Configuration loading.
3
+ *
4
+ * Merge order (later wins):
5
+ * 1. built-in defaults
6
+ * 2. ~/.pi/agent/orchestra.json (global)
7
+ * 3. <project>/.pi/orchestra.json (project-local)
8
+ */
9
+
10
+ import { existsSync, readFileSync } from "node:fs";
11
+ import { homedir } from "node:os";
12
+ import { join, resolve } from "node:path";
13
+
14
+ export type SessionMode = "no-session" | "session";
15
+
16
+ export interface AgentOverride {
17
+ model?: string;
18
+ /** Provider that serves `model`, when the bare id is ambiguous. */
19
+ provider?: string;
20
+ thinking?: string;
21
+ tools?: string[];
22
+ }
23
+
24
+ export interface OrchestraConfig {
25
+ /** Maximum number of concurrently running workers. */
26
+ maxConcurrency: number;
27
+ /** Agent used when a dispatch does not name one. */
28
+ defaultAgent: string;
29
+ /** Let workers inherit the coordinator's model/thinking when the agent has none. */
30
+ inheritModel: boolean;
31
+ /** Hard limit for one worker before it is stopped (0 = no limit). */
32
+ timeoutMs: number;
33
+ /**
34
+ * How `timeoutMs` is measured: "total" from spawn (default), or "idle" — the
35
+ * timer restarts on every worker event, so only silence that long stops it.
36
+ */
37
+ timeoutMode: "total" | "idle";
38
+ /** Keep a settled worker's process alive so the user can keep chatting with it. */
39
+ keepOpen: boolean;
40
+ /** Wake the coordinator when a worker settles. */
41
+ notifyOnSettle: boolean;
42
+ /** Override the pi executable used to spawn workers. */
43
+ workerCommand?: string;
44
+ /** Where state, logs and mail live. Defaults to <cwd>/.pi/orchestra. */
45
+ stateDir?: string;
46
+ /** Give workers a persistent session so they can be resumed with `pi --resume`. */
47
+ sessionMode: SessionMode;
48
+ /**
49
+ * Start workers with `--no-extensions` plus this extension only. Keeps workers free of
50
+ * MCP servers, interactive gates and other extensions the coordinator has loaded.
51
+ */
52
+ workerIsolation: boolean;
53
+ /** Default cost ceiling per worker in USD (0 = off). */
54
+ budgetUsdPerWorker: number;
55
+ /** Cost ceiling for a whole run in USD; once reached, no new workers start (0 = off). */
56
+ budgetUsdPerRun: number;
57
+ /**
58
+ * What to do when a ceiling is reached: "stop" kills the workers, "ask" only
59
+ * pauses the run and waits for `orchestra action=budget usd=<n>`.
60
+ */
61
+ budgetAction: "stop" | "ask";
62
+ /** Wall-clock ceiling per worker: wrap up, then stop (0 = off, `timeoutMs` still applies). */
63
+ budgetMsPerWorker: number;
64
+ /** Extra attempts after a failed worker (0 = off). */
65
+ retries: number;
66
+ /** Delay before the first retry; doubles per attempt, capped at 5 minutes. */
67
+ retryBackoffMs: number;
68
+ /** Grace before a worker that exceeded `budgetMsPerWorker` is stopped. */
69
+ budgetGraceMs: number;
70
+ /** Silence (no events) before a worker is flagged as stalled; 0 = off. */
71
+ stallMs: number;
72
+ /** What to do about a stalled worker. */
73
+ stallAction: "notify" | "abort";
74
+ /** Maximum rows in the always-on widget (hint row excluded). */
75
+ widgetMaxLines: number;
76
+ /** Show settled/done rows in the widget instead of collapsing them into a counter. */
77
+ widgetShowSettled: boolean;
78
+ /**
79
+ * Extra extension files (or `npm:`/`git:` package specs) an isolated worker
80
+ * should load — typically a provider package. Discovered automatically when
81
+ * possible; this list is for the rest.
82
+ */
83
+ providerExtensions: string[];
84
+ /** Per-agent overrides applied on top of the agent markdown frontmatter. */
85
+ agents: Record<string, AgentOverride>;
86
+ }
87
+
88
+ export const DEFAULT_CONFIG: OrchestraConfig = {
89
+ maxConcurrency: 4,
90
+ defaultAgent: "worker",
91
+ inheritModel: true,
92
+ timeoutMs: 15 * 60 * 1000,
93
+ timeoutMode: "total",
94
+ keepOpen: false,
95
+ notifyOnSettle: true,
96
+ sessionMode: "no-session",
97
+ workerIsolation: true,
98
+ budgetUsdPerWorker: 0,
99
+ budgetUsdPerRun: 0,
100
+ budgetMsPerWorker: 0,
101
+ budgetGraceMs: 60_000,
102
+ stallMs: 600_000,
103
+ stallAction: "notify",
104
+ budgetAction: "stop",
105
+ retries: 0,
106
+ retryBackoffMs: 2000,
107
+ widgetMaxLines: 8,
108
+ widgetShowSettled: false,
109
+ providerExtensions: [],
110
+ agents: {},
111
+ };
112
+
113
+ export interface ConfigSource {
114
+ path: string;
115
+ scope: "global" | "project";
116
+ }
117
+
118
+ function readJson(path: string): Record<string, unknown> | undefined {
119
+ try {
120
+ if (!existsSync(path)) return undefined;
121
+ const raw = readFileSync(path, "utf8");
122
+ const parsed = JSON.parse(raw);
123
+ if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) return undefined;
124
+ return parsed as Record<string, unknown>;
125
+ } catch {
126
+ return undefined;
127
+ }
128
+ }
129
+
130
+ function coerce(base: OrchestraConfig, patch: Record<string, unknown>): OrchestraConfig {
131
+ const next: OrchestraConfig = { ...base, agents: { ...base.agents } };
132
+
133
+ if (typeof patch.maxConcurrency === "number" && patch.maxConcurrency > 0) {
134
+ next.maxConcurrency = Math.floor(patch.maxConcurrency);
135
+ }
136
+ if (typeof patch.defaultAgent === "string" && patch.defaultAgent.trim()) next.defaultAgent = patch.defaultAgent.trim();
137
+ if (typeof patch.inheritModel === "boolean") next.inheritModel = patch.inheritModel;
138
+ if (typeof patch.timeoutMs === "number" && patch.timeoutMs >= 0) next.timeoutMs = patch.timeoutMs;
139
+ if (patch.timeoutMode === "total" || patch.timeoutMode === "idle") next.timeoutMode = patch.timeoutMode;
140
+ if (typeof patch.keepOpen === "boolean") next.keepOpen = patch.keepOpen;
141
+ if (typeof patch.notifyOnSettle === "boolean") next.notifyOnSettle = patch.notifyOnSettle;
142
+ if (typeof patch.workerCommand === "string" && patch.workerCommand.trim()) {
143
+ next.workerCommand = patch.workerCommand.trim();
144
+ }
145
+ if (typeof patch.stateDir === "string" && patch.stateDir.trim()) next.stateDir = patch.stateDir.trim();
146
+ if (patch.sessionMode === "no-session" || patch.sessionMode === "session") next.sessionMode = patch.sessionMode;
147
+ if (typeof patch.workerIsolation === "boolean") next.workerIsolation = patch.workerIsolation;
148
+ if (typeof patch.budgetUsdPerWorker === "number" && patch.budgetUsdPerWorker >= 0) {
149
+ next.budgetUsdPerWorker = patch.budgetUsdPerWorker;
150
+ }
151
+ if (typeof patch.budgetUsdPerRun === "number" && patch.budgetUsdPerRun >= 0) {
152
+ next.budgetUsdPerRun = patch.budgetUsdPerRun;
153
+ }
154
+ if (typeof patch.budgetMsPerWorker === "number" && patch.budgetMsPerWorker >= 0) {
155
+ next.budgetMsPerWorker = patch.budgetMsPerWorker;
156
+ }
157
+ if (typeof patch.budgetGraceMs === "number" && patch.budgetGraceMs >= 0) {
158
+ next.budgetGraceMs = patch.budgetGraceMs;
159
+ }
160
+ if (typeof patch.stallMs === "number" && patch.stallMs >= 0) next.stallMs = patch.stallMs;
161
+ if (patch.stallAction === "notify" || patch.stallAction === "abort") next.stallAction = patch.stallAction;
162
+ if (patch.budgetAction === "stop" || patch.budgetAction === "ask") next.budgetAction = patch.budgetAction;
163
+ if (typeof patch.retries === "number" && patch.retries >= 0) next.retries = Math.floor(patch.retries);
164
+ if (typeof patch.retryBackoffMs === "number" && patch.retryBackoffMs >= 0) next.retryBackoffMs = Math.floor(patch.retryBackoffMs);
165
+ if (typeof patch.widgetMaxLines === "number" && patch.widgetMaxLines > 0) {
166
+ next.widgetMaxLines = Math.floor(patch.widgetMaxLines);
167
+ }
168
+ if (typeof patch.widgetShowSettled === "boolean") next.widgetShowSettled = patch.widgetShowSettled;
169
+ if (Array.isArray(patch.providerExtensions)) {
170
+ next.providerExtensions = patch.providerExtensions.filter((entry): entry is string => typeof entry === "string");
171
+ }
172
+
173
+ if (patch.agents && typeof patch.agents === "object" && !Array.isArray(patch.agents)) {
174
+ for (const [name, value] of Object.entries(patch.agents as Record<string, unknown>)) {
175
+ if (!value || typeof value !== "object" || Array.isArray(value)) continue;
176
+ const entry = value as Record<string, unknown>;
177
+ const override: AgentOverride = { ...(next.agents[name] ?? {}) };
178
+ if (typeof entry.model === "string") override.model = entry.model;
179
+ if (typeof entry.thinking === "string") override.thinking = entry.thinking;
180
+ if (typeof entry.tools === "string") {
181
+ override.tools = entry.tools
182
+ .split(",")
183
+ .map((tool) => tool.trim())
184
+ .filter(Boolean);
185
+ } else if (Array.isArray(entry.tools)) {
186
+ override.tools = entry.tools.filter((tool): tool is string => typeof tool === "string");
187
+ }
188
+ next.agents[name] = override;
189
+ }
190
+ }
191
+
192
+ return next;
193
+ }
194
+
195
+ export function configPaths(cwd: string): ConfigSource[] {
196
+ return [
197
+ { path: join(homedir(), ".pi", "agent", "orchestra.json"), scope: "global" },
198
+ { path: join(resolve(cwd), ".pi", "orchestra.json"), scope: "project" },
199
+ ];
200
+ }
201
+
202
+ export function loadConfig(cwd: string): { config: OrchestraConfig; sources: string[] } {
203
+ let config = DEFAULT_CONFIG;
204
+ const sources: string[] = [];
205
+
206
+ for (const source of configPaths(cwd)) {
207
+ const patch = readJson(source.path);
208
+ if (!patch) continue;
209
+ config = coerce(config, patch);
210
+ sources.push(source.path);
211
+ }
212
+
213
+ return { config, sources };
214
+ }
215
+
216
+ export function resolveStateDir(cwd: string, config: OrchestraConfig): string {
217
+ const dir = config.stateDir ? resolve(cwd, config.stateDir) : join(resolve(cwd), ".pi", "orchestra");
218
+ return dir;
219
+ }