pi-subagent-manager 0.1.1 → 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.
package/src/runtime.ts CHANGED
@@ -1,6 +1,6 @@
1
1
  import path from "node:path";
2
2
  import { existsSync } from "node:fs";
3
- import { mkdir, realpath } from "node:fs/promises";
3
+ import { mkdir, readFile, realpath } from "node:fs/promises";
4
4
  import {
5
5
  createAgentSession,
6
6
  DefaultResourceLoader,
@@ -18,9 +18,116 @@ import {
18
18
  DurableMailbox,
19
19
  } from "./mailbox.ts";
20
20
  import { selectTools } from "./config.ts";
21
- import { THINKING_LEVELS, type DriverFactory, type ThinkingLevel } from "./types.ts";
21
+ import { modelIdentity, getModelPreferences, selectPreferredModel } from "./models.ts";
22
+ import {
23
+ THINKING_LEVELS,
24
+ type DriverFactory,
25
+ type DriverOptions,
26
+ type ThinkingLevel,
27
+ } from "./types.ts";
22
28
 
23
29
  const BUILTINS = ["read", "bash", "powershell", "edit", "write", "grep", "find", "ls"];
30
+ /** Persisted before transcript messages so older-leaf restores still carry ownership. */
31
+ const THREAD_OWNERSHIP_TYPE = "pi-subagent:thread:v1";
32
+ const SESSION_FILE_ERROR =
33
+ "Subagent sessionFile must be a JSONL file inside this root's session directory";
34
+ type ScopedModel = ExtensionContext["scopedModels"][number];
35
+ interface ThreadOwnership {
36
+ rootId: string;
37
+ threadPath: string;
38
+ }
39
+
40
+ function parseModelIdentity(identity: string): { provider: string; id: string } {
41
+ const slash = identity.indexOf("/");
42
+ return { provider: identity.slice(0, slash), id: identity.slice(slash + 1) };
43
+ }
44
+
45
+ function scopedModelsKey(scopedModels: readonly ScopedModel[]): string {
46
+ return scopedModels
47
+ .map(({ model, thinkingLevel }) => `${modelIdentity(model)}\0${thinkingLevel ?? ""}`)
48
+ .join("\n");
49
+ }
50
+
51
+ function isJsonlWithin(directory: string, file: string): boolean {
52
+ const relative = path.relative(directory, file);
53
+ return (
54
+ !!relative &&
55
+ !relative.startsWith(`..${path.sep}`) &&
56
+ relative !== ".." &&
57
+ !path.isAbsolute(relative) &&
58
+ file.endsWith(".jsonl")
59
+ );
60
+ }
61
+
62
+ async function tryRealpath(target: string): Promise<string | undefined> {
63
+ try {
64
+ return await realpath(target);
65
+ } catch (error) {
66
+ const code = (error as NodeJS.ErrnoException).code;
67
+ if (code === "ENOENT" || code === "ENOTDIR") return undefined;
68
+ throw error;
69
+ }
70
+ }
71
+
72
+ function ownershipFromTranscript(content: string): ThreadOwnership | undefined {
73
+ for (const line of content.split("\n")) {
74
+ if (!line.trim()) continue;
75
+ let parsed: unknown;
76
+ try {
77
+ parsed = JSON.parse(line);
78
+ } catch {
79
+ continue;
80
+ }
81
+ if (!parsed || typeof parsed !== "object") continue;
82
+ const entry = parsed as { type?: unknown; customType?: unknown; data?: unknown };
83
+ if (entry.type !== "custom" || entry.customType !== THREAD_OWNERSHIP_TYPE) continue;
84
+ const data = entry.data;
85
+ if (!data || typeof data !== "object") return undefined;
86
+ const { rootId, threadPath } = data as { rootId?: unknown; threadPath?: unknown };
87
+ if (typeof rootId !== "string" || typeof threadPath !== "string") return undefined;
88
+ return { rootId, threadPath };
89
+ }
90
+ return undefined;
91
+ }
92
+
93
+ /** Orchestrator file for /root and independent roots; nested parents supply their own file. */
94
+ function resolveParentSession(
95
+ options: DriverOptions,
96
+ rootSessionFile: string | undefined,
97
+ ): string | undefined {
98
+ if (options.parentSessionFile) return options.parentSessionFile;
99
+ if (!options.parentPath || options.parentPath === "/root") return rootSessionFile;
100
+ return undefined;
101
+ }
102
+
103
+ async function assertAcceptedSessionFile(
104
+ sessionFile: string,
105
+ sessionDir: string,
106
+ legacyDir: string,
107
+ rootId: string,
108
+ threadPath: string,
109
+ signal: AbortSignal,
110
+ ): Promise<void> {
111
+ signal.throwIfAborted();
112
+ const sharedDir = await realpath(sessionDir);
113
+ signal.throwIfAborted();
114
+ const file = await tryRealpath(sessionFile);
115
+ signal.throwIfAborted();
116
+ const legacyDirReal = await tryRealpath(legacyDir);
117
+ signal.throwIfAborted();
118
+ // Legacy root-scoped transcripts stay valid, including files nested under that directory.
119
+ if (file && legacyDirReal && isJsonlWithin(legacyDirReal, file)) return;
120
+ if (!file || path.dirname(file) !== sharedDir || !file.endsWith(".jsonl")) {
121
+ throw new Error(SESSION_FILE_ERROR);
122
+ }
123
+ const ownership = ownershipFromTranscript(await readFile(file, { encoding: "utf8", signal }));
124
+ signal.throwIfAborted();
125
+ if (!ownership || ownership.rootId !== rootId || ownership.threadPath !== threadPath) {
126
+ throw new Error(
127
+ "Subagent sessionFile ownership metadata does not match this rootId and thread path",
128
+ );
129
+ }
130
+ }
24
131
 
25
132
  /** Isolated SDK sessions; neither external extensions nor the CLI's MCP factories are loaded. */
26
133
  export function createDriverFactory(getRootContext: () => ExtensionContext): DriverFactory {
@@ -33,36 +140,40 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
33
140
  if (!/^[A-Za-z0-9][A-Za-z0-9_-]*$/.test(rootId))
34
141
  throw new Error("Unsafe root session id for subagent storage");
35
142
  const agentDir = getAgentDir();
36
- const sessionDir = path.join(agentDir, "subagents", rootId);
143
+ const sessionDir = ctx.sessionManager.getSessionDir();
144
+ const legacyDir = path.join(agentDir, "subagents", rootId);
37
145
  options.signal.throwIfAborted();
38
146
  await mkdir(sessionDir, { recursive: true });
39
147
  options.signal.throwIfAborted();
40
148
  let sessionManager: SessionManager;
41
149
  if (options.sessionFile) {
42
- options.signal.throwIfAborted();
43
- const directory = await realpath(sessionDir);
44
- options.signal.throwIfAborted();
45
- const file = await realpath(options.sessionFile);
46
- options.signal.throwIfAborted();
47
- const relative = path.relative(directory, file);
48
- if (
49
- !relative ||
50
- relative.startsWith(`..${path.sep}`) ||
51
- relative === ".." ||
52
- path.isAbsolute(relative) ||
53
- !file.endsWith(".jsonl")
54
- ) {
55
- throw new Error(
56
- "Subagent sessionFile must be a JSONL file inside this root's subagent sessions directory",
57
- );
58
- }
150
+ await assertAcceptedSessionFile(
151
+ options.sessionFile,
152
+ sessionDir,
153
+ legacyDir,
154
+ rootId,
155
+ options.path,
156
+ options.signal,
157
+ );
158
+ // Open the caller path, not its realpath, so retained sessionFile identity is stable.
59
159
  sessionManager = SessionManager.open(path.resolve(options.sessionFile), sessionDir, ctx.cwd);
60
160
  if (options.sessionLeafId !== undefined) {
61
161
  if (options.sessionLeafId === null) sessionManager.resetLeaf();
62
162
  else sessionManager.branch(options.sessionLeafId);
63
163
  }
64
164
  } else {
65
- sessionManager = SessionManager.create(ctx.cwd, sessionDir);
165
+ const parentSession = resolveParentSession(options, ctx.sessionManager.getSessionFile());
166
+ sessionManager = SessionManager.create(
167
+ ctx.cwd,
168
+ sessionDir,
169
+ parentSession ? { parentSession } : undefined,
170
+ );
171
+ // Before transcript messages so an older restored leaf still has name and ownership as ancestors.
172
+ sessionManager.appendSessionInfo(`${options.type.name} ${options.path}`);
173
+ sessionManager.appendCustomEntry(THREAD_OWNERSHIP_TYPE, {
174
+ rootId,
175
+ threadPath: options.path,
176
+ });
66
177
  for (const message of options.inherited) {
67
178
  // Summary messages are projections, not appendable SDK session entries.
68
179
  if (message.role === "compactionSummary" || message.role === "branchSummary") {
@@ -88,6 +199,30 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
88
199
  }
89
200
  }
90
201
  }
202
+ const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
203
+ const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
204
+ const modelPreferences = getModelPreferences(options.type);
205
+ const normalizeScopedModels = (
206
+ scopedModels: ExtensionContext["scopedModels"] | null | undefined,
207
+ ): readonly ScopedModel[] => scopedModels ?? [];
208
+ const selectScopedPreference = (scopedModels: readonly ScopedModel[]) => {
209
+ try {
210
+ return selectPreferredModel(options.type, scopedModels);
211
+ } catch (error) {
212
+ if (scopedModels.length === 0 && error instanceof Error && !error.message.includes("[]"))
213
+ throw new Error(`${error.message} Current /scoped-models scope: [].`);
214
+ throw error;
215
+ }
216
+ };
217
+ const initialScopedModels = normalizeScopedModels(ctx.scopedModels);
218
+ let provider = parent?.provider ?? ctx.model?.provider;
219
+ let id = parent?.id ?? ctx.model?.id;
220
+ if (modelPreferences !== undefined) {
221
+ ({ provider, id } = parseModelIdentity(selectScopedPreference(initialScopedModels)!));
222
+ } else if (restored?.model) {
223
+ provider = restored.model.provider;
224
+ id = restored.model.modelId;
225
+ }
91
226
  options.signal.throwIfAborted();
92
227
  const runtime = await ModelRuntime.create({
93
228
  authPath: path.join(agentDir, "auth.json"),
@@ -103,40 +238,41 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
103
238
  if (native) runtime.registerNativeProvider(native);
104
239
  if (config) runtime.registerProvider(providerId, config);
105
240
  }
106
- const parent = options.parentPath ? resolved.get(`${rootId}:${options.parentPath}`) : undefined;
107
- let provider = parent?.provider ?? ctx.model?.provider;
108
- let id = parent?.id ?? ctx.model?.id;
109
- if (options.type.model) {
110
- const slash = options.type.model.indexOf("/");
111
- if (slash < 1 || slash === options.type.model.length - 1)
112
- throw new Error("Agent model must be provider/model-id");
113
- provider = options.type.model.slice(0, slash);
114
- id = options.type.model.slice(slash + 1);
115
- }
116
- const restored = options.sessionFile ? sessionManager.buildSessionContext() : undefined;
117
- if (restored?.model) {
118
- provider = restored.model.provider;
119
- id = restored.model.modelId;
120
- }
121
- options.signal.throwIfAborted();
122
- if (provider && ctx.modelRegistry.getProviderAuthStatus(provider).source === "runtime") {
123
- const apiKey = await ctx.modelRegistry.getApiKeyForProvider(provider);
241
+ const mirrorRuntimeAuth = async (providerId: string) => {
242
+ options.signal.throwIfAborted();
243
+ if (ctx.modelRegistry.getProviderAuthStatus(providerId).source !== "runtime") return;
244
+ const apiKey = await ctx.modelRegistry.getApiKeyForProvider(providerId);
124
245
  options.signal.throwIfAborted();
125
246
  if (apiKey !== undefined)
126
- await runtime.setRuntimeApiKey(provider, apiKey, { signal: options.signal });
247
+ await runtime.setRuntimeApiKey(providerId, apiKey, { signal: options.signal });
127
248
  options.signal.throwIfAborted();
128
- }
129
- const rootModel = provider && id ? ctx.modelRegistry.find(provider, id) : undefined;
130
- if (rootModel?.api === "pi-virtual") {
131
- throw new Error(
132
- `Virtual model ${provider}/${id} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`,
133
- );
134
- }
135
- const model = provider && id ? runtime.getModel(provider, id) : undefined;
136
- if (!model)
137
- throw new Error(
138
- `Subagent model ${provider ?? "(unset)"}/${id ?? "(unset)"} is unavailable; select a physical model in the root or agent type`,
139
- );
249
+ };
250
+ const resolveRuntimeModel = async (
251
+ providerId: string | undefined,
252
+ modelId: string | undefined,
253
+ scopedModels: readonly ScopedModel[],
254
+ ) => {
255
+ if (!providerId || !modelId)
256
+ throw new Error(
257
+ `Subagent model ${providerId ?? "(unset)"}/${modelId ?? "(unset)"} is unavailable; select a physical model in the root or agent type`,
258
+ );
259
+ await mirrorRuntimeAuth(providerId);
260
+ const sourceModel =
261
+ scopedModels.find(({ model }) => model.provider === providerId && model.id === modelId)
262
+ ?.model ?? ctx.modelRegistry.find(providerId, modelId);
263
+ if (sourceModel?.api === "pi-virtual") {
264
+ throw new Error(
265
+ `Virtual model ${providerId}/${modelId} cannot be reproduced through the public registry API. Set this agent type's model to a physical provider/model-id.`,
266
+ );
267
+ }
268
+ const runtimeModel = runtime.getModel(providerId, modelId);
269
+ if (!runtimeModel)
270
+ throw new Error(
271
+ `Subagent model ${providerId}/${modelId} is unavailable; select a physical model in the root or agent type`,
272
+ );
273
+ return runtimeModel;
274
+ };
275
+ const model = await resolveRuntimeModel(provider, id, initialScopedModels);
140
276
  const savedThinking =
141
277
  restored && THINKING_LEVELS.includes(restored.thinkingLevel as ThinkingLevel)
142
278
  ? (restored.thinkingLevel as ThinkingLevel)
@@ -171,6 +307,11 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
171
307
  ? `Your lexical parent is ${options.parentPath}; inherited conversation comes only from that parent.`
172
308
  : "You are an independent root thread with no inherited history.",
173
309
  "When finished, give your final answer normally so it can be handed back. To retain unfinished work without a final answer, call agent_pause (if available), then stop; resume only when instructed.",
310
+ ...(allowed.has("agent_spawn") && allowed.has("agent_wait")
311
+ ? [
312
+ "For independent parallel work, launch all siblings with agent_spawn wait:false before calling agent_wait. Children share the main conversation's depth and concurrency limits; waiting parents count as active. Do not delegate work beyond your assigned scope.",
313
+ ]
314
+ : []),
174
315
  ].join("\n\n"),
175
316
  appendSystemPromptOverride: () => [],
176
317
  extensionFactories: [
@@ -194,13 +335,72 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
194
335
  modelRuntime: runtime,
195
336
  model,
196
337
  thinkingLevel,
338
+ scopedModels: [...initialScopedModels],
197
339
  settingsManager,
198
340
  resourceLoader: loader,
199
341
  sessionManager,
200
342
  tools: toolNames,
201
343
  customTools: options.tools.filter((tool) => allowed.has(tool.name)),
202
344
  });
345
+ let lastScopedModelsKey = "";
346
+ const updateResolved = () => {
347
+ const currentModel = session.model;
348
+ if (!currentModel) throw new Error(`Subagent ${options.path} has no selected model`);
349
+ resolved.set(`${rootId}:${options.path}`, {
350
+ provider: currentModel.provider,
351
+ id: currentModel.id,
352
+ thinking: session.thinkingLevel,
353
+ });
354
+ };
355
+ const assertScopedRequestAuthorized = (
356
+ currentIdentity: string | undefined,
357
+ liveScopedModels: readonly ScopedModel[],
358
+ ) => {
359
+ if (modelPreferences === undefined) return;
360
+ const preferredIdentity = selectScopedPreference(liveScopedModels);
361
+ if (!preferredIdentity) return;
362
+ if (!currentIdentity) throw new Error(`Subagent ${options.path} has no selected model`);
363
+ if (currentIdentity !== preferredIdentity) {
364
+ throw new Error(
365
+ `Agent type ${JSON.stringify(options.type.name)} scope changed for subagent ${JSON.stringify(options.path)}: current model is ${currentIdentity} but preferred is ${preferredIdentity}; resume agent to use ${preferredIdentity}.`,
366
+ );
367
+ }
368
+ };
369
+ const assertCurrentModelAuthorized = () => {
370
+ const currentModel = session.model;
371
+ assertScopedRequestAuthorized(
372
+ currentModel ? modelIdentity(currentModel) : undefined,
373
+ normalizeScopedModels(getRootContext().scopedModels),
374
+ );
375
+ };
376
+ const enforceScopedModelPolicy = async () => {
377
+ const liveScopedModels = normalizeScopedModels(getRootContext().scopedModels);
378
+ const key = scopedModelsKey(liveScopedModels);
379
+ if (key !== lastScopedModelsKey) {
380
+ session.setScopedModels([...liveScopedModels]);
381
+ lastScopedModelsKey = key;
382
+ }
383
+ if (modelPreferences === undefined) {
384
+ updateResolved();
385
+ return;
386
+ }
387
+ const preferredIdentity = selectScopedPreference(liveScopedModels);
388
+ if (!preferredIdentity) {
389
+ updateResolved();
390
+ return;
391
+ }
392
+ const currentModel = session.model;
393
+ if (!currentModel || modelIdentity(currentModel) !== preferredIdentity) {
394
+ const { provider: preferredProvider, id: preferredId } =
395
+ parseModelIdentity(preferredIdentity);
396
+ await session.setModel(
397
+ await resolveRuntimeModel(preferredProvider, preferredId, liveScopedModels),
398
+ );
399
+ }
400
+ updateResolved();
401
+ };
203
402
  try {
403
+ await enforceScopedModelPolicy();
204
404
  options.signal.throwIfAborted();
205
405
  await session.bindExtensions({ mode: "print" });
206
406
  options.signal.throwIfAborted();
@@ -208,6 +408,14 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
208
408
  session.dispose();
209
409
  throw error;
210
410
  }
411
+ const streamFunction = session.agent.streamFunction;
412
+ session.agent.streamFunction = async (requestModel, context, streamOptions) => {
413
+ assertScopedRequestAuthorized(
414
+ modelIdentity(requestModel),
415
+ normalizeScopedModels(getRootContext().scopedModels),
416
+ );
417
+ return streamFunction(requestModel, context, streamOptions);
418
+ };
211
419
  const mailbox = new DurableMailbox(sessionManager);
212
420
  const emitCheckpoint = () =>
213
421
  options.onEvent({
@@ -223,6 +431,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
223
431
  emit("activity", BOOTSTRAP_MESSAGE);
224
432
  };
225
433
  const queueAccepted = async (kind: "steer" | "followUp", content: string) => {
434
+ assertCurrentModelAuthorized();
226
435
  ensurePersistedSession();
227
436
  const accepted = mailbox.accept(kind, content);
228
437
  emitCheckpoint();
@@ -266,11 +475,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
266
475
  }
267
476
  return decision || undefined;
268
477
  };
269
- resolved.set(`${rootId}:${options.path}`, {
270
- provider: model.provider,
271
- id: model.id,
272
- thinking: session.thinkingLevel,
273
- });
478
+ updateResolved();
274
479
  let disposed = false;
275
480
  let running = false;
276
481
  let aborted = false;
@@ -313,6 +518,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
313
518
  baseline = session.messages.length;
314
519
  finalOutput = "";
315
520
  try {
521
+ await enforceScopedModelPolicy();
316
522
  await resumePending();
317
523
  await session.prompt(message, { expandPromptTemplates: false });
318
524
  await session.waitForIdle();
@@ -332,6 +538,7 @@ export function createDriverFactory(getRootContext: () => ExtensionContext): Dri
332
538
  emit("error", error instanceof Error ? error.message : String(error));
333
539
  throw error;
334
540
  } finally {
541
+ updateResolved();
335
542
  running = false;
336
543
  }
337
544
  },
@@ -0,0 +1,124 @@
1
+ import { lstatSync, readFileSync } from "node:fs";
2
+ import { join, resolve } from "node:path";
3
+
4
+ export interface ManagerSettings {
5
+ maxLevels: number;
6
+ maxConcurrent: number;
7
+ maxThreads: number;
8
+ }
9
+
10
+ export const DEFAULT_MANAGER_SETTINGS: ManagerSettings = {
11
+ maxLevels: 3,
12
+ maxConcurrent: 16,
13
+ maxThreads: 64,
14
+ };
15
+
16
+ const KEYS = ["maxLevels", "maxConcurrent", "maxThreads"] as const;
17
+ const MAX_LEVELS = 32;
18
+
19
+ function errorCode(error: unknown): string | undefined {
20
+ return typeof error === "object" && error !== null && "code" in error
21
+ ? String((error as { code?: unknown }).code)
22
+ : undefined;
23
+ }
24
+
25
+ function lstatIfPresent(path: string): ReturnType<typeof lstatSync> | undefined {
26
+ try {
27
+ return lstatSync(path);
28
+ } catch (error) {
29
+ if (errorCode(error) === "ENOENT") return undefined;
30
+ throw error;
31
+ }
32
+ }
33
+
34
+ function assertNotSymlinkPath(path: string): ReturnType<typeof lstatSync> | undefined {
35
+ const stat = lstatIfPresent(path);
36
+ if (stat?.isSymbolicLink()) throw new Error(`Unsafe symlink path: ${path}`);
37
+ return stat;
38
+ }
39
+
40
+ function isSupportedKey(key: string): key is (typeof KEYS)[number] {
41
+ return KEYS.includes(key as (typeof KEYS)[number]);
42
+ }
43
+
44
+ function positiveSafeInteger(value: unknown): value is number {
45
+ return typeof value === "number" && Number.isSafeInteger(value) && value > 0;
46
+ }
47
+
48
+ function parseSettings(content: string): Partial<ManagerSettings> {
49
+ let parsed: unknown;
50
+ try {
51
+ parsed = JSON.parse(content);
52
+ } catch (error) {
53
+ const detail = error instanceof Error ? error.message : String(error);
54
+ throw new Error(`Invalid JSON: ${detail}`);
55
+ }
56
+ if (parsed === null || typeof parsed !== "object" || Array.isArray(parsed)) {
57
+ throw new Error("Settings must be a JSON object");
58
+ }
59
+ const record = parsed as Record<string, unknown>;
60
+ for (const key of Object.keys(record)) {
61
+ if (!isSupportedKey(key)) throw new Error(`Unknown settings key: ${key}`);
62
+ }
63
+ const layer: Partial<ManagerSettings> = {};
64
+ for (const key of KEYS) {
65
+ if (!Object.hasOwn(record, key)) continue;
66
+ const value = record[key];
67
+ if (!positiveSafeInteger(value)) throw new Error(`${key} must be a positive safe integer`);
68
+ if (key === "maxLevels" && value > MAX_LEVELS) throw new Error("maxLevels must be <= 32");
69
+ layer[key] = value;
70
+ }
71
+ return layer;
72
+ }
73
+
74
+ interface SettingsLayer {
75
+ filePath: string;
76
+ directories: string[];
77
+ }
78
+
79
+ function layer(base: string, segments: string[]): SettingsLayer {
80
+ let current = resolve(base);
81
+ const directories = [current];
82
+ for (const segment of segments) {
83
+ current = join(current, segment);
84
+ directories.push(current);
85
+ }
86
+ return { filePath: join(current, "settings.json"), directories };
87
+ }
88
+
89
+ function readLayer(entry: SettingsLayer): Partial<ManagerSettings> | undefined {
90
+ for (const directory of entry.directories) {
91
+ const stat = assertNotSymlinkPath(directory);
92
+ if (!stat) return undefined;
93
+ if (!stat.isDirectory())
94
+ throw new Error(`Settings directory must be a directory: ${directory}`);
95
+ }
96
+ const stat = assertNotSymlinkPath(entry.filePath);
97
+ if (!stat) return undefined;
98
+ if (!stat.isFile()) throw new Error(`Settings must be a regular file: ${entry.filePath}`);
99
+ return parseSettings(readFileSync(entry.filePath, "utf8"));
100
+ }
101
+
102
+ function detail(error: unknown): string {
103
+ return error instanceof Error ? error.message : String(error);
104
+ }
105
+
106
+ export function loadManagerSettings(options: {
107
+ cwd: string;
108
+ agentDir: string;
109
+ includeProject: boolean;
110
+ }): { settings: ManagerSettings; diagnostics: string[] } {
111
+ const diagnostics: string[] = [];
112
+ const settings: ManagerSettings = { ...DEFAULT_MANAGER_SETTINGS };
113
+ const layers = [layer(options.agentDir, ["subagent-manager"])];
114
+ if (options.includeProject) layers.push(layer(options.cwd, [".pi", "agent", "subagent-manager"]));
115
+ for (const entry of layers) {
116
+ try {
117
+ const parsed = readLayer(entry);
118
+ if (parsed !== undefined) Object.assign(settings, parsed);
119
+ } catch (error) {
120
+ diagnostics.push(`${entry.filePath}: ${detail(error)}`);
121
+ }
122
+ }
123
+ return { settings, diagnostics };
124
+ }
package/src/tools.ts CHANGED
@@ -1,5 +1,6 @@
1
1
  import { Type } from "typebox";
2
2
  import type { ToolDefinition } from "@earendil-works/pi-coding-agent";
3
+ import { getModelPreferences } from "./models.ts";
3
4
  import type { ThreadManager } from "./manager.ts";
4
5
  import type { AgentType, ThreadView } from "./types.ts";
5
6
 
@@ -43,10 +44,10 @@ export function agentTools(
43
44
  Type.Object({}),
44
45
  () =>
45
46
  result(
46
- getTypes().map(({ name, description, model, thinkingLevel, color }) => ({
47
+ getTypes().map(({ name, description, thinkingLevel, color, ...type }) => ({
47
48
  name,
48
49
  description,
49
- model,
50
+ models: getModelPreferences(type),
50
51
  thinkingLevel,
51
52
  color,
52
53
  })),
@@ -54,7 +55,7 @@ export function agentTools(
54
55
  ),
55
56
  make(
56
57
  "agent_spawn",
57
- "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
58
+ "Spawn a named child. The lexical parent, NOT the caller, supplies a context snapshot. /root is the main thread; independent roots have no inherited context. Foreground waits by default; wait:false runs detached. For parallel work, spawn every independent sibling with wait:false before calling agent_wait; child agents with delegation tools should do the same. Existing paths are retained and can be resumed with agent_steer. Use agent_types to discover current types.",
58
59
  Type.Object({ path, type: text, task: text, wait: Type.Optional(Type.Boolean()) }),
59
60
  async (params, signal) => result(compact(await threads().spawn(params, signal))),
60
61
  ),
package/src/types.ts CHANGED
@@ -6,8 +6,11 @@ export type ThinkingLevel = (typeof THINKING_LEVELS)[number];
6
6
  export interface AgentType {
7
7
  name: string;
8
8
  description: string;
9
+ models?: string[];
10
+ /** @deprecated Use ordered models instead. */
9
11
  model?: string;
10
12
  thinkingLevel?: ThinkingLevel;
13
+ /** Pi semantic token used as the agent name pill's background. */
11
14
  color?: string;
12
15
  tools?: { allow?: string[]; block?: string[] };
13
16
  systemPrompt: string;
@@ -58,6 +61,8 @@ export interface DriverOptions {
58
61
  shouldPause(): boolean;
59
62
  parentPath: string | null;
60
63
  sessionFile?: string;
64
+ /** Retained transcript of a nested lexical parent. Absent for /root and independent roots. */
65
+ parentSessionFile?: string;
61
66
  sessionLeafId?: string | null;
62
67
  signal: AbortSignal;
63
68
  }
@@ -108,6 +113,9 @@ export interface ManagerOptions {
108
113
  getType(name: string): AgentType;
109
114
  toolsFor(path: string): ToolDefinition[];
110
115
  onEvent?(event: ThreadEvent): void;
116
+ /** Maximum levels including the main conversation as L1; defaults to 3. */
117
+ maxLevels?: number;
118
+ /** @deprecated Internal legacy path-depth override; prefer maxLevels. */
111
119
  maxDepth?: number;
112
120
  maxThreads?: number;
113
121
  maxConcurrent?: number;