@loka1/pi-orchestra 0.0.0-stage → 0.6.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
@@ -0,0 +1,355 @@
1
+ /**
2
+ * Worker model resolution.
3
+ *
4
+ * A worker is a separate pi process, and with `workerIsolation` it starts with
5
+ * `--no-extensions`, so a provider contributed by an *extension package* is not
6
+ * registered there. Passing the bare model id then either fails (`Unknown
7
+ * provider`) or silently resolves to a different model on a built-in provider.
8
+ *
9
+ * This module answers three questions, provider-agnostically and without
10
+ * requiring any particular package:
11
+ *
12
+ * 1. what `{provider, id}` does a dispatch mean? → `resolveModelChoice`
13
+ * 2. which installed extension makes that provider available? → `providerExtensions`
14
+ * 3. does the worker really see that model? → `probeModel`
15
+ */
16
+
17
+ import { execFile } from "node:child_process";
18
+ import { existsSync, readFileSync, readdirSync } from "node:fs";
19
+ import { homedir } from "node:os";
20
+ import { join, resolve } from "node:path";
21
+
22
+ export interface ModelRef {
23
+ provider?: string;
24
+ id: string;
25
+ }
26
+
27
+ export interface ModelRequest {
28
+ model?: string;
29
+ provider?: string;
30
+ }
31
+
32
+ export function formatModel(ref: { provider?: string; id?: string } | undefined): string {
33
+ if (!ref?.id) return "default";
34
+ return ref.provider ? `(${ref.provider}) ${ref.id}` : ref.id;
35
+ }
36
+
37
+ /**
38
+ * Provider of a bare model id. `commandcode` and the built-in `deepseek` provider
39
+ * both expose ids that look like `deepseek/...`, so a slash is not enough: ask the
40
+ * registry, and prefer the provider the caller already uses when several match.
41
+ */
42
+ export function providerOf(id: string, known: ModelRef[], preferred?: string): string | undefined {
43
+ const matches = known.filter((model) => model.id === id);
44
+ if (matches.length === 0) return undefined;
45
+ if (preferred && matches.some((model) => model.provider === preferred)) return preferred;
46
+ const providers = [...new Set(matches.map((model) => model.provider).filter(Boolean))] as string[];
47
+ return providers.length === 1 ? providers[0] : undefined;
48
+ }
49
+
50
+ export interface ResolveInput {
51
+ /** Tool parameters: `model` and optionally `provider`. */
52
+ requested?: ModelRequest;
53
+ /** Agent frontmatter / config override. */
54
+ agent?: ModelRequest;
55
+ /** The coordinator's own model. */
56
+ inherited?: ModelRef;
57
+ /** Every model the coordinator can see (provider + id). */
58
+ known: ModelRef[];
59
+ /** Whether `inheritModel` is on. */
60
+ inherit: boolean;
61
+ }
62
+
63
+ /** Explicit beats agent beats config beats inherited. */
64
+ export function resolveModelChoice(input: ResolveInput): ModelRef | undefined {
65
+ const preferred = input.inherited?.provider;
66
+ for (const request of [input.requested, input.agent]) {
67
+ if (!request?.model) continue;
68
+ const provider = request.provider ?? providerOf(request.model, input.known, preferred);
69
+ return { provider, id: request.model };
70
+ }
71
+ return input.inherit ? input.inherited : undefined;
72
+ }
73
+
74
+ export interface AvailabilityInput {
75
+ /** The model the dispatch asked for (tool param, agent or config). */
76
+ requested?: ModelRef;
77
+ /** The coordinator's model, used when the requested one is unavailable. */
78
+ inherited?: ModelRef;
79
+ /** Whether the worker process can actually resolve this model. */
80
+ sees: (model: ModelRef) => Promise<boolean>;
81
+ }
82
+
83
+ /**
84
+ * Keep the requested model when the worker can see it; otherwise fall back to the
85
+ * coordinator's model (never silently to a fuzzy match), and explain why.
86
+ */
87
+ export async function pickAvailableModel(
88
+ input: AvailabilityInput,
89
+ ): Promise<{ model?: ModelRef; note?: string }> {
90
+ const requested = input.requested;
91
+ if (!requested?.id) return {};
92
+
93
+ if (await input.sees(requested)) return { model: requested };
94
+
95
+ const inherited = input.inherited;
96
+ const same = inherited?.id === requested.id && inherited?.provider === requested.provider;
97
+ if (inherited && !same && (await input.sees(inherited))) {
98
+ return {
99
+ model: inherited,
100
+ note: `${formatModel(requested)} is not available in an isolated worker; using the coordinator model ${formatModel(inherited)}.`,
101
+ };
102
+ }
103
+ return {
104
+ model: requested,
105
+ note: `${formatModel(requested)} is not available in an isolated worker; pi will resolve the nearest match. Enable the provider package for the worker (providerExtensions) to use it.`,
106
+ };
107
+ }
108
+
109
+ // ---------------------------------------------------------------------------
110
+ // provider extensions among installed packages
111
+ // ---------------------------------------------------------------------------
112
+
113
+ export interface InstalledPackage {
114
+ name: string;
115
+ dir: string;
116
+ }
117
+
118
+ interface SettingsFile {
119
+ path: string;
120
+ base: string;
121
+ }
122
+
123
+ function readSettings(file: string, base: string): SettingsFile | undefined {
124
+ if (!existsSync(file)) return undefined;
125
+ try {
126
+ JSON.parse(readFileSync(file, "utf8"));
127
+ return { path: file, base };
128
+ } catch {
129
+ return undefined;
130
+ }
131
+ }
132
+
133
+ function packageSpecs(file: string): string[] {
134
+ try {
135
+ const parsed = JSON.parse(readFileSync(file, "utf8")) as { packages?: unknown };
136
+ const entries = Array.isArray(parsed.packages) ? parsed.packages : [];
137
+ return entries
138
+ .map((entry) =>
139
+ typeof entry === "string"
140
+ ? entry
141
+ : entry && typeof entry === "object" && typeof (entry as { source?: unknown }).source === "string"
142
+ ? (entry as { source: string }).source
143
+ : undefined,
144
+ )
145
+ .filter((entry): entry is string => Boolean(entry));
146
+ } catch {
147
+ return [];
148
+ }
149
+ }
150
+
151
+ function resolveSpec(spec: string, base: string): string | undefined {
152
+ if (spec.startsWith("npm:")) return join(base, "npm", "node_modules", spec.slice(4));
153
+ if (spec.startsWith("git:")) return join(base, "git", spec.slice(4));
154
+ if (spec.startsWith("file:")) return resolve(base, spec.slice(5));
155
+ if (spec.startsWith("/") || spec.startsWith("./") || spec.startsWith("../")) return resolve(base, spec);
156
+ return undefined;
157
+ }
158
+
159
+ /**
160
+ * Packages the user already installed, resolved to directories. Nothing here is
161
+ * pi-orchestra-specific: whatever provides a model can be reused by a worker.
162
+ */
163
+ /** pi's global config dir, honouring `--agent-dir` / `PI_CODING_AGENT_DIR`. */
164
+ export function defaultAgentDir(): string {
165
+ return process.env.PI_CODING_AGENT_DIR || join(homedir(), ".pi", "agent");
166
+ }
167
+
168
+ export function installedPackages(cwd: string, agentDir = defaultAgentDir()): InstalledPackage[] {
169
+ const files = [
170
+ readSettings(join(agentDir, "settings.json"), agentDir),
171
+ readSettings(join(cwd, ".pi", "settings.json"), join(cwd, ".pi")),
172
+ ].filter((file): file is SettingsFile => Boolean(file));
173
+
174
+ const seen = new Set<string>();
175
+ const packages: InstalledPackage[] = [];
176
+ for (const file of files) {
177
+ for (const spec of packageSpecs(file.path)) {
178
+ const dir = resolveSpec(spec, file.base);
179
+ if (!dir || seen.has(dir) || !existsSync(join(dir, "package.json"))) continue;
180
+ seen.add(dir);
181
+ packages.push({ name: spec, dir });
182
+ }
183
+ }
184
+ return packages;
185
+ }
186
+
187
+ /** Entry files a pi package declares under its `pi.extensions` manifest. */
188
+ export function extensionFiles(dir: string): string[] {
189
+ try {
190
+ const manifest = JSON.parse(readFileSync(join(dir, "package.json"), "utf8")) as {
191
+ pi?: unknown;
192
+ main?: string;
193
+ };
194
+ const declared =
195
+ manifest.pi && typeof manifest.pi === "object" && Array.isArray((manifest.pi as { extensions?: unknown }).extensions)
196
+ ? ((manifest.pi as { extensions: unknown[] }).extensions.filter(
197
+ (entry): entry is string => typeof entry === "string",
198
+ ) as string[])
199
+ : [];
200
+ const files = declared.map((entry) => resolve(dir, entry));
201
+ if (files.length === 0 && typeof manifest.main === "string") files.push(resolve(dir, manifest.main));
202
+ return files.filter((file) => existsSync(file));
203
+ } catch {
204
+ return [];
205
+ }
206
+ }
207
+
208
+ function readCapped(file: string, cap = 400_000): string {
209
+ try {
210
+ return readFileSync(file, "utf8").slice(0, cap);
211
+ } catch {
212
+ return "";
213
+ }
214
+ }
215
+
216
+ /**
217
+ * A provider registration is an id next to `registerProvider`; requiring both
218
+ * keeps unrelated packages (that merely mention the provider in prose) out.
219
+ */
220
+ export function mentionsProvider(file: string, provider: string): boolean {
221
+ const text = readCapped(file);
222
+ if (!text.includes("registerProvider")) return false;
223
+ const quoted = `["'\`]${provider.replace(/[.*+?^${}()|[\]\\]/g, "\\$&")}["'\`]`;
224
+ const after = new RegExp(`registerProvider[\\s\\S]{0,400}${quoted}`);
225
+ const before = new RegExp(`${quoted}[\\s\\S]{0,400}registerProvider`);
226
+ return after.test(text) || before.test(text);
227
+ }
228
+
229
+ function sourceFiles(dir: string, limit = 60): string[] {
230
+ if (!existsSync(dir)) return [];
231
+ const out: string[] = [];
232
+ for (const entry of readdirSync(dir, { withFileTypes: true })) {
233
+ if (out.length >= limit) break;
234
+ if (!entry.isFile()) continue;
235
+ if (!/\.(ts|js|mjs|cjs)$/.test(entry.name)) continue;
236
+ out.push(join(dir, entry.name));
237
+ }
238
+ return out;
239
+ }
240
+
241
+ /**
242
+ * Extension entry files that register `provider`, taken from packages the user
243
+ * already has installed. Empty when nothing matches — never a hard requirement.
244
+ */
245
+ export function providerExtensions(provider: string, cwd: string, agentDir?: string): string[] {
246
+ const found: string[] = [];
247
+ for (const pkg of installedPackages(cwd, agentDir)) {
248
+ const entries = extensionFiles(pkg.dir);
249
+ if (entries.length === 0) continue;
250
+ const direct = entries.some((file) => mentionsProvider(file, provider));
251
+ const viaSources = direct || sourceFiles(join(pkg.dir, "src")).some((file) => mentionsProvider(file, provider));
252
+ if (viaSources) {
253
+ for (const file of entries) if (!found.includes(file)) found.push(file);
254
+ }
255
+ }
256
+ return found;
257
+ }
258
+
259
+ /** Resolve `npm:`/`git:`/path entries from the `providerExtensions` config. */
260
+ export function resolveExtensions(specs: string[], cwd: string, agentDir?: string): string[] {
261
+ const out: string[] = [];
262
+ for (const spec of specs) {
263
+ const direct = resolve(spec);
264
+ if (existsSync(direct)) {
265
+ out.push(direct);
266
+ continue;
267
+ }
268
+ const pkg = installedPackages(cwd, agentDir).find((candidate) => candidate.dir.endsWith(spec.replace(/^npm:/, "")));
269
+ if (pkg) {
270
+ for (const file of extensionFiles(pkg.dir)) if (!out.includes(file)) out.push(file);
271
+ continue;
272
+ }
273
+ const resolved = resolveSpec(spec, agentDir ?? defaultAgentDir());
274
+ if (resolved) {
275
+ for (const file of extensionFiles(resolved)) if (!out.includes(file)) out.push(file);
276
+ }
277
+ }
278
+ return out;
279
+ }
280
+
281
+ // ---------------------------------------------------------------------------
282
+ // probe: does the worker's own model list contain this pair?
283
+ // ---------------------------------------------------------------------------
284
+
285
+ const probes = new Map<string, Promise<boolean>>();
286
+
287
+ export function clearProbeCache(): void {
288
+ probes.clear();
289
+ }
290
+
291
+ /** Rows of `pi --list-models` output as `{provider, id}`. */
292
+ export function parseModelList(stdout: string): ModelRef[] {
293
+ const rows: ModelRef[] = [];
294
+ for (const line of stdout.split("\n")) {
295
+ const fields = line.trim().split(/\s+/);
296
+ if (fields.length < 2) continue;
297
+ const [provider, id] = fields;
298
+ if (!provider || !id || provider === "provider") continue;
299
+ if (!/^[a-z0-9._-]+$/i.test(provider)) continue;
300
+ rows.push({ provider, id });
301
+ }
302
+ return rows;
303
+ }
304
+
305
+ export interface ProbeInput {
306
+ /** The pi invocation without the probe flags. */
307
+ command: string;
308
+ args: string[];
309
+ cwd: string;
310
+ provider?: string;
311
+ id: string;
312
+ timeoutMs?: number;
313
+ env?: NodeJS.ProcessEnv;
314
+ }
315
+
316
+ /**
317
+ * Ask a throwaway pi process for its model list. This is the only trustworthy
318
+ * check: it applies the same flags the worker will get, including `-e` extras.
319
+ */
320
+ export function probeModel(input: ProbeInput): Promise<boolean> {
321
+ const key = [input.command, ...input.args, input.provider ?? "", input.id].join("\u0000");
322
+ const cached = probes.get(key);
323
+ if (cached) return cached;
324
+
325
+ const search = input.provider ? `${input.provider}/${input.id}` : input.id;
326
+ const promise = new Promise<boolean>((resolvePromise) => {
327
+ execFile(
328
+ input.command,
329
+ [...input.args, "--offline", "--list-models", search],
330
+ { cwd: input.cwd, timeout: input.timeoutMs ?? 20_000, env: input.env ?? process.env, maxBuffer: 4 * 1024 * 1024 },
331
+ (error, stdout) => {
332
+ if (error) {
333
+ resolvePromise(false);
334
+ return;
335
+ }
336
+ const rows = parseModelList(stdout);
337
+ resolvePromise(
338
+ rows.some(
339
+ (row) => row.id === input.id && (input.provider === undefined || row.provider === input.provider),
340
+ ),
341
+ );
342
+ },
343
+ );
344
+ });
345
+ probes.set(key, promise);
346
+ return promise;
347
+ }
348
+
349
+ /** Arguments that reproduce the worker's model environment for a probe. */
350
+ export function probeArgs(options: { isolated: boolean; extensions: string[] }): string[] {
351
+ if (!options.isolated) return [];
352
+ const args = ["--no-extensions"];
353
+ for (const file of options.extensions) args.push("-e", file);
354
+ return args;
355
+ }
@@ -0,0 +1,57 @@
1
+ /**
2
+ * Secret scrubbing for anything that is persisted or rendered.
3
+ *
4
+ * Worker output is written to `.pi/orchestra/logs/*.jsonl`, then shown in
5
+ * transcripts, reports and the browser. A worker that prints an env dump or a
6
+ * curl command must not turn that into a plaintext credential on disk, so the
7
+ * log writer redacts first and the renderers redact again on the way out.
8
+ */
9
+
10
+ /** Applied in order; each pattern keeps enough shape to stay recognisable. */
11
+ const RULES: Array<{ pattern: RegExp; replace: string }> = [
12
+ // OpenAI / Anthropic style keys, including `sk-proj-…` and `sk-ant-…`.
13
+ { pattern: /\bsk-(?:proj-|ant-)?[A-Za-z0-9_-]{16,}/g, replace: "sk-***REDACTED***" },
14
+ // GitHub tokens: ghp_, gho_, ghu_, ghs_, ghr_.
15
+ { pattern: /\bgh[pousr]_[A-Za-z0-9]{20,}/g, replace: "gh*_***REDACTED***" },
16
+ // npm automation/publish tokens.
17
+ { pattern: /\bnpm_[A-Za-z0-9]{20,}/g, replace: "npm_***REDACTED***" },
18
+ // Slack tokens.
19
+ { pattern: /\bxox[abprs]-[A-Za-z0-9-]{10,}/g, replace: "xox*-***REDACTED***" },
20
+ // AWS access key ids.
21
+ { pattern: /\bAKIA[0-9A-Z]{16}\b/g, replace: "AKIA***REDACTED***" },
22
+ // JWT-ish blobs.
23
+ { pattern: /\beyJ[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}\.[A-Za-z0-9_-]{10,}/g, replace: "***JWT***" },
24
+ // Authorization headers.
25
+ { pattern: /\b(Bearer|Basic)\s+[A-Za-z0-9._~+/=-]{16,}/gi, replace: "$1 ***REDACTED***" },
26
+ // key=value / "key": "value" assignments.
27
+ {
28
+ pattern:
29
+ /\b([A-Za-z0-9_-]*(?:api[_-]?key|apikey|access[_-]?token|auth[_-]?token|secret|password|passwd|client[_-]?secret)[A-Za-z0-9_-]*)(["']?\s*[:=]\s*["']?)([A-Za-z0-9._~+/=-]{12,})/gi,
30
+ replace: "$1$2***REDACTED***",
31
+ },
32
+ ];
33
+
34
+ /** Larger inputs are truncated before redaction to keep the regexes bounded. */
35
+ const MAX_LENGTH = 400_000;
36
+
37
+ export function redact(text: string): string {
38
+ if (!text) return text;
39
+ let out = text.length > MAX_LENGTH ? text.slice(0, MAX_LENGTH) : text;
40
+ for (const rule of RULES) out = out.replace(rule.pattern, rule.replace);
41
+ return out;
42
+ }
43
+
44
+ /** Redact every string value of a JSON-ish record (used for log lines). */
45
+ export function redactRecord<T>(value: T): T {
46
+ if (typeof value === "string") return redact(value) as unknown as T;
47
+ if (Array.isArray(value)) return value.map((entry) => redactRecord(entry)) as unknown as T;
48
+ if (value && typeof value === "object") {
49
+ const out: Record<string, unknown> = {};
50
+ for (const [key, entry] of Object.entries(value as Record<string, unknown>)) {
51
+ // Never rewrite a key; only the values can carry a secret.
52
+ out[key] = redactRecord(entry);
53
+ }
54
+ return out as T;
55
+ }
56
+ return value;
57
+ }
@@ -0,0 +1,61 @@
1
+ /**
2
+ * Retry planning: a failed worker can be replaced automatically, with the same
3
+ * brief and the failure prepended, up to a configured number of attempts.
4
+ *
5
+ * Kept pure so the decision can be tested without spawning anything.
6
+ */
7
+
8
+ import type { Dispatch } from "./types.ts";
9
+
10
+ export interface RetryPolicy {
11
+ /** Extra attempts after the first one. 0 disables retries. */
12
+ retries: number;
13
+ /** Wait before the first retry; doubles per attempt, capped. */
14
+ retryBackoffMs: number;
15
+ }
16
+
17
+ export interface RetryDecision {
18
+ retry: boolean;
19
+ /** 1-based number the next attempt would carry. */
20
+ nextAttempt: number;
21
+ delayMs: number;
22
+ reason: string;
23
+ }
24
+
25
+ const MAX_BACKOFF_MS = 300_000;
26
+
27
+ /** Statuses worth another go. A user stop or a budget/stall kill is deliberate. */
28
+ const RETRYABLE = new Set(["failed", "timeout", "lost"]);
29
+
30
+ /**
31
+ * Decide whether `dispatch` should be retried. `attempt` counts attempts already
32
+ * made (the first dispatch is attempt 1).
33
+ */
34
+ export function planRetry(
35
+ dispatch: Pick<Dispatch, "status" | "attempt" | "retries" | "stopReason" | "resumedFrom">,
36
+ policy: RetryPolicy,
37
+ options: { runExhausted?: boolean } = {},
38
+ ): RetryDecision {
39
+ const attempts = dispatch.attempt ?? 1;
40
+ const allowed = dispatch.retries ?? policy.retries;
41
+ const nextAttempt = attempts + 1;
42
+ const deny = (reason: string): RetryDecision => ({ retry: false, nextAttempt, delayMs: 0, reason });
43
+
44
+ if (!RETRYABLE.has(dispatch.status)) return deny(`status ${dispatch.status} is not retryable`);
45
+ if (dispatch.stopReason) return deny(`stopped by policy (${dispatch.stopReason})`);
46
+ if (dispatch.resumedFrom) return deny("resumed sessions are not retried automatically");
47
+ if (allowed <= 0) return deny("retries are disabled");
48
+ if (attempts > allowed) return deny(`attempt ${attempts} of ${allowed + 1} was the last`);
49
+ if (options.runExhausted) return deny("run budget exhausted");
50
+
51
+ const delayMs = Math.min(
52
+ MAX_BACKOFF_MS,
53
+ Math.round(Math.max(0, policy.retryBackoffMs) * 2 ** Math.max(0, attempts - 1)),
54
+ );
55
+ return {
56
+ retry: true,
57
+ nextAttempt,
58
+ delayMs,
59
+ reason: `attempt ${nextAttempt} of ${allowed + 1} in ${Math.round(delayMs / 1000)}s`,
60
+ };
61
+ }