@wierdbytes/pi-wierdr 0.0.0-stage → 0.1.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,545 @@
1
+ /**
2
+ * Parent side: starts sub-agents as child terminals of this pi's terminal,
3
+ * follows them (herdr-core events + the child's run file) and answers
4
+ * wait / steer / stop. One manager per pi process.
5
+ */
6
+
7
+ import { type FSWatcher, watch } from "node:fs";
8
+ import type { AgentType } from "./agent-types.ts";
9
+ import {
10
+ HcError,
11
+ type HcEndpoint,
12
+ type HcEvent,
13
+ HcSubscription,
14
+ type HcTerminal,
15
+ hcCall,
16
+ type SubscriptionHandlers,
17
+ } from "./hc.ts";
18
+ import { buildArgv, ENV, inheritedEnv, nameCandidate, slugName } from "./launch.ts";
19
+ import {
20
+ type ChildActivity,
21
+ ensureDir,
22
+ newRunId,
23
+ readMeta,
24
+ readState,
25
+ runIdOfStateFile,
26
+ writeMeta,
27
+ } from "./runs.ts";
28
+ import type { AgentsSettings } from "./settings.ts";
29
+
30
+ export type AgentStatus = "running" | "blocked" | "completed" | "failed" | "stopped";
31
+
32
+ export const isActive = (s: AgentStatus): boolean => s === "running";
33
+ export const isFinal = (s: AgentStatus): boolean => s === "completed" || s === "failed" || s === "stopped";
34
+
35
+ export interface AgentSnapshot {
36
+ /** The hc terminal name: what tools and herdr call it. */
37
+ id: string;
38
+ /** The hc address (`t8c`). */
39
+ address: string;
40
+ runId: string;
41
+ description: string;
42
+ type: string;
43
+ model?: string;
44
+ thinking?: string;
45
+ cwd: string;
46
+ status: AgentStatus;
47
+ background: boolean;
48
+ /** When the current piece of work was handed over. */
49
+ startedAt: number;
50
+ endedAt?: number;
51
+ result?: string;
52
+ error?: string;
53
+ activity?: ChildActivity;
54
+ /** The child's own status word and message, as herdr shows them. */
55
+ hcStatus?: string;
56
+ hcMessage?: string;
57
+ sessionId?: string;
58
+ /** The terminal is still there. */
59
+ live: boolean;
60
+ }
61
+
62
+ export interface AgentRecord extends AgentSnapshot {
63
+ /** Tell the parent's model when this settles. */
64
+ notify: boolean;
65
+ /** Its latest result was already handed to the model. */
66
+ consumed: boolean;
67
+ /** The child's settled-run count when the current work was handed over. */
68
+ baseline: number;
69
+ }
70
+
71
+ export const snapshot = (r: AgentRecord): AgentSnapshot => ({
72
+ id: r.id,
73
+ address: r.address,
74
+ runId: r.runId,
75
+ description: r.description,
76
+ type: r.type,
77
+ model: r.model,
78
+ thinking: r.thinking,
79
+ cwd: r.cwd,
80
+ status: r.status,
81
+ background: r.background,
82
+ startedAt: r.startedAt,
83
+ endedAt: r.endedAt,
84
+ result: r.result,
85
+ error: r.error,
86
+ activity: r.activity ? { ...r.activity } : undefined,
87
+ hcStatus: r.hcStatus,
88
+ hcMessage: r.hcMessage,
89
+ sessionId: r.sessionId,
90
+ live: r.live,
91
+ });
92
+
93
+ export interface SpawnSpec {
94
+ prompt: string;
95
+ description: string;
96
+ type: AgentType;
97
+ /** `provider/id`. */
98
+ model?: string;
99
+ thinking?: string;
100
+ cwd: string;
101
+ background: boolean;
102
+ /** Tell the model when it settles (background tool runs). */
103
+ notify: boolean;
104
+ /** The parent's project trust, inherited by the child. */
105
+ trust?: "yes" | "no";
106
+ }
107
+
108
+ export type WaitOutcome = "settled" | "timeout" | "aborted";
109
+
110
+ export type ChangeListener = (rec: AgentRecord, previous: AgentStatus | undefined) => void;
111
+
112
+ export interface ManagerDeps {
113
+ endpoint: HcEndpoint;
114
+ runsDir: string;
115
+ settings: AgentsSettings;
116
+ /** This pi's own depth: 0 at the top. */
117
+ depth: number;
118
+ env?: NodeJS.ProcessEnv;
119
+ pid?: number;
120
+ /** For tests: the herdr-core call. */
121
+ call?: typeof hcCall;
122
+ /** For tests: the event stream. */
123
+ subscribe?: (params: Record<string, unknown>, handlers: SubscriptionHandlers) => { start(): void; stop(): void };
124
+ }
125
+
126
+ // Named before pi-agents became pi-wierdr, and kept: a pi updated in place
127
+ // still finds the sub-agents it started before.
128
+ const LABEL_RUN = "pi-agents.run";
129
+ const LABEL_PID = "pi-agents.pid";
130
+ const LABEL_TYPE = "pi-agents.type";
131
+
132
+ export class AgentManager {
133
+ private readonly byId = new Map<string, AgentRecord>();
134
+ private readonly byAddress = new Map<string, AgentRecord>();
135
+ private readonly byRun = new Map<string, AgentRecord>();
136
+ private readonly waiters = new Map<AgentRecord, Set<() => void>>();
137
+ private readonly listeners = new Set<ChangeListener>();
138
+ private subscription: { start(): void; stop(): void } | undefined;
139
+ private watcher: FSWatcher | undefined;
140
+ private poll: ReturnType<typeof setInterval> | undefined;
141
+ private readonly call: typeof hcCall;
142
+ private readonly pid: number;
143
+
144
+ constructor(private readonly deps: ManagerDeps) {
145
+ this.call = deps.call ?? hcCall;
146
+ this.pid = deps.pid ?? process.pid;
147
+ }
148
+
149
+ // ─────────────────────────────────────────────────────────── lifecycle ──
150
+
151
+ /** Follow this terminal's children; adopts sub-agents a previous load of this pi started. */
152
+ start(): void {
153
+ if (this.subscription) return;
154
+ const params = { children_of: this.deps.endpoint.terminal };
155
+ const handlers: SubscriptionHandlers = { snapshot: (ts) => this.onSnapshot(ts), event: (e) => this.onEvent(e) };
156
+ this.subscription = this.deps.subscribe
157
+ ? this.deps.subscribe(params, handlers)
158
+ : new HcSubscription(this.deps.endpoint.socket, params, handlers);
159
+ this.subscription.start();
160
+ try {
161
+ ensureDir(this.deps.runsDir);
162
+ this.watcher = watch(this.deps.runsDir, (_evt, file) => {
163
+ const runId = file ? runIdOfStateFile(String(file)) : undefined;
164
+ const rec = runId ? this.byRun.get(runId) : undefined;
165
+ if (rec) this.reconcile(rec);
166
+ });
167
+ this.watcher.unref?.();
168
+ } catch {
169
+ // The poll below still notices.
170
+ }
171
+ this.poll = setInterval(() => {
172
+ for (const rec of this.byId.values()) if (rec.live && !isFinal(rec.status)) this.reconcile(rec);
173
+ }, 2000);
174
+ this.poll.unref?.();
175
+ }
176
+
177
+ dispose(): void {
178
+ this.subscription?.stop();
179
+ this.subscription = undefined;
180
+ this.watcher?.close();
181
+ this.watcher = undefined;
182
+ if (this.poll) clearInterval(this.poll);
183
+ this.poll = undefined;
184
+ for (const set of this.waiters.values()) for (const wake of set) wake();
185
+ this.waiters.clear();
186
+ }
187
+
188
+ onChange(listener: ChangeListener): () => void {
189
+ this.listeners.add(listener);
190
+ return () => this.listeners.delete(listener);
191
+ }
192
+
193
+ // ─────────────────────────────────────────────────────────── queries ──
194
+
195
+ list(): AgentRecord[] {
196
+ return [...this.byId.values()];
197
+ }
198
+
199
+ /** By name, address or run id. */
200
+ find(ref: string): AgentRecord | undefined {
201
+ const r = ref.trim();
202
+ return this.byId.get(r) ?? this.byAddress.get(r) ?? this.byRun.get(r);
203
+ }
204
+
205
+ // ─────────────────────────────────────────────────────────── actions ──
206
+
207
+ async spawn(spec: SpawnSpec): Promise<AgentRecord> {
208
+ const { endpoint, runsDir, settings } = this.deps;
209
+ const runId = newRunId();
210
+ const depth = this.deps.depth + 1;
211
+ writeMeta(runsDir, {
212
+ v: 1,
213
+ runId,
214
+ description: spec.description,
215
+ type: spec.type.name,
216
+ typePrompt: spec.type.prompt,
217
+ parent: endpoint.terminal,
218
+ parentPid: this.pid,
219
+ depth,
220
+ cwd: spec.cwd,
221
+ model: spec.model,
222
+ thinking: spec.thinking,
223
+ createdAt: Date.now(),
224
+ });
225
+ const argv = buildArgv(settings, {
226
+ model: spec.model,
227
+ thinking: spec.thinking,
228
+ tools: spec.type.tools,
229
+ excludeTools: spec.type.excludeTools,
230
+ sessionName: spec.description,
231
+ prompt: spec.prompt,
232
+ });
233
+ const env: Record<string, string> = {
234
+ ...(settings.inheritEnv ? inheritedEnv(this.deps.env ?? process.env) : {}),
235
+ [ENV.RUN]: runId,
236
+ [ENV.DIR]: runsDir,
237
+ [ENV.DEPTH]: String(depth),
238
+ };
239
+ if (spec.trust) env[ENV.TRUST] = spec.trust;
240
+
241
+ this.start();
242
+ const base = slugName(spec.description);
243
+ let created: HcTerminal | undefined;
244
+ for (let attempt = 1; attempt <= 30 && !created; attempt++) {
245
+ try {
246
+ created = await this.call<HcTerminal>(endpoint.socket, "terminal.run", {
247
+ argv,
248
+ cwd: spec.cwd,
249
+ env,
250
+ labels: { [LABEL_RUN]: runId, [LABEL_PID]: String(this.pid), [LABEL_TYPE]: spec.type.name },
251
+ name: nameCandidate(base, attempt),
252
+ caller: endpoint.terminal,
253
+ parent: endpoint.terminal,
254
+ no_notify: true,
255
+ });
256
+ } catch (e) {
257
+ if (e instanceof HcError && e.kind === "name_taken") continue;
258
+ throw e;
259
+ }
260
+ }
261
+ if (!created) throw new Error(`no free terminal name for "${base}"`);
262
+
263
+ const rec: AgentRecord = {
264
+ id: created.name ?? created.address,
265
+ address: created.address,
266
+ runId,
267
+ description: spec.description,
268
+ type: spec.type.name,
269
+ model: spec.model,
270
+ thinking: spec.thinking,
271
+ cwd: spec.cwd,
272
+ status: "running",
273
+ background: spec.background,
274
+ startedAt: Date.now(),
275
+ live: created.state !== "finished",
276
+ notify: spec.notify,
277
+ consumed: false,
278
+ baseline: 0,
279
+ };
280
+ this.add(rec);
281
+ this.emit(rec, undefined);
282
+ return rec;
283
+ }
284
+
285
+ /**
286
+ * Resolves once the record leaves `running` (completed, failed, stopped,
287
+ * or blocked on a person), at `timeoutMs`, or when `signal` aborts.
288
+ */
289
+ wait(rec: AgentRecord, opts: { signal?: AbortSignal; timeoutMs?: number } = {}): Promise<WaitOutcome> {
290
+ if (!isActive(rec.status)) return Promise.resolve("settled");
291
+ if (opts.signal?.aborted) return Promise.resolve("aborted");
292
+ return new Promise((resolve) => {
293
+ let timer: ReturnType<typeof setTimeout> | undefined;
294
+ const set = this.waiters.get(rec) ?? new Set();
295
+ this.waiters.set(rec, set);
296
+ const done = (outcome: WaitOutcome) => {
297
+ set.delete(wake);
298
+ if (timer) clearTimeout(timer);
299
+ opts.signal?.removeEventListener("abort", onAbort);
300
+ resolve(outcome);
301
+ };
302
+ const wake = () => done("settled");
303
+ const onAbort = () => done("aborted");
304
+ set.add(wake);
305
+ opts.signal?.addEventListener("abort", onAbort, { once: true });
306
+ if (opts.timeoutMs !== undefined && opts.timeoutMs > 0) timer = setTimeout(() => done("timeout"), opts.timeoutMs);
307
+ });
308
+ }
309
+
310
+ /**
311
+ * Types `message` into the sub-agent. While it works, pi takes it as a
312
+ * steer; once it has finished, it starts a new turn and the record runs again.
313
+ */
314
+ async steer(rec: AgentRecord, message: string): Promise<{ mode: "steer" | "follow-up" }> {
315
+ if (!rec.live) throw new Error(`${rec.id}'s terminal has ended; start a new agent instead`);
316
+ if (rec.status === "stopped") throw new Error(`${rec.id} was stopped`);
317
+ if (rec.status === "blocked") {
318
+ throw new Error(
319
+ `${rec.id} is waiting for a person${rec.hcMessage ? ` (${rec.hcMessage})` : ""}; ask the user to answer it in herdr`,
320
+ );
321
+ }
322
+ const mode = rec.status === "running" ? "steer" : "follow-up";
323
+ // Running again before the send returns (hc waits for a quiet moment):
324
+ // a wait issued alongside this steer must wait for the new turn.
325
+ const before = { status: rec.status, baseline: rec.baseline, error: rec.error, endedAt: rec.endedAt, startedAt: rec.startedAt, consumed: rec.consumed };
326
+ if (mode === "follow-up") {
327
+ rec.baseline = readState(this.deps.runsDir, rec.runId)?.seq ?? rec.baseline;
328
+ rec.error = undefined;
329
+ rec.endedAt = undefined;
330
+ rec.startedAt = Date.now();
331
+ rec.consumed = false;
332
+ this.setStatus(rec, "running");
333
+ }
334
+ try {
335
+ await this.call(
336
+ this.deps.endpoint.socket,
337
+ "terminal.send",
338
+ { terminal: rec.address, text: message, caller: this.deps.endpoint.terminal },
339
+ { timeoutMs: 90_000 },
340
+ );
341
+ } catch (e) {
342
+ if (mode === "follow-up" && rec.status === "running") {
343
+ Object.assign(rec, { ...before, status: rec.status });
344
+ this.setStatus(rec, before.status);
345
+ }
346
+ throw e;
347
+ }
348
+ // A very fast turn may already have settled.
349
+ if (mode === "follow-up") this.reconcile(rec);
350
+ return { mode };
351
+ }
352
+
353
+ /** Ends the sub-agent's pi and removes its terminal. */
354
+ async stop(rec: AgentRecord): Promise<void> {
355
+ const { socket } = this.deps.endpoint;
356
+ if (rec.live) {
357
+ try {
358
+ await this.call(socket, "terminal.kill", { terminal: rec.address, caller: this.deps.endpoint.terminal }, { timeoutMs: 10_000 });
359
+ } catch (e) {
360
+ if (!(e instanceof HcError && e.kind === "not_found")) throw e;
361
+ }
362
+ }
363
+ rec.live = false;
364
+ if (!isFinal(rec.status)) {
365
+ rec.error = rec.error ?? "stopped";
366
+ this.setStatus(rec, "stopped");
367
+ }
368
+ await this.call(socket, "terminal.rm", { terminal: rec.address }, { timeoutMs: 5000 }).catch(() => undefined);
369
+ }
370
+
371
+ /** On quit: end every live sub-agent (herdr would only end them with the terminal). */
372
+ async stopAll(timeoutMs = 2000): Promise<void> {
373
+ const live = this.list().filter((r) => r.live);
374
+ await Promise.all(
375
+ live.map((r) =>
376
+ this.call(this.deps.endpoint.socket, "terminal.kill", { terminal: r.address }, { timeoutMs }).catch(() => undefined),
377
+ ),
378
+ );
379
+ }
380
+
381
+ // ─────────────────────────────────────────────────────────── internals ──
382
+
383
+ private add(rec: AgentRecord): void {
384
+ this.byId.set(rec.id, rec);
385
+ this.byAddress.set(rec.address, rec);
386
+ this.byRun.set(rec.runId, rec);
387
+ }
388
+
389
+ private emit(rec: AgentRecord, previous: AgentStatus | undefined): void {
390
+ for (const l of this.listeners) {
391
+ try {
392
+ l(rec, previous);
393
+ } catch {
394
+ // A listener bug must not break tracking.
395
+ }
396
+ }
397
+ }
398
+
399
+ private setStatus(rec: AgentRecord, status: AgentStatus): void {
400
+ const previous = rec.status;
401
+ if (previous === status) return;
402
+ rec.status = status;
403
+ if (isFinal(status)) rec.endedAt = Date.now();
404
+ if (!isActive(status)) {
405
+ const set = this.waiters.get(rec);
406
+ if (set) for (const wake of [...set]) wake();
407
+ }
408
+ this.emit(rec, previous);
409
+ }
410
+
411
+ /** Reads the child's run file and moves the record on when a run settled. */
412
+ reconcile(rec: AgentRecord): void {
413
+ const st = readState(this.deps.runsDir, rec.runId);
414
+ let changed = false;
415
+ if (st) {
416
+ if (st.activity && st.activity.at !== rec.activity?.at) {
417
+ rec.activity = st.activity;
418
+ changed = true;
419
+ }
420
+ if (st.sessionId && st.sessionId !== rec.sessionId) rec.sessionId = st.sessionId;
421
+ if (st.seq > rec.baseline) {
422
+ rec.baseline = st.seq;
423
+ const last = st.last;
424
+ rec.result = last?.text ?? rec.result;
425
+ rec.error =
426
+ last?.status === "error" ? (last.error ?? "error") : last?.status === "aborted" ? "interrupted" : undefined;
427
+ if (!isFinal(rec.status)) {
428
+ this.setStatus(rec, last?.status === "error" ? "failed" : "completed");
429
+ return;
430
+ }
431
+ // Someone kept working with it in herdr: keep its latest answer.
432
+ changed = true;
433
+ }
434
+ }
435
+ if (changed) this.emit(rec, rec.status);
436
+ }
437
+
438
+ private onSnapshot(terminals: HcTerminal[]): void {
439
+ const seen = new Set<string>();
440
+ for (const t of terminals) {
441
+ seen.add(t.address);
442
+ const rec = this.byAddress.get(t.address) ?? this.adopt(t);
443
+ if (!rec) continue;
444
+ this.applyStatus(rec, t.status ?? null);
445
+ if (t.state === "finished") this.onFinished(rec, { exit_code: t.exit_code, reason: t.reason });
446
+ else this.reconcile(rec);
447
+ }
448
+ // Gone while we weren't listening.
449
+ for (const rec of this.byId.values()) {
450
+ if (rec.live && !seen.has(rec.address)) this.onFinished(rec, { reason: "removed" });
451
+ }
452
+ }
453
+
454
+ private onEvent(e: HcEvent): void {
455
+ const rec = this.byAddress.get(e.terminal);
456
+ if (!rec) return;
457
+ switch (e.type) {
458
+ case "status":
459
+ this.applyStatus(rec, e.data?.status ?? null);
460
+ break;
461
+ case "finished":
462
+ this.onFinished(rec, e.data ?? {});
463
+ break;
464
+ case "removed":
465
+ this.onFinished(rec, { reason: "removed" });
466
+ break;
467
+ default:
468
+ break;
469
+ }
470
+ }
471
+
472
+ private applyStatus(rec: AgentRecord, status: HcTerminal["status"]): void {
473
+ const word = status?.state;
474
+ const msg = status?.msg || undefined;
475
+ const changed = word !== rec.hcStatus || msg !== rec.hcMessage;
476
+ rec.hcStatus = word;
477
+ rec.hcMessage = msg;
478
+ if (word === "blocked" && rec.status === "running") {
479
+ this.setStatus(rec, "blocked");
480
+ return;
481
+ }
482
+ if (word === "working" && rec.status === "blocked") {
483
+ this.setStatus(rec, "running");
484
+ return;
485
+ }
486
+ // done / idle / error: the run file says how it ended (if it isn't there yet, fs.watch or the poll will see it).
487
+ if (word && word !== "working" && word !== "blocked") this.reconcile(rec);
488
+ if (changed) this.emit(rec, rec.status);
489
+ }
490
+
491
+ private onFinished(rec: AgentRecord, info: { exit_code?: number | null; reason?: string | null }): void {
492
+ if (!rec.live) return;
493
+ rec.live = false;
494
+ // A run may have settled just before the exit.
495
+ this.reconcile(rec);
496
+ if (isFinal(rec.status)) {
497
+ this.emit(rec, rec.status);
498
+ return;
499
+ }
500
+ const how = info.reason === "removed" ? "its terminal was removed" : `pi exited${info.exit_code != null ? ` with code ${info.exit_code}` : ""}${info.reason && info.reason !== "exited" ? ` (${info.reason})` : ""}`;
501
+ const { socket } = this.deps.endpoint;
502
+ void this.call<{ text?: string }>(socket, "terminal.read", { terminal: rec.address, lines: 40 }, { timeoutMs: 3000 })
503
+ .then((r) => r?.text?.trim())
504
+ .catch(() => undefined)
505
+ .then((tail) => {
506
+ rec.error = tail ? `${how}. Last screen:\n${tail}` : how;
507
+ this.setStatus(rec, "failed");
508
+ void this.call(socket, "terminal.rm", { terminal: rec.address }, { timeoutMs: 3000 }).catch(() => undefined);
509
+ });
510
+ }
511
+
512
+ /** A child this pi process started before a /reload. */
513
+ private adopt(t: HcTerminal): AgentRecord | undefined {
514
+ const runId = t.labels?.[LABEL_RUN];
515
+ if (!runId || t.labels?.[LABEL_PID] !== String(this.pid) || t.state !== "live") return undefined;
516
+ const meta = readMeta(this.deps.runsDir, runId);
517
+ const st = readState(this.deps.runsDir, runId);
518
+ const working = t.status?.state === "working" || st?.running === true;
519
+ const rec: AgentRecord = {
520
+ id: t.name ?? t.address,
521
+ address: t.address,
522
+ runId,
523
+ description: meta?.description ?? t.name ?? t.address,
524
+ type: meta?.type ?? t.labels?.[LABEL_TYPE] ?? "general-purpose",
525
+ model: meta?.model,
526
+ thinking: meta?.thinking,
527
+ cwd: meta?.cwd ?? t.cwd ?? "",
528
+ status: t.status?.state === "blocked" ? "blocked" : working ? "running" : "completed",
529
+ background: true,
530
+ startedAt: meta?.createdAt ?? Date.now(),
531
+ endedAt: working ? undefined : Date.now(),
532
+ result: st?.last?.text,
533
+ error: st?.last?.status === "error" ? st.last.error : undefined,
534
+ activity: st?.activity,
535
+ sessionId: st?.sessionId,
536
+ live: true,
537
+ notify: true,
538
+ consumed: !working,
539
+ baseline: st?.seq ?? 0,
540
+ };
541
+ this.add(rec);
542
+ this.emit(rec, undefined);
543
+ return rec;
544
+ }
545
+ }
@@ -0,0 +1,71 @@
1
+ /**
2
+ * Turns what the model asked for (`"sonnet"`, `"anthropic/claude-sonnet-5-5"`,
3
+ * `"gpt-6.1-sol"`) into one `provider/id` from the parent's model registry,
4
+ * so a typo fails in the parent with a useful list instead of in a child
5
+ * terminal nobody is looking at.
6
+ */
7
+
8
+ export const THINKING_LEVELS = ["off", "minimal", "low", "medium", "high", "xhigh", "max"] as const;
9
+ export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
10
+
11
+ export const isThinkingLevel = (v: unknown): v is ThinkingLevel =>
12
+ typeof v === "string" && (THINKING_LEVELS as readonly string[]).includes(v);
13
+
14
+ export interface ModelLike {
15
+ provider: string;
16
+ id: string;
17
+ name?: string;
18
+ }
19
+
20
+ export type ModelResolution = { ok: true; model: ModelLike } | { ok: false; error: string };
21
+
22
+ const key = (m: ModelLike) => `${m.provider}/${m.id}`;
23
+ const norm = (s: string) => s.toLowerCase().replace(/[\s_.]+/g, "-");
24
+
25
+ /** Natural order: `claude-sonnet-5-5` after `claude-sonnet-5`, `gpt-6.10` after `gpt-6.9`. */
26
+ export function naturalCompare(a: string, b: string): number {
27
+ return a.localeCompare(b, "en", { numeric: true, sensitivity: "base" });
28
+ }
29
+
30
+ export interface ResolveOptions {
31
+ /** The session's scoped models (`enabledModels` / `--models`): preferred among several matches. */
32
+ scoped?: readonly ModelLike[];
33
+ /** The parent's provider: preferred next. */
34
+ provider?: string;
35
+ }
36
+
37
+ /**
38
+ * `available` are the models with credentials. Among several matches the
39
+ * scoped ones win, then the parent's provider, then the newest-looking id
40
+ * (natural order, highest first).
41
+ */
42
+ export function resolveModel(query: string, available: readonly ModelLike[], opts: ResolveOptions = {}): ModelResolution {
43
+ const scoped = new Set((opts.scoped ?? []).map(key));
44
+ const q = query.trim();
45
+ if (!q) return { ok: false, error: "empty model" };
46
+ const slash = q.indexOf("/");
47
+ if (slash > 0) {
48
+ const provider = q.slice(0, slash);
49
+ const id = q.slice(slash + 1);
50
+ const exact = available.find((m) => m.provider === provider && m.id === id);
51
+ if (exact) return { ok: true, model: exact };
52
+ }
53
+ const byId = available.filter((m) => m.id === q);
54
+ const rank = (m: ModelLike) => (scoped.has(key(m)) ? 0 : 2) + (m.provider === opts.provider ? 0 : 1);
55
+ const pick = (list: readonly ModelLike[]): ModelLike =>
56
+ [...list].sort((a, b) => rank(a) - rank(b) || naturalCompare(b.id, a.id) || key(a).localeCompare(key(b)))[0]!;
57
+ if (byId.length) return { ok: true, model: pick(byId) };
58
+
59
+ const nq = norm(q);
60
+ const fuzzy = available.filter(
61
+ (m) => norm(key(m)).includes(nq) || norm(m.id).includes(nq) || (m.name ? norm(m.name).includes(nq) : false),
62
+ );
63
+ if (fuzzy.length) return { ok: true, model: pick(fuzzy) };
64
+
65
+ const list = available.map(key).sort();
66
+ const shown = list.slice(0, 30).join(", ");
67
+ return {
68
+ ok: false,
69
+ error: `Unknown model "${q}". Available: ${shown}${list.length > 30 ? `, … (${list.length - 30} more)` : ""}`,
70
+ };
71
+ }
@@ -0,0 +1,86 @@
1
+ /**
2
+ * What the tool or an RPC caller asked for → a launchable SpawnSpec:
3
+ * agent type, model, effort and folder resolved against the parent session.
4
+ */
5
+
6
+ import { statSync } from "node:fs";
7
+ import { isAbsolute, relative, resolve } from "node:path";
8
+ import { type AgentType, DEFAULT_TYPE, findType } from "./agent-types.ts";
9
+ import type { SpawnSpec } from "./manager.ts";
10
+ import { isThinkingLevel, type ModelLike, resolveModel, THINKING_LEVELS } from "./models.ts";
11
+
12
+ export interface SpawnInput {
13
+ prompt: string;
14
+ description: string;
15
+ subagent_type?: string;
16
+ model?: string;
17
+ thinking?: string;
18
+ cwd?: string;
19
+ background?: boolean;
20
+ notify?: boolean;
21
+ }
22
+
23
+ export interface PrepareContext {
24
+ cwd: string;
25
+ types: Map<string, AgentType>;
26
+ available: readonly ModelLike[];
27
+ scoped?: readonly ModelLike[];
28
+ currentModel?: ModelLike;
29
+ currentThinking?: string;
30
+ projectTrusted?: boolean;
31
+ }
32
+
33
+ const inside = (child: string, parent: string): boolean => {
34
+ const rel = relative(parent, child);
35
+ return rel === "" || (!rel.startsWith("..") && !isAbsolute(rel));
36
+ };
37
+
38
+ export function prepareSpawn(input: SpawnInput, pc: PrepareContext): SpawnSpec {
39
+ const prompt = input.prompt?.trim();
40
+ if (!prompt) throw new Error("prompt is empty");
41
+ const description = input.description?.trim() || prompt.split("\n")[0]!.slice(0, 40);
42
+
43
+ const type = findType(pc.types, input.subagent_type);
44
+ if (!type) {
45
+ throw new Error(
46
+ `Unknown subagent_type "${input.subagent_type}". Available: ${[...pc.types.keys()].join(", ") || DEFAULT_TYPE}`,
47
+ );
48
+ }
49
+
50
+ let model: string | undefined;
51
+ const wanted = input.model?.trim() || type.model;
52
+ if (wanted) {
53
+ const r = resolveModel(wanted, pc.available, { scoped: pc.scoped, provider: pc.currentModel?.provider });
54
+ if (!r.ok) throw new Error(r.error);
55
+ model = `${r.model.provider}/${r.model.id}`;
56
+ } else if (pc.currentModel) {
57
+ model = `${pc.currentModel.provider}/${pc.currentModel.id}`;
58
+ }
59
+
60
+ const thinking = input.thinking?.trim() || type.thinking || pc.currentThinking;
61
+ if (thinking !== undefined && !isThinkingLevel(thinking)) {
62
+ throw new Error(`Unknown thinking level "${thinking}". Use one of: ${THINKING_LEVELS.join(", ")}`);
63
+ }
64
+
65
+ const cwd = input.cwd?.trim() ? resolve(pc.cwd, input.cwd.trim().replace(/^@/, "")) : pc.cwd;
66
+ let isDir = false;
67
+ try {
68
+ isDir = statSync(cwd).isDirectory();
69
+ } catch {
70
+ isDir = false;
71
+ }
72
+ if (!isDir) throw new Error(`cwd is not a folder: ${cwd}`);
73
+
74
+ const background = input.background === true;
75
+ return {
76
+ prompt,
77
+ description,
78
+ type,
79
+ model,
80
+ thinking,
81
+ cwd,
82
+ background,
83
+ notify: input.notify ?? background,
84
+ trust: pc.projectTrusted === undefined || !inside(cwd, pc.cwd) ? undefined : pc.projectTrusted ? "yes" : "no",
85
+ };
86
+ }