@xzzpig/pi-subagents 0.18.0 → 0.19.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/CHANGELOG.md +69 -0
- package/README.md +1 -1
- package/docs/agents.md +18 -12
- package/docs/configuration.md +66 -9
- package/docs/extension-api.md +5 -4
- package/docs/missions.md +13 -13
- package/docs/models.md +2 -2
- package/docs/observability.md +2 -2
- package/docs/standalone-background.md +1 -1
- package/docs/tool-reference.md +63 -86
- package/docs/workflows.md +170 -172
- package/node_modules/@xzzpig/pi-components/package.json +4 -4
- package/package.json +6 -6
- package/prompts/review-loop.md +1 -1
- package/skills/council-mode/SKILL.md +1 -1
- package/skills/pi-subagents/SKILL.md +12 -5
- package/skills/pi-subagents/references/constraints-and-recipes.md +3 -3
- package/skills/pi-subagents/references/execution-controls.md +68 -67
- package/skills/pi-subagents/references/management-authoring-rpc.md +2 -2
- package/skills/pi-subagents/references/multi-lane-orchestration.md +1 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +45 -48
- package/src/agents/advertised-agent-prompt.ts +21 -41
- package/src/agents/agent-management.ts +2 -2
- package/src/agents/agents.ts +7 -0
- package/src/api/preflight.ts +67 -62
- package/src/extension/config.ts +12 -4
- package/src/extension/control-notices.ts +3 -0
- package/src/extension/doctor.ts +1 -0
- package/src/extension/fanout-child.ts +12 -3
- package/src/extension/herdr-pi-bridge.ts +2 -0
- package/src/extension/index.ts +68 -159
- package/src/extension/public-execution.ts +69 -35
- package/src/extension/reply-workflow-script.ts +58 -0
- package/src/extension/rpc.ts +29 -10
- package/src/extension/schemas.ts +36 -133
- package/src/extension/tool-activation.ts +57 -108
- package/src/extension/tool-description.ts +62 -27
- package/src/extension/upgrade-notice.ts +40 -0
- package/src/integrations/herdr-status.ts +19 -3
- package/src/intercom/native-supervisor-channel.ts +4 -1
- package/src/runs/background/async-execution.ts +58 -53
- package/src/runs/background/async-job-tracker.ts +63 -22
- package/src/runs/background/async-retention.ts +46 -16
- package/src/runs/background/await-async-run.ts +76 -0
- package/src/runs/background/chain-root-attachment.ts +4 -4
- package/src/runs/background/control-channel.ts +18 -2
- package/src/runs/background/notify.ts +5 -0
- package/src/runs/background/run-child-session.ts +4 -1
- package/src/runs/background/run-status.ts +6 -0
- package/src/runs/background/runner-aliases.ts +30 -2
- package/src/runs/background/runner-child-launch.ts +3 -0
- package/src/runs/background/scheduled-runs.ts +5 -5
- package/src/runs/background/subagent-runner.ts +15 -1
- package/src/runs/foreground/async-stop-action.ts +17 -3
- package/src/runs/foreground/execution.ts +130 -125
- package/src/runs/foreground/subagent-executor.ts +487 -288
- package/src/runs/shared/async-status-projection.ts +5 -0
- package/src/runs/shared/child-launch.ts +15 -2
- package/src/runs/shared/child-session.ts +92 -6
- package/src/runs/shared/child-tool-plan.ts +15 -3
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/mcp-config-sources.ts +2 -1
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +103 -11
- package/src/runs/shared/model-resolution.ts +29 -9
- package/src/runs/shared/model-scope.ts +28 -9
- package/src/runs/shared/nested-events.ts +55 -55
- package/src/runs/shared/parallel-utils.ts +2 -0
- package/src/runs/shared/pi-spawn.ts +7 -95
- package/src/runs/shared/subagent-prompt-runtime.ts +2 -0
- package/src/runs/shared/worktree.ts +1 -1
- package/src/shared/disabled-features.ts +123 -0
- package/src/shared/extension-context.ts +13 -0
- package/src/shared/model-info.ts +9 -0
- package/src/shared/settings.ts +1 -1
- package/src/shared/types.ts +21 -0
- package/src/slash/prompt-template-bridge.ts +2 -2
- package/src/slash/slash-commands.ts +10 -5
- package/src/slash/subagents-admin.ts +24 -24
- package/src/tui/fleet-status.ts +14 -6
- package/src/tui/fleet.ts +14 -2
- package/src/tui/render.ts +113 -52
- package/src/tui/running-tone.ts +28 -0
- package/src/watchdog/diff-tool.ts +23 -9
- package/src/watchdog/register-child.ts +3 -3
- package/src/watchdog/register-main.ts +3 -3
- package/src/watchdog/review.ts +2 -2
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/workflows/chat-progress.ts +2 -2
- package/src/workflows/scripted-workflow.ts +117 -37
- package/src/workflows/structured-workflow-scripts.ts +177 -0
- package/src/workflows/workflow-checklist.ts +6 -0
- package/src/workflows/workflow-receipt.ts +8 -2
- package/src/workflows/workflow-resources.ts +37 -12
- package/src/workflows/workflow-reuse.ts +120 -0
- package/src/workflows/workflow-revival.ts +123 -0
|
@@ -1,5 +1,6 @@
|
|
|
1
1
|
import { sanitizeDisplayText, truncateDisplayText } from "../../shared/display-text.ts";
|
|
2
2
|
import { formatModelThinking } from "../../shared/formatters.ts";
|
|
3
|
+
import { childThinkingLevel, type ThinkingLevel } from "../../shared/model-info.ts";
|
|
3
4
|
import type { AsyncJobState, AsyncJobStep, HostStepFreshness, HostStepMonitorKind, HostStepNode, HostStepState, HostStepVerdict, NestedRunSummary, NestedStepSummary, SubagentRunMode, WorkflowGraphSnapshot, WorkflowPreflightLane, WorkflowPreflight } from "../../shared/types.ts";
|
|
4
5
|
import { HOST_STEP_MAX_COUNT, HOST_STEP_MAX_DETAIL_CHARS, HOST_STEP_MAX_LABEL_CHARS, HOST_STEP_MAX_PROVIDER_CHARS, HOST_STEP_MAX_REASON_CHARS, HOST_STEP_MAX_REF_CHARS, HOST_STEP_MAX_ROLE_CHARS, HOST_STEP_MAX_TARGET_CHARS, hostStepReportName, parseHostStepNode, validHostStepNodes } from "./host-step-status.ts";
|
|
5
6
|
import { workflowPreflightLaneForRuntimeKey } from "../../workflows/workflow-preflight.ts";
|
|
@@ -106,6 +107,8 @@ export interface AsyncStatusWorkflowRow {
|
|
|
106
107
|
kind?: HostStepMonitorKind;
|
|
107
108
|
context?: AsyncJobStep["context"];
|
|
108
109
|
modelThinking?: string;
|
|
110
|
+
/** Thinking level of the child a child row stands for. */
|
|
111
|
+
thinking?: ThinkingLevel;
|
|
109
112
|
activity?: string;
|
|
110
113
|
startedAt?: number;
|
|
111
114
|
endedAt?: number;
|
|
@@ -623,12 +626,14 @@ export function projectAsyncWorkflowRows(
|
|
|
623
626
|
|
|
624
627
|
function projectLoadedWorkflowRow(step: AsyncJobStep, index: number, preflight?: WorkflowPreflightLane): AsyncStatusWorkflowRow {
|
|
625
628
|
const modelThinking = formatModelThinking(step.model, step.thinking) || undefined;
|
|
629
|
+
const thinking = childThinkingLevel(step);
|
|
626
630
|
const activity = workflowStepActivity(step);
|
|
627
631
|
return {
|
|
628
632
|
name: workflowStepName(step, index),
|
|
629
633
|
state: step.status,
|
|
630
634
|
...(step.context ? { context: step.context } : {}),
|
|
631
635
|
...(modelThinking ? { modelThinking } : {}),
|
|
636
|
+
...(thinking ? { thinking } : {}),
|
|
632
637
|
...(activity ? { activity } : {}),
|
|
633
638
|
...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
|
|
634
639
|
...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
|
|
@@ -17,7 +17,7 @@ import {
|
|
|
17
17
|
type HerdrMachineReference,
|
|
18
18
|
} from "../../shared/types.ts";
|
|
19
19
|
import type { NestedPathEntry } from "./nested-path.ts";
|
|
20
|
-
import type
|
|
20
|
+
import { extensionOnlyMcpServers, type McpRuntimeSnapshotHost, type ResolvedMcpDirectToolSelection } from "./mcp-direct-tool-allowlist.ts";
|
|
21
21
|
import type { PermissionRules } from "./permissions.ts";
|
|
22
22
|
import type { StructuredOutputRuntime } from "./structured-output.ts";
|
|
23
23
|
import type { ChildToolDiagnostic } from "./tool-availability.ts";
|
|
@@ -86,6 +86,8 @@ export interface BuildInProcessChildLaunchInput {
|
|
|
86
86
|
requiredExtensions?: RequiredChildExtensionSnapshot;
|
|
87
87
|
systemPrompt?: string | null;
|
|
88
88
|
mcpDirectTools?: string[];
|
|
89
|
+
/** Selections the parent resolved against Pi's built-in MCP, carried to the runner. */
|
|
90
|
+
builtinMcpTools?: ResolvedMcpDirectToolSelection[];
|
|
89
91
|
extensionBindings?: ExtensionBindings;
|
|
90
92
|
cwd: string;
|
|
91
93
|
intercomSessionName?: string;
|
|
@@ -174,7 +176,9 @@ function inheritedCapabilityCeiling(inherited: InheritedChildRuntime | undefined
|
|
|
174
176
|
function childProcessEnv(input: BuildInProcessChildLaunchInput, toolPlan: PiLaunchToolPlan, sandboxEnv?: Record<string, string | undefined>): Record<string, string | undefined> {
|
|
175
177
|
const env: Record<string, string | undefined> = {};
|
|
176
178
|
env[PI_SUBAGENT_EXTENSION_BINDINGS_ENV] = encodeExtensionBindings(input.extensionBindings);
|
|
177
|
-
|
|
179
|
+
// Selectors resolved against Pi's built-in MCP never reach an adapter.
|
|
180
|
+
if (toolPlan.builtinMcpTools) env[MCP_DIRECT_TOOLS_ENV] = "__none__";
|
|
181
|
+
else if (!toolPlan.capabilityCeiling && input.mcpDirectTools?.length) env[MCP_DIRECT_TOOLS_ENV] = input.mcpDirectTools.join(",");
|
|
178
182
|
else if (toolPlan.capabilityCeiling && toolPlan.effectiveMcpSelections.length && !toolPlan.capabilityCeiling.denyExtensions) {
|
|
179
183
|
env[MCP_DIRECT_TOOLS_ENV] = toolPlan.effectiveMcpSelections.map((selection) => selection.selector).join(",");
|
|
180
184
|
} else env[MCP_DIRECT_TOOLS_ENV] = "__none__";
|
|
@@ -211,6 +215,7 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
211
215
|
subagentOnlyExtensions: input.subagentOnlyExtensions,
|
|
212
216
|
requiredExtensions,
|
|
213
217
|
mcpDirectTools: input.mcpDirectTools,
|
|
218
|
+
builtinMcpTools: input.builtinMcpTools,
|
|
214
219
|
cwd: input.cwd,
|
|
215
220
|
requireReadTool: input.requireReadTool,
|
|
216
221
|
structuredOutput: Boolean(input.structuredOutput),
|
|
@@ -225,6 +230,12 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
225
230
|
permissionProfile: input.permissionProfile,
|
|
226
231
|
hostAvailableBuiltins: input.hostAvailableBuiltins,
|
|
227
232
|
});
|
|
233
|
+
// Foreground children load no ambient extensions, so an extension's registerMcpServer() never runs in them.
|
|
234
|
+
if (input.host === "parent" && input.runtimeSnapshotHost && toolPlan.builtinMcpTools?.length) {
|
|
235
|
+
// Pi treats a session without a trust decision as trusted.
|
|
236
|
+
const servers = extensionOnlyMcpServers(toolPlan.effectiveMcpSelections, input.runtimeSnapshotHost, input.cwd, input.projectTrusted !== false);
|
|
237
|
+
if (servers.length) throw new Error(`Agent '${input.childAgentName}' selects MCP tools from servers that extensions registered (${servers.join(", ")}). Only background children (async: true) load those extensions; run the agent in the background or add the server to the global mcp.json or a trusted project's .pi/mcp.json.`);
|
|
238
|
+
}
|
|
228
239
|
toolPlan.capabilityCeiling = intersectSubagentCapabilityCeilings(toolPlan.capabilityCeiling, agentCapabilityCeiling);
|
|
229
240
|
if (toolPlan.capabilityAudit && toolPlan.capabilityCeiling) {
|
|
230
241
|
toolPlan.capabilityAudit = { ...toolPlan.capabilityAudit, ceiling: toolPlan.capabilityCeiling };
|
|
@@ -334,10 +345,12 @@ export function buildInProcessChildLaunch(input: BuildInProcessChildLaunchInput)
|
|
|
334
345
|
const session: Omit<ChildSessionLaunch, "onExtensionError"> = {
|
|
335
346
|
cwd: input.cwd,
|
|
336
347
|
...(input.machine ? { machine: input.machine } : {}),
|
|
348
|
+
...(input.projectTrusted !== undefined ? { projectTrusted: input.projectTrusted } : {}),
|
|
337
349
|
...(input.machine ? { remoteResources: { agent: input.childAgentName, ...(input.remoteSkillNames ? { skills: input.remoteSkillNames } : {}), ...(input.remoteReads !== undefined ? { reads: input.remoteReads } : {}), ...(toolPlan.explicitToolAllowlist ? { toolCeiling: [...toolPlan.effectiveToolAllowlist] } : toolPlan.capabilityCeiling?.allowedTools ? { toolCeiling: [...toolPlan.capabilityCeiling.allowedTools] } : {}) } } : {}),
|
|
338
350
|
storage: childStorage(input),
|
|
339
351
|
...(input.model ? { model: input.model } : {}),
|
|
340
352
|
...(toolPlan.explicitToolAllowlist ? { tools: toolPlan.effectiveToolAllowlist } : {}),
|
|
353
|
+
...(toolPlan.builtinMcpTools?.length ? { builtinMcpTools: toolPlan.builtinMcpTools } : {}),
|
|
341
354
|
...(!toolPlan.explicitToolAllowlist && toolPlan.excludeTools.length > 0 ? { excludeTools: toolPlan.excludeTools } : {}),
|
|
342
355
|
extensionPaths,
|
|
343
356
|
requiredExtensions: toolPlan.requiredExtensions,
|
|
@@ -55,6 +55,8 @@ export interface ChildSessionLaunch {
|
|
|
55
55
|
cwd: string;
|
|
56
56
|
/** Resolved pane-native placement. Local launches omit this field. */
|
|
57
57
|
machine?: HerdrMachineReference;
|
|
58
|
+
/** The launching session's project trust; undefined keeps Pi's default for hosts without trust. */
|
|
59
|
+
projectTrusted?: boolean;
|
|
58
60
|
/** Process-local provider source owned by the invoking foreground parent. */
|
|
59
61
|
parentProviderRegistry?: ParentProviderRegistry;
|
|
60
62
|
/** Logical names resolved only by the remote ambient package. */
|
|
@@ -64,6 +66,8 @@ export interface ChildSessionLaunch {
|
|
|
64
66
|
model?: string;
|
|
65
67
|
/** Explicit tool allowlist; undefined keeps pi's defaults. */
|
|
66
68
|
tools?: string[];
|
|
69
|
+
/** Tools of Pi's built-in MCP extension the child must declare to its model directly, with the `mcp:` selector that granted each; `tools` names them too. */
|
|
70
|
+
builtinMcpTools?: Array<{ name: string; selector: string }>;
|
|
67
71
|
excludeTools?: string[];
|
|
68
72
|
/** Extension files loaded for this child in addition to the inline hooks. */
|
|
69
73
|
extensionPaths: string[];
|
|
@@ -148,6 +152,8 @@ export interface DefaultChildSessionFactoryOptions {
|
|
|
148
152
|
loadPiCodingAgent?: () => Promise<PiCodingAgentModule>;
|
|
149
153
|
/** Upper bound on a disposed child's `session_shutdown` handlers before the session is dropped anyway. */
|
|
150
154
|
shutdownTimeoutMs?: number;
|
|
155
|
+
/** Upper bound on the wait for selected built-in MCP tools to register after the session starts. */
|
|
156
|
+
builtinMcpToolWaitMs?: number;
|
|
151
157
|
}
|
|
152
158
|
|
|
153
159
|
type ModelRuntimeInstance = Awaited<ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]>>;
|
|
@@ -231,6 +237,53 @@ function restoreProcessEnv(saved: Array<[string, string | undefined]>): void {
|
|
|
231
237
|
}
|
|
232
238
|
}
|
|
233
239
|
|
|
240
|
+
/**
|
|
241
|
+
* Pi's built-in MCP extension registers server tools with the configured exposure, `codemode` by
|
|
242
|
+
* default, which the child's `tools` allowlist cannot declare. Registering the selected names as
|
|
243
|
+
* `direct` makes them model-declared and callable; `hidden` stays hidden. A name counts only when
|
|
244
|
+
* the tool's raw identity, its `<server>/<tool>` label, matches the granting selector: Pi can give
|
|
245
|
+
* the sanitized name of `srv/a.b` to `srv/a_b`. Every other tool the extension registers becomes
|
|
246
|
+
* `hidden`, so neither codemode nor `ctx.executeTool()` can call it, independent of the `tools`
|
|
247
|
+
* allowlist. The `builtin` entry loads
|
|
248
|
+
* through the explicit `builtin:mcp` path even with `noExtensions`, and `replaceable` lets an
|
|
249
|
+
* ambient MCP extension that registers `/mcp` replace it, as in the parent.
|
|
250
|
+
*/
|
|
251
|
+
function selectedBuiltinMcpExtension(pi: PiCodingAgentModule, selections: ReadonlyArray<{ name: string; selector: string }>): ChildHookExtension & { builtin: true; replaceable: true } {
|
|
252
|
+
// Pi 0.99 export; the pinned SDK types predate it.
|
|
253
|
+
const createMcpExtension = (pi as { createMcpExtension?: () => (api: ExtensionAPI) => void | Promise<void> }).createMcpExtension;
|
|
254
|
+
if (typeof createMcpExtension !== "function") throw new Error(`Selected built-in MCP tools (${selections.map(({ name }) => name).join(", ")}) need a Pi version with built-in MCP.`);
|
|
255
|
+
const selectors = new Map(selections.map(({ name, selector }) => [name, selector]));
|
|
256
|
+
const granted = (tool: { name: string; label?: string; exposure?: string }) => {
|
|
257
|
+
const selector = selectors.get(tool.name);
|
|
258
|
+
if (selector === undefined || tool.exposure === "hidden" || tool.label === undefined) return false;
|
|
259
|
+
return selector.includes("/") ? tool.label === selector : tool.label.startsWith(`${selector}/`);
|
|
260
|
+
};
|
|
261
|
+
const mcp = createMcpExtension();
|
|
262
|
+
const factory = (api: ExtensionAPI) => mcp(new Proxy(api, {
|
|
263
|
+
get(target, prop) {
|
|
264
|
+
if (prop === "registerTool") {
|
|
265
|
+
return (tool: Parameters<ExtensionAPI["registerTool"]>[0] & { exposure?: string }) =>
|
|
266
|
+
target.registerTool({ ...tool, exposure: granted(tool) ? "direct" : "hidden" } as typeof tool);
|
|
267
|
+
}
|
|
268
|
+
const value = Reflect.get(target, prop, target);
|
|
269
|
+
return typeof value === "function" ? value.bind(target) : value;
|
|
270
|
+
},
|
|
271
|
+
}));
|
|
272
|
+
return { name: "mcp", factory, builtin: true, replaceable: true };
|
|
273
|
+
}
|
|
274
|
+
|
|
275
|
+
/** MCP connects after `session_start`, so the selected tools register some time after the session binds. */
|
|
276
|
+
async function missingBuiltinMcpTools(session: { getAllTools(): Array<{ name: string }>; getActiveToolNames(): string[] }, names: readonly string[], timeoutMs: number, stopped: () => boolean): Promise<string[]> {
|
|
277
|
+
const deadline = Date.now() + timeoutMs;
|
|
278
|
+
for (;;) {
|
|
279
|
+
const active = new Set(session.getActiveToolNames());
|
|
280
|
+
const direct = new Set(session.getAllTools().filter((tool) => (tool as { exposure?: string }).exposure === "direct").map(({ name }) => name));
|
|
281
|
+
const missing = names.filter((name) => !active.has(name) || !direct.has(name));
|
|
282
|
+
if (missing.length === 0 || stopped() || Date.now() >= deadline) return missing;
|
|
283
|
+
await new Promise((resolve) => setTimeout(resolve, 50));
|
|
284
|
+
}
|
|
285
|
+
}
|
|
286
|
+
|
|
234
287
|
function flushQueuedProviderRegistrations(loader: InstanceType<PiCodingAgentModule["DefaultResourceLoader"]>, modelRuntime: ModelRuntimeInstance, onError: ((error: ChildSessionExtensionError) => void) | undefined, requiredPaths: ReadonlySet<string>): { claimedProviderIds: Set<string>; registered: boolean } {
|
|
235
288
|
const claimedProviderIds = new Set<string>();
|
|
236
289
|
if (!("getExtensions" in loader) || typeof loader.getExtensions !== "function") return { claimedProviderIds, registered: false };
|
|
@@ -311,10 +364,14 @@ function isUnknownRecord(value: unknown): value is Record<string, unknown> {
|
|
|
311
364
|
export function createDefaultChildSessionFactory(options: DefaultChildSessionFactoryOptions = {}): ChildSessionFactory {
|
|
312
365
|
const loadPiCodingAgent = options.loadPiCodingAgent ?? loadHostPiCodingAgent;
|
|
313
366
|
const shutdownTimeoutMs = options.shutdownTimeoutMs ?? 5_000;
|
|
367
|
+
const builtinMcpToolWaitMs = options.builtinMcpToolWaitMs ?? 10_000;
|
|
314
368
|
let runtime: ReturnType<PiCodingAgentModule["ModelRuntime"]["create"]> | undefined;
|
|
315
369
|
const live = new Set<ChildSession>();
|
|
316
370
|
/** Extension shutdowns still running for disposed children; `dispose()` waits for them. */
|
|
317
371
|
const shutdowns = new Set<Promise<void>>();
|
|
372
|
+
/** Launches still waiting for their MCP tools; `dispose()` ends the wait and waits for their shutdown. */
|
|
373
|
+
const mcpWaits = new Set<Promise<void>>();
|
|
374
|
+
let disposals = 0;
|
|
318
375
|
const sharedRuntime = async (pi: PiCodingAgentModule) => {
|
|
319
376
|
runtime ??= pi.ModelRuntime.create().catch((error: unknown) => {
|
|
320
377
|
runtime = undefined;
|
|
@@ -324,29 +381,44 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
324
381
|
};
|
|
325
382
|
return {
|
|
326
383
|
async create(launch) {
|
|
384
|
+
const disposalsAtStart = disposals;
|
|
327
385
|
const pi = await loadPiCodingAgent();
|
|
386
|
+
const builtinMcpTools = launch.builtinMcpTools ?? [];
|
|
387
|
+
const builtinMcp = builtinMcpTools.length ? selectedBuiltinMcpExtension(pi, builtinMcpTools) : undefined;
|
|
328
388
|
const modelRuntime = launch.parentProviderRegistry
|
|
329
389
|
? await pi.ModelRuntime.create()
|
|
330
390
|
: await sharedRuntime(pi);
|
|
331
391
|
const agentDir = getAgentDir();
|
|
332
|
-
const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir);
|
|
392
|
+
const settingsManager = pi.SettingsManager.create(launch.cwd, agentDir, { projectTrusted: launch.projectTrusted });
|
|
333
393
|
// Foreground children share Pi's global theme with the parent, so reinitializing it
|
|
334
394
|
// would overwrite the parent's active light/dark appearance. Detached runners have
|
|
335
395
|
// no initialized theme and must initialize one for headless extension renderers.
|
|
336
396
|
const themeKey = Symbol.for("@earendil-works/pi-coding-agent:theme");
|
|
337
397
|
const themeInitialized = Boolean((globalThis as Record<symbol, unknown>)[themeKey]);
|
|
338
398
|
if (!themeInitialized && typeof pi.initTheme === "function") pi.initTheme(settingsManager.getTheme());
|
|
399
|
+
// SDK sessions do not install Pi's CLI built-ins. Use the host's own
|
|
400
|
+
// codemode factory only when this child can select it; older Pi hosts
|
|
401
|
+
// without that factory retain the strict missing-tool diagnostic.
|
|
402
|
+
const createCodemodeExtension = (pi as PiCodingAgentModule & { createCodemodeExtension?: () => ChildHookExtension["factory"] }).createCodemodeExtension;
|
|
403
|
+
const codemode = typeof createCodemodeExtension === "function" &&
|
|
404
|
+
!launch.runtime.capabilityCeiling?.denyExtensions &&
|
|
405
|
+
(launch.tools === undefined || launch.tools.includes("codemode")) &&
|
|
406
|
+
!launch.excludeTools?.includes("codemode")
|
|
407
|
+
? [{ name: "codemode", factory: createCodemodeExtension(), replaceable: true }]
|
|
408
|
+
: [];
|
|
339
409
|
const loader = new pi.DefaultResourceLoader({
|
|
340
410
|
cwd: launch.cwd,
|
|
341
411
|
agentDir,
|
|
342
412
|
settingsManager,
|
|
343
413
|
noExtensions: !launch.ambientExtensions,
|
|
344
414
|
noSkills: launch.noSkills,
|
|
415
|
+
// Pi merges skills from extensions' resources_discover without checking noSkills.
|
|
416
|
+
skillsOverride: launch.noSkills ? (base) => ({ ...base, skills: [] }) : undefined,
|
|
345
417
|
noPromptTemplates: true,
|
|
346
418
|
noThemes: true,
|
|
347
419
|
noContextFiles: launch.noContextFiles,
|
|
348
|
-
additionalExtensionPaths: launch.extensionPaths,
|
|
349
|
-
extensionFactories: launch.hooks,
|
|
420
|
+
additionalExtensionPaths: builtinMcp ? [...launch.extensionPaths, "builtin:mcp"] : launch.extensionPaths,
|
|
421
|
+
extensionFactories: [...launch.hooks, ...codemode, ...(builtinMcp ? [builtinMcp] : [])],
|
|
350
422
|
extensionsOverride: prioritizeChildPromptRuntime,
|
|
351
423
|
...(launch.systemPrompt !== undefined ? { systemPrompt: launch.systemPrompt } : {}),
|
|
352
424
|
...(launch.appendSystemPrompt !== undefined ? { appendSystemPrompt: [launch.appendSystemPrompt] } : {}),
|
|
@@ -431,11 +503,24 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
431
503
|
session.dispose();
|
|
432
504
|
}
|
|
433
505
|
};
|
|
506
|
+
// Outside the launch lock: MCP servers connect after `session_start` without reading the per-launch env.
|
|
507
|
+
if (builtinMcpTools.length) {
|
|
508
|
+
const disposed = () => disposals !== disposalsAtStart;
|
|
509
|
+
const ready = missingBuiltinMcpTools(session, builtinMcpTools.map(({ name }) => name), builtinMcpToolWaitMs, disposed).then(async (missing) => {
|
|
510
|
+
if (!missing.length && !disposed()) return;
|
|
511
|
+
await shutdown();
|
|
512
|
+
throw new Error(disposed()
|
|
513
|
+
? "The child session factory was disposed while the child waited for its MCP tools."
|
|
514
|
+
: `Selected built-in MCP tools did not register in the child session: ${missing.join(", ")}. The MCP server may have failed to connect, or the name belongs to a different tool than the selector names; check it with /mcp.`);
|
|
515
|
+
});
|
|
516
|
+
mcpWaits.add(ready);
|
|
517
|
+
try { await ready; } finally { mcpWaits.delete(ready); }
|
|
518
|
+
}
|
|
434
519
|
const child: ChildSession = {
|
|
435
520
|
subscribe: (listener) => session.subscribe((event) => listener(event as unknown as ChildSessionEvent)),
|
|
436
521
|
prompt: (text) => session.prompt(text),
|
|
437
|
-
steer: (text) => session.steer(text),
|
|
438
|
-
followUp: (text) => session.followUp(text),
|
|
522
|
+
steer: (text) => session.steer(text).then(() => undefined),
|
|
523
|
+
followUp: (text) => session.followUp(text).then(() => undefined),
|
|
439
524
|
abort: () => session.abort(),
|
|
440
525
|
hasQueuedMessages: () => session.agent?.hasQueuedMessages?.() === true,
|
|
441
526
|
dispose: () => {
|
|
@@ -458,13 +543,14 @@ export function createDefaultChildSessionFactory(options: DefaultChildSessionFac
|
|
|
458
543
|
return child;
|
|
459
544
|
},
|
|
460
545
|
async dispose() {
|
|
546
|
+
disposals += 1;
|
|
461
547
|
const children = [...live].filter((child) => !child.detached);
|
|
462
548
|
for (const child of children) child.shutDown = true;
|
|
463
549
|
await Promise.allSettled(children.map((child) => child.abort()));
|
|
464
550
|
for (const child of children) {
|
|
465
551
|
try { void child.dispose(); } catch { /* best effort */ }
|
|
466
552
|
}
|
|
467
|
-
await Promise.allSettled([...shutdowns]);
|
|
553
|
+
await Promise.allSettled([...shutdowns, ...mcpWaits]);
|
|
468
554
|
if (live.size === 0) runtime = undefined;
|
|
469
555
|
},
|
|
470
556
|
};
|
|
@@ -9,6 +9,7 @@ import * as path from "node:path";
|
|
|
9
9
|
import { fileURLToPath } from "node:url";
|
|
10
10
|
import type { ExtensionAPI } from "@earendil-works/pi-coding-agent";
|
|
11
11
|
import {
|
|
12
|
+
formatUnresolvedBuiltinMcpSelectors,
|
|
12
13
|
formatUnresolvedMcpDirectToolSelectors,
|
|
13
14
|
resolveMcpDirectToolResolution,
|
|
14
15
|
type McpRuntimeSnapshotHost,
|
|
@@ -171,6 +172,8 @@ export interface ResolvePiLaunchToolPlanInput {
|
|
|
171
172
|
* Non-core names remain allowed and are validated in the child's registry.
|
|
172
173
|
*/
|
|
173
174
|
hostAvailableBuiltins?: readonly string[];
|
|
175
|
+
/** The parent's built-in MCP selections; the background runner has no host to resolve selectors against. */
|
|
176
|
+
builtinMcpTools?: ResolvedMcpDirectToolSelection[];
|
|
174
177
|
}
|
|
175
178
|
|
|
176
179
|
export interface PiLaunchToolPlan {
|
|
@@ -182,6 +185,8 @@ export interface PiLaunchToolPlan {
|
|
|
182
185
|
resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
|
|
183
186
|
effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
|
|
184
187
|
effectiveMcpTools: string[];
|
|
188
|
+
/** Effective selections granted from Pi's built-in MCP; undefined when the selectors did not resolve against it. */
|
|
189
|
+
builtinMcpTools?: ResolvedMcpDirectToolSelection[];
|
|
185
190
|
explicitToolAllowlist: boolean;
|
|
186
191
|
internalTools: string[];
|
|
187
192
|
effectiveToolAllowlist: string[];
|
|
@@ -383,16 +388,21 @@ export function resolvePiLaunchToolPlan(
|
|
|
383
388
|
);
|
|
384
389
|
const mcpResolution = capabilityCeiling?.denyExtensions
|
|
385
390
|
? { selections: [], unresolvedSelectors: [] }
|
|
386
|
-
:
|
|
391
|
+
: input.builtinMcpTools
|
|
392
|
+
// The runner applies the same ceilings again; filtering is idempotent.
|
|
393
|
+
? { selections: input.builtinMcpTools, unresolvedSelectors: [], builtin: true as const }
|
|
394
|
+
: resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
|
|
387
395
|
if (mcpResolution.runtimeServerNames?.length) {
|
|
388
396
|
throw new Error(formatRuntimeSnapshotMcpServersError(input.agentName, mcpResolution.runtimeServerNames));
|
|
389
397
|
}
|
|
390
398
|
if (mcpResolution.unresolvedSelectors.length > 0) {
|
|
391
|
-
throw new Error(
|
|
399
|
+
throw new Error(mcpResolution.builtin
|
|
400
|
+
? formatUnresolvedBuiltinMcpSelectors(input.agentName, mcpResolution.unresolvedSelectors)
|
|
401
|
+
: formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
|
|
392
402
|
}
|
|
393
403
|
const resolvedMcpSelections = mcpResolution.selections;
|
|
394
404
|
const resolvedMcpNames = new Set(resolvedMcpSelections.map((selection) => selection.name));
|
|
395
|
-
const legacyMcpNameCounts = countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
|
|
405
|
+
const legacyMcpNameCounts = mcpResolution.builtin ? new Map<string, number>() : countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
|
|
396
406
|
const effectiveMcpSelections = resolvedMcpSelections.filter(
|
|
397
407
|
(selection) =>
|
|
398
408
|
!allowedToolSet ||
|
|
@@ -402,6 +412,7 @@ export function resolvePiLaunchToolPlan(
|
|
|
402
412
|
const effectiveMcpTools = effectiveMcpSelections.map(
|
|
403
413
|
(selection) => selection.name,
|
|
404
414
|
);
|
|
415
|
+
const builtinMcpTools = mcpResolution.builtin ? effectiveMcpSelections : undefined;
|
|
405
416
|
const explicitToolAllowlist =
|
|
406
417
|
input.tools !== undefined ||
|
|
407
418
|
(input.mcpDirectTools?.length ?? 0) > 0 ||
|
|
@@ -538,6 +549,7 @@ export function resolvePiLaunchToolPlan(
|
|
|
538
549
|
resolvedMcpSelections,
|
|
539
550
|
effectiveMcpSelections,
|
|
540
551
|
effectiveMcpTools,
|
|
552
|
+
builtinMcpTools,
|
|
541
553
|
explicitToolAllowlist,
|
|
542
554
|
internalTools,
|
|
543
555
|
effectiveToolAllowlist,
|
|
@@ -50,7 +50,7 @@ const DYNAMIC_PARALLEL_KEYS = new Set(["agent", "task", "phase", "label", "outpu
|
|
|
50
50
|
const RUNNER_DYNAMIC_PARALLEL_KEYS = new Set([
|
|
51
51
|
...DYNAMIC_PARALLEL_KEYS,
|
|
52
52
|
"outputName", "structured", "inheritProjectContext", "inheritGlobalContext", "inheritSkills", "skills", "outputPath", "namespaceOutputPath", "maxSubagentDepth", "timeoutMs", "waitToolEnabled", "waitToolDefaultTimeoutMs",
|
|
53
|
-
"structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "mutationTools", "capabilityCeiling", "systemPrompt",
|
|
53
|
+
"structuredOutput", "structuredOutputSchema", "tools", "excludeTools", "allowNestedSubagents", "extensions", "subagentOnlyExtensions", "mcpDirectTools", "builtinMcpTools", "mutationTools", "capabilityCeiling", "systemPrompt",
|
|
54
54
|
"systemPromptMode", "thinking", "requestedModel", "sessionFile", "effectiveAcceptance", "acceptanceInput", "acceptanceRole", "parentSessionId", "requiredExtensions", "launchResolvedExtensions", "requestedCwd", "machineEnv",
|
|
55
55
|
]);
|
|
56
56
|
const DYNAMIC_COLLECT_KEYS = new Set(["as", "outputSchema"]);
|
|
@@ -40,6 +40,7 @@ export interface McpServerDefinition {
|
|
|
40
40
|
httpTransport?: string;
|
|
41
41
|
pluginDataDir?: string;
|
|
42
42
|
literalEnv?: boolean;
|
|
43
|
+
inheritEnv?: boolean;
|
|
43
44
|
}
|
|
44
45
|
|
|
45
46
|
export function isMcpServerDefinition(value: unknown): value is McpServerDefinition {
|
|
@@ -53,7 +54,7 @@ export function isMcpServerDefinition(value: unknown): value is McpServerDefinit
|
|
|
53
54
|
for (const field of ["env", "headers"] as const) {
|
|
54
55
|
if (value[field] !== undefined && !isStringRecord(value[field])) return false;
|
|
55
56
|
}
|
|
56
|
-
for (const field of ["exposeResources", "literalEnv"] as const) {
|
|
57
|
+
for (const field of ["exposeResources", "literalEnv", "inheritEnv"] as const) {
|
|
57
58
|
if (value[field] !== undefined && typeof value[field] !== "boolean") return false;
|
|
58
59
|
}
|
|
59
60
|
if (value.requestHeadersCommand !== undefined && !isRequestHeadersCommand(value.requestHeadersCommand)) return false;
|
|
@@ -67,6 +67,17 @@ export interface McpRuntimeSnapshotHost {
|
|
|
67
67
|
events: {
|
|
68
68
|
emit(event: string, request: McpRuntimeSnapshotRequest): void;
|
|
69
69
|
};
|
|
70
|
+
getAllTools?(): readonly McpHostToolInfo[];
|
|
71
|
+
getCommands?(): readonly { name: string; sourceInfo: { path: string } }[];
|
|
72
|
+
/** Pi 0.99: servers extensions added with `pi.registerMcpServer()`. */
|
|
73
|
+
getMcpServers?(): readonly { name: string }[];
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/** A `pi.getAllTools()` entry; `exposure` and `namespace` exist only from Pi 0.99. */
|
|
77
|
+
export interface McpHostToolInfo {
|
|
78
|
+
name: string;
|
|
79
|
+
exposure?: string;
|
|
80
|
+
namespace?: { name: string };
|
|
70
81
|
}
|
|
71
82
|
|
|
72
83
|
interface CachedTool {
|
|
@@ -96,6 +107,8 @@ export interface McpDirectToolResolution {
|
|
|
96
107
|
/** Normal loaded config plus the selected runtime server definitions. */
|
|
97
108
|
mcpConfig?: McpConfig;
|
|
98
109
|
runtimeServerNames?: string[];
|
|
110
|
+
/** Set when the selectors were resolved against Pi's built-in MCP instead of pi-mcp-adapter. */
|
|
111
|
+
builtin?: true;
|
|
99
112
|
}
|
|
100
113
|
|
|
101
114
|
export function resolveMcpDirectToolResolution(
|
|
@@ -106,6 +119,9 @@ export function resolveMcpDirectToolResolution(
|
|
|
106
119
|
): McpDirectToolResolution {
|
|
107
120
|
const selectors = normalizeMcpDirectToolSelectors(mcpDirectTools);
|
|
108
121
|
if (selectors.length === 0) return { selections: [], unresolvedSelectors: [] };
|
|
122
|
+
if (usesBuiltinMcp(runtimeSnapshotHost)) {
|
|
123
|
+
return resolveBuiltinMcpSelections(selectors, runtimeSnapshotHost.getAllTools?.() ?? []);
|
|
124
|
+
}
|
|
109
125
|
|
|
110
126
|
const config = configOverride ?? loadMcpConfig(cwd);
|
|
111
127
|
const { servers: selectedServers, tools: selectedTools } = parseMcpDirectToolSelectors(selectors);
|
|
@@ -146,6 +162,75 @@ export function resolveMcpDirectToolSelections(
|
|
|
146
162
|
return resolveMcpDirectToolResolution(mcpDirectTools, cwd, runtimeSnapshotHost).selections;
|
|
147
163
|
}
|
|
148
164
|
|
|
165
|
+
/**
|
|
166
|
+
* pi-mcp-adapter keeps priority whenever it is loaded. 2.x registers /mcp, so Pi does not load its
|
|
167
|
+
* built-in MCP. 3.x always registers /mcp-adapter and leaves /mcp to the built-in MCP.
|
|
168
|
+
*/
|
|
169
|
+
function usesBuiltinMcp(host: McpRuntimeSnapshotHost | undefined): host is McpRuntimeSnapshotHost {
|
|
170
|
+
const commands = host?.getCommands?.() ?? [];
|
|
171
|
+
return commands.find((command) => command.name === "mcp")?.sourceInfo.path === "builtin:mcp"
|
|
172
|
+
&& !commands.some((command) => /^mcp-adapter(?::\d+)?$/.test(command.name));
|
|
173
|
+
}
|
|
174
|
+
|
|
175
|
+
/**
|
|
176
|
+
* Pi names built-in MCP tools `mcp__<server>__<tool>` with invalid characters replaced by `_`,
|
|
177
|
+
* in the namespace `mcp__<server>`. An overlong name, or one an earlier tool already took (`a_b`
|
|
178
|
+
* before `a.b`), gets a suffix hashed from the raw server and tool (Pi's `createMcpToolName`), so
|
|
179
|
+
* that suffixed name identifies the tool. The unsuffixed name may belong to another raw tool; the
|
|
180
|
+
* child checks each granted tool's raw identity before it exposes the tool.
|
|
181
|
+
*/
|
|
182
|
+
function resolveBuiltinMcpSelections(selectors: string[], tools: readonly McpHostToolInfo[]): McpDirectToolResolution {
|
|
183
|
+
const selections: ResolvedMcpDirectToolSelection[] = [];
|
|
184
|
+
const unresolvedSelectors: string[] = [];
|
|
185
|
+
for (const selector of selectors) {
|
|
186
|
+
const slash = selector.indexOf("/");
|
|
187
|
+
const server = slash === -1 ? selector : selector.slice(0, slash);
|
|
188
|
+
const inServer = tools.filter((tool) => tool.namespace?.name === `mcp__${server}`);
|
|
189
|
+
const toolName = slash === -1 ? undefined : builtinMcpToolNames(server, selector.slice(slash + 1)).find((name) => inServer.some((tool) => tool.name === name));
|
|
190
|
+
const matches = inServer.filter((tool) => tool.exposure !== "hidden" && (slash === -1 || tool.name === toolName));
|
|
191
|
+
if (matches.length === 0) unresolvedSelectors.push(selector);
|
|
192
|
+
for (const tool of matches) {
|
|
193
|
+
if (!selections.some((selection) => selection.name === tool.name)) selections.push({ name: tool.name, selector });
|
|
194
|
+
}
|
|
195
|
+
}
|
|
196
|
+
return { selections, unresolvedSelectors, builtin: true };
|
|
197
|
+
}
|
|
198
|
+
|
|
199
|
+
/** The names Pi's `createMcpToolName` can give a raw tool, the hash-suffixed one first. */
|
|
200
|
+
function builtinMcpToolNames(server: string, tool: string): string[] {
|
|
201
|
+
const name = `mcp__${server}__${tool}`.replace(/[^A-Za-z0-9_-]/g, "_");
|
|
202
|
+
const hash = createHash("sha256").update(`${server}\0${tool}`).digest("hex").slice(0, 8);
|
|
203
|
+
const suffixed = `${name.slice(0, 64 - hash.length - 1)}_${hash}`;
|
|
204
|
+
return name.length <= 64 ? [suffixed, name] : [suffixed];
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
export function formatUnresolvedBuiltinMcpSelectors(agentName: string | undefined, selectors: readonly string[]): string {
|
|
208
|
+
const subject = agentName ? `Agent '${agentName}'` : "Subagent";
|
|
209
|
+
return `${subject} selects MCP tools that Pi's built-in MCP does not offer: ${selectors.map((selector) => `mcp:${selector}`).join(", ")}. The server may be missing, disconnected, still connecting, or its tools hidden; check /mcp.`;
|
|
210
|
+
}
|
|
211
|
+
|
|
212
|
+
/**
|
|
213
|
+
* Selected servers that only an extension registered, which a child without ambient extensions
|
|
214
|
+
* never has. A server of the same name in an `mcp.json` the child reads takes precedence; like Pi,
|
|
215
|
+
* the project file is read only when the project is trusted.
|
|
216
|
+
*/
|
|
217
|
+
export function extensionOnlyMcpServers(selections: readonly ResolvedMcpDirectToolSelection[], host: McpRuntimeSnapshotHost, cwd: string, projectTrusted: boolean): string[] {
|
|
218
|
+
const registered = new Set(host.getMcpServers?.().map(({ name }) => name));
|
|
219
|
+
const servers = [...new Set(selections.map(({ selector }) => selector.split("/")[0]!))].filter((server) => registered.has(server));
|
|
220
|
+
if (servers.length === 0) return [];
|
|
221
|
+
const files = [path.join(getAgentDir(), "mcp.json"), ...(projectTrusted ? [path.join(cwd, ".pi", "mcp.json")] : [])];
|
|
222
|
+
const configured = new Set(files.flatMap((file) => {
|
|
223
|
+
let parsed: unknown;
|
|
224
|
+
try {
|
|
225
|
+
parsed = JSON.parse(fs.readFileSync(file, "utf-8"));
|
|
226
|
+
} catch {
|
|
227
|
+
return [];
|
|
228
|
+
}
|
|
229
|
+
return isRecord(parsed) && isRecord(parsed.mcpServers) ? Object.keys(parsed.mcpServers) : [];
|
|
230
|
+
}));
|
|
231
|
+
return servers.filter((server) => !configured.has(server));
|
|
232
|
+
}
|
|
233
|
+
|
|
149
234
|
function loadMetadataCache(): MetadataCache | null {
|
|
150
235
|
const cachePath = path.join(getAgentDir(), "mcp-cache.json");
|
|
151
236
|
let parsed: unknown;
|
|
@@ -262,15 +347,17 @@ function loadMcpConfig(cwd: string): McpConfig {
|
|
|
262
347
|
}
|
|
263
348
|
|
|
264
349
|
function getConfigPaths(projectRoot: string): string[] {
|
|
265
|
-
const
|
|
266
|
-
const
|
|
267
|
-
|
|
268
|
-
|
|
269
|
-
|
|
270
|
-
|
|
271
|
-
|
|
272
|
-
|
|
273
|
-
|
|
350
|
+
const agentDir = getAgentDir();
|
|
351
|
+
const projectDir = getProjectConfigDir(projectRoot);
|
|
352
|
+
// pi-mcp-adapter 3.x reads mcp-adapter.json. Pi's own mcp.json files belong to
|
|
353
|
+
// Pi's built-in MCP support, so servers there are never adapter-registered.
|
|
354
|
+
const candidates = [
|
|
355
|
+
GENERIC_GLOBAL_CONFIG_PATH,
|
|
356
|
+
path.join(agentDir, "mcp-adapter.json"),
|
|
357
|
+
path.resolve(projectRoot, ".mcp.json"),
|
|
358
|
+
path.join(projectDir, "mcp-adapter.json"),
|
|
359
|
+
];
|
|
360
|
+
return [...new Set(candidates)];
|
|
274
361
|
}
|
|
275
362
|
|
|
276
363
|
function readConfig(configPath: string): McpConfig | null {
|
|
@@ -381,11 +468,16 @@ function isServerCacheValid(entry: ServerCacheEntry | undefined, definition: Ser
|
|
|
381
468
|
}
|
|
382
469
|
|
|
383
470
|
export function computeMcpServerHash(definition: ServerEntry): string {
|
|
471
|
+
// Aligned with pi-mcp-adapter's computeServerHash; since 3.1.0 stdio hashes include
|
|
472
|
+
// inheritEnv/literalEnv. A mismatch leaves that server's cached direct-tool selectors unresolved.
|
|
473
|
+
const isStdio = definition.command !== undefined;
|
|
474
|
+
const literalEnv = isStdio && definition.literalEnv === true;
|
|
384
475
|
const identity: Record<string, unknown> = {
|
|
385
|
-
command: definition.command,
|
|
476
|
+
command: resolveConfigPath(definition.command),
|
|
386
477
|
args: definition.args,
|
|
387
478
|
socket: resolveConfigPath(definition.socket),
|
|
388
|
-
env: interpolateEnvRecord(definition.env),
|
|
479
|
+
env: literalEnv ? definition.env : interpolateEnvRecord(definition.env),
|
|
480
|
+
...(isStdio ? { inheritEnv: definition.inheritEnv !== false, literalEnv } : {}),
|
|
389
481
|
cwd: resolveConfigPath(definition.cwd),
|
|
390
482
|
url: resolveServerUrl(definition),
|
|
391
483
|
headers: interpolateEnvRecord(definition.headers),
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import { splitKnownThinkingSuffix as splitThinkingSuffix, type ModelInfo as AvailableModelInfo } from "../../shared/model-info.ts";
|
|
2
|
-
import { checkModelScope, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
|
|
2
|
+
import { checkModelScope, SCOPED_PATTERN, type ModelScopeCheckRule, type ModelScopeViolation, type ModelSource } from "./model-scope.ts";
|
|
3
3
|
|
|
4
4
|
export type { AvailableModelInfo };
|
|
5
5
|
|
|
@@ -50,6 +50,23 @@ export function normalizeParentModel(model: unknown): ParentModel | undefined {
|
|
|
50
50
|
return { provider: candidate.provider, id: candidate.id };
|
|
51
51
|
}
|
|
52
52
|
|
|
53
|
+
/**
|
|
54
|
+
* Provider/id ids of the host session's scoped-model snapshot (`ctx.scopedModels`).
|
|
55
|
+
* Pi reports an empty set when the session is unscoped (nothing configured, or no
|
|
56
|
+
* pattern matched), and then allows every model; `scoped` narrows that to `inherit`.
|
|
57
|
+
*/
|
|
58
|
+
export function scopedModelIdsFromContext(ctx: { scopedModels?: ReadonlyArray<{ model?: unknown }> }): string[] {
|
|
59
|
+
const scoped = ctx.scopedModels;
|
|
60
|
+
if (!Array.isArray(scoped)) return [];
|
|
61
|
+
const ids: string[] = [];
|
|
62
|
+
for (const entry of scoped) {
|
|
63
|
+
const model = entry?.model;
|
|
64
|
+
const normalized = normalizeParentModel(model);
|
|
65
|
+
if (normalized) ids.push(`${normalized.provider}/${normalized.id}`);
|
|
66
|
+
}
|
|
67
|
+
return ids;
|
|
68
|
+
}
|
|
69
|
+
|
|
53
70
|
/**
|
|
54
71
|
* Normalize a model id or provider segment for fuzzy comparison: case-fold,
|
|
55
72
|
* treat dots/underscores as dashes (so `4.5` matches `4-5`), and collapse
|
|
@@ -267,12 +284,15 @@ function configuredScopes(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | u
|
|
|
267
284
|
return scope ? (Array.isArray(scope) ? scope : [scope]) : [];
|
|
268
285
|
}
|
|
269
286
|
|
|
270
|
-
function
|
|
271
|
-
const
|
|
272
|
-
.find((entry) => entry.enforce === true && (includeMixed
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
287
|
+
function throwForUnresolvedEnforcedReservedScope(scope: ModelScopeCheckRule | ModelScopeCheckRule[] | undefined, includeMixed = false): void {
|
|
288
|
+
const unresolvedReservedScope = configuredScopes(scope)
|
|
289
|
+
.find((entry) => entry.enforce === true && (includeMixed
|
|
290
|
+
? entry.allow?.some((pattern) => pattern === INHERIT_MODEL || pattern === SCOPED_PATTERN)
|
|
291
|
+
: entry.allow?.length === 1 && (entry.allow[0] === INHERIT_MODEL || entry.allow[0] === SCOPED_PATTERN)));
|
|
292
|
+
if (!unresolvedReservedScope) return;
|
|
293
|
+
const origin = unresolvedReservedScope.origin ?? "modelScope";
|
|
294
|
+
const token = unresolvedReservedScope.allow?.includes(INHERIT_MODEL) ? INHERIT_MODEL : SCOPED_PATTERN;
|
|
295
|
+
throw new Error(`Cannot enforce subagent model scope (${origin}): '${token}' requires a current parent session model.`);
|
|
276
296
|
}
|
|
277
297
|
|
|
278
298
|
function enforceModelScopes(
|
|
@@ -316,7 +336,7 @@ export function resolveSubagentModelOverride(
|
|
|
316
336
|
): string | undefined {
|
|
317
337
|
const trimmed = typeof requestedModel === "string" ? requestedModel.trim() : "";
|
|
318
338
|
const explicit = trimmed && trimmed !== INHERIT_MODEL ? trimmed : undefined;
|
|
319
|
-
if (!parentModel)
|
|
339
|
+
if (!parentModel) throwForUnresolvedEnforcedReservedScope(options?.scope, explicit === undefined || options?.source === "inherited");
|
|
320
340
|
let resolved: string | undefined;
|
|
321
341
|
let resolvedFromRegistry = explicit === undefined;
|
|
322
342
|
if (explicit === undefined) {
|
|
@@ -407,7 +427,7 @@ export function resolveModelSelection(
|
|
|
407
427
|
preferredProvider?: string,
|
|
408
428
|
options?: ResolveModelSelectionOptions,
|
|
409
429
|
): ModelSelectionEvidence {
|
|
410
|
-
if (!model)
|
|
430
|
+
if (!model) throwForUnresolvedEnforcedReservedScope(options?.scope, true);
|
|
411
431
|
const origin = options?.origin ?? (options?.primaryModelFromParent ? "inherited" : "configured");
|
|
412
432
|
const requestedModel = origin === "inherited" ? undefined : model;
|
|
413
433
|
const scopes = configuredScopes(options?.scope);
|