@xzzpig/pi-subagents 0.15.1 → 0.18.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 +178 -1
- package/README.md +5 -3
- package/agents/claude-code-writer.md +1 -0
- package/agents/codex-exec-writer.md +1 -0
- package/agents/cursor-agent-writer.md +1 -0
- package/agents/reviewer.md +3 -2
- package/agents/worker.md +3 -2
- package/docs/agents.md +19 -12
- package/docs/configuration.md +21 -3
- package/docs/extension-api.md +70 -4
- package/docs/fork-extensions.md +23 -15
- package/docs/models.md +5 -3
- package/docs/observability.md +23 -13
- package/docs/standalone-background.md +4 -4
- package/docs/tool-reference.md +40 -19
- package/docs/watchdog.md +2 -0
- package/docs/workflows.md +57 -3
- package/inspector-runner.mjs +1 -1
- package/package.json +14 -8
- package/prompts/council.md +6 -3
- package/runner-peer-loader.mjs +4 -7
- package/runner-peer-preload.mjs +5 -7
- package/skills/pi-subagents/SKILL.md +1 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +5 -2
- package/skills/pi-subagents/references/execution-controls.md +6 -4
- package/skills/pi-subagents/references/management-authoring-rpc.md +3 -3
- package/skills/pi-subagents/references/multi-lane-orchestration.md +8 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +16 -15
- package/src/agents/agent-eject.ts +3 -3
- package/src/agents/agent-management.ts +61 -52
- package/src/agents/agent-memory.ts +90 -3
- package/src/agents/agent-serializer.ts +4 -4
- package/src/agents/agents.ts +125 -51
- package/src/agents/global-npm-root.ts +58 -0
- package/src/agents/proactive-skills.ts +4 -1
- package/src/agents/runtime-agent-registry.ts +14 -11
- package/src/agents/skills.ts +42 -9
- package/src/api/delegation.ts +15 -0
- package/src/api/inspectors.ts +27 -0
- package/src/api/preflight.ts +60 -60
- package/src/extension/doctor.ts +9 -4
- package/src/extension/fanout-child.ts +8 -0
- package/src/extension/index.ts +101 -48
- package/src/extension/rpc.ts +10 -1
- package/src/extension/schemas.ts +12 -6
- package/src/extension/subagent-guide.ts +12 -4
- package/src/extension/tool-activation.ts +197 -0
- package/src/extension/tool-description.ts +1 -1
- package/src/inspectors/ghostty/plugin.ts +13 -1
- package/src/inspectors/plugins.ts +70 -3
- package/src/intercom/intercom-bridge.ts +2 -0
- package/src/intercom/native-supervisor-channel.ts +22 -15
- package/src/intercom/result-intercom.ts +4 -0
- package/src/runs/background/active-async-capacity.ts +3 -25
- package/src/runs/background/async-execution.ts +100 -140
- package/src/runs/background/async-job-tracker.ts +28 -34
- package/src/runs/background/async-resume.ts +16 -8
- package/src/runs/background/async-status.ts +2 -0
- package/src/runs/background/binary-bootstrap.ts +34 -6
- package/src/runs/background/fleet-view.ts +51 -7
- package/src/runs/background/notify.ts +93 -7
- package/src/runs/background/pid-namespace.ts +18 -0
- package/src/runs/background/process-terminal-candidate.ts +98 -0
- package/src/runs/background/process-terminal.ts +17 -96
- package/src/runs/background/result-watcher.ts +1 -1
- package/src/runs/background/retained-children.ts +3 -2
- package/src/runs/background/run-child-session.ts +16 -5
- package/src/runs/background/run-id-resolver.ts +10 -5
- package/src/runs/background/run-status.ts +10 -4
- package/src/runs/background/runner-aliases.ts +25 -15
- package/src/runs/background/runner-child-launch.ts +1 -2
- package/src/runs/background/runner-startup-failure.ts +56 -0
- package/src/runs/background/stale-run-reconciler.ts +19 -3
- package/src/runs/background/subagent-runner-bootstrap.ts +276 -0
- package/src/runs/background/subagent-runner.ts +96 -287
- package/src/runs/background/wait-tool.ts +2 -0
- package/src/runs/background/workflow-terminal-proof.ts +68 -0
- package/src/runs/foreground/execution.ts +217 -250
- package/src/runs/foreground/prompt-audit.ts +3 -9
- package/src/runs/foreground/subagent-executor.ts +377 -119
- package/src/runs/shared/acceptance.ts +167 -68
- package/src/runs/shared/capability-ceiling.ts +4 -1
- package/src/runs/shared/child-hooks.ts +1 -16
- package/src/runs/shared/child-launch.ts +22 -14
- package/src/runs/shared/child-runtime-config.ts +3 -0
- package/src/runs/shared/child-session.ts +52 -2
- package/src/runs/shared/child-tool-plan.ts +23 -113
- package/src/runs/shared/dynamic-fanout.ts +1 -1
- package/src/runs/shared/external-cli-runner.ts +3 -1
- package/src/runs/shared/external-job-bridge.ts +54 -0
- package/src/runs/shared/git-environment.ts +29 -0
- package/src/runs/shared/mcp-config-sources.ts +3 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +1 -1
- package/src/runs/shared/mcp-direct-tool-grant.ts +22 -6
- package/src/runs/shared/model-resolution.ts +6 -1
- package/src/runs/shared/nested-events.ts +67 -55
- package/src/runs/shared/orca-progress-tabs.ts +3 -2
- package/src/runs/shared/parallel-utils.ts +2 -1
- package/src/runs/shared/pi-spawn.ts +92 -6
- package/src/runs/shared/profile-launch-env.ts +10 -2
- package/src/runs/shared/single-output.ts +11 -2
- package/src/runs/shared/structured-output.ts +227 -7
- package/src/runs/shared/subagent-control.ts +2 -16
- package/src/runs/shared/subagent-prompt-runtime.ts +27 -5
- package/src/runs/shared/tool-availability.ts +2 -2
- package/src/runs/shared/tool-budget.ts +21 -0
- package/src/runs/shared/usage-reconciliation.ts +73 -0
- package/src/runs/shared/worktree.ts +35 -8
- package/src/shared/child-session-name.ts +4 -2
- package/src/shared/fork-context.ts +11 -4
- package/src/shared/launch-contract.ts +1 -1
- package/src/shared/pruned-fork.ts +69 -56
- package/src/shared/types.ts +52 -16
- package/src/slash/delegation-adapters.ts +25 -1
- package/src/slash/prompt-template-bridge.ts +16 -1
- package/src/slash/prompt-workflows.ts +12 -1
- package/src/slash/slash-commands.ts +7 -241
- package/src/slash/subagent-cost.ts +313 -0
- package/src/slash/subagents-admin.ts +28 -29
- package/src/tui/fleet-status.ts +24 -2
- package/src/tui/fleet.ts +7 -4
- package/src/tui/render.ts +53 -19
- package/src/watchdog/diff-tool.ts +24 -3
- package/src/watchdog/permission-arbiter.ts +13 -15
- package/src/watchdog/register-child.ts +10 -2
- package/src/watchdog/review.ts +14 -14
- package/src/watchdog/runtime.ts +2 -1
- package/src/watchdog/turn-delta.ts +11 -5
- package/src/workflows/scripted-workflow.ts +109 -23
- package/src/workflows/workflow-child-summary.ts +4 -2
- package/src/workflows/workflow-settlement.ts +4 -1
- package/src/runs/shared/completion-evidence.ts +0 -89
- package/src/runs/shared/completion-guard.ts +0 -255
- package/src/runs/shared/llm-intent-arbiter.ts +0 -321
- package/src/runs/shared/task-intent.ts +0 -244
|
@@ -138,17 +138,17 @@ export function resolveNestedRoute(route: NestedRoute): NestedRoute {
|
|
|
138
138
|
const { rootRunId, capabilityToken } = route;
|
|
139
139
|
validateRouteShape(route);
|
|
140
140
|
const routeFile = path.join(commonRouteRoot(route), ROUTE_FILE);
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
141
|
+
let metadata: { rootRunId?: unknown; capabilityToken?: unknown };
|
|
142
|
+
try {
|
|
143
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(routeFile, "utf-8"));
|
|
144
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
145
|
+
throw new Error("route metadata must be an object");
|
|
146
|
+
}
|
|
147
|
+
metadata = parsed as { rootRunId?: unknown; capabilityToken?: unknown };
|
|
148
|
+
} catch (error) {
|
|
149
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
150
|
+
throw new Error(`Nested event route metadata is unreadable: ${message}`);
|
|
151
|
+
}
|
|
152
152
|
if (metadata.rootRunId !== rootRunId || metadata.capabilityToken !== capabilityToken) {
|
|
153
153
|
throw new Error("Nested event route metadata does not match the provided root id and capability token.");
|
|
154
154
|
}
|
|
@@ -315,16 +315,16 @@ function sanitizeStep(input: unknown, depth: number): NestedStepSummary | undefi
|
|
|
315
315
|
: "pending";
|
|
316
316
|
const model = stringValue(raw.model);
|
|
317
317
|
const thinking = THINKING_LEVELS.find((level) => level === raw.thinking);
|
|
318
|
-
|
|
319
|
-
|
|
318
|
+
const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
|
|
319
|
+
const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
|
|
320
320
|
return {
|
|
321
321
|
agent,
|
|
322
322
|
status,
|
|
323
323
|
...(model ? { model } : {}),
|
|
324
324
|
...(thinking ? { thinking } : {}),
|
|
325
325
|
...(stringValue(raw.sessionName, 256) ? { sessionName: stringValue(raw.sessionName, 256) } : {}),
|
|
326
|
-
|
|
327
|
-
|
|
326
|
+
...(sandbox ? { sandbox } : {}),
|
|
327
|
+
...(permissionProfile ? { permissionProfile } : {}),
|
|
328
328
|
...(stringValue(raw.sessionFile, 2048) ? { sessionFile: stringValue(raw.sessionFile, 2048) } : {}),
|
|
329
329
|
...(raw.activityState === "active_long_running" || raw.activityState === "needs_attention" ? { activityState: raw.activityState } : {}),
|
|
330
330
|
...(clampNumber(raw.lastActivityAt) !== undefined ? { lastActivityAt: clampNumber(raw.lastActivityAt) } : {}),
|
|
@@ -357,8 +357,8 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
|
|
|
357
357
|
: undefined;
|
|
358
358
|
const totalTokens = sanitizeTokenUsage(raw.totalTokens);
|
|
359
359
|
const totalCost = sanitizeCost(raw.totalCost);
|
|
360
|
-
|
|
361
|
-
|
|
360
|
+
const sandbox = validateSandboxProfileNameOptional(raw.sandbox);
|
|
361
|
+
const permissionProfile = validatePermissionProfileNameOptional(raw.permissionProfile);
|
|
362
362
|
return {
|
|
363
363
|
id: raw.id,
|
|
364
364
|
parentRunId: raw.parentRunId,
|
|
@@ -382,8 +382,8 @@ export function sanitizeSummary(input: unknown, depth = 0): NestedRunSummary | u
|
|
|
382
382
|
...(stringValue(raw.capabilityToken, 128) ? { capabilityToken: stringValue(raw.capabilityToken, 128) } : {}),
|
|
383
383
|
...(raw.mode === "single" || raw.mode === "parallel" || raw.mode === "chain" ? { mode: raw.mode } : {}),
|
|
384
384
|
...(stringValue(raw.agent, 128) ? { agent: stringValue(raw.agent, 128) } : {}),
|
|
385
|
-
|
|
386
|
-
|
|
385
|
+
...(sandbox ? { sandbox } : {}),
|
|
386
|
+
...(permissionProfile ? { permissionProfile } : {}),
|
|
387
387
|
...(Array.isArray(raw.agents) ? { agents: raw.agents.map((agent) => stringValue(agent, 128)).filter((agent): agent is string => Boolean(agent)).slice(0, MAX_STEPS) } : {}),
|
|
388
388
|
|
|
389
389
|
...(clampNumber(raw.currentStep) !== undefined ? { currentStep: clampNumber(raw.currentStep) } : {}),
|
|
@@ -634,6 +634,18 @@ export interface NestedRunMatch {
|
|
|
634
634
|
run: NestedRunSummary;
|
|
635
635
|
}
|
|
636
636
|
|
|
637
|
+
export function retainNestedLookupRoute(
|
|
638
|
+
state: Pick<SubagentState, "currentSessionId" | "retainedNestedLookupRoutes">,
|
|
639
|
+
route: NestedRouteInfo | undefined,
|
|
640
|
+
sessionId: string | undefined,
|
|
641
|
+
): void {
|
|
642
|
+
if (!route || !sessionId || sessionId !== state.currentSessionId) return;
|
|
643
|
+
if (state.retainedNestedLookupRoutes?.sessionId !== sessionId) {
|
|
644
|
+
state.retainedNestedLookupRoutes = { sessionId, routes: new Map() };
|
|
645
|
+
}
|
|
646
|
+
state.retainedNestedLookupRoutes.routes.set(route.rootRunId, route);
|
|
647
|
+
}
|
|
648
|
+
|
|
637
649
|
export interface NestedRunResolutionScope {
|
|
638
650
|
routes: NestedRoute[];
|
|
639
651
|
descendantOf?: { parentRunId: string; parentStepIndex?: number };
|
|
@@ -1009,7 +1021,7 @@ export function hasLiveNestedDescendants(children: NestedRunSummary[] | undefine
|
|
|
1009
1021
|
}
|
|
1010
1022
|
|
|
1011
1023
|
export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: string, fallback: { id: string; parentRunId: string; parentStepIndex?: number; depth: number; path?: Array<{ runId: string; stepIndex?: number; agent?: string }>; mode?: SubagentRunMode; ts: number }): NestedRunSummary {
|
|
1012
|
-
|
|
1024
|
+
const sandbox = validateSandboxProfileNameOptional(status.sandbox);
|
|
1013
1025
|
return {
|
|
1014
1026
|
id: status.runId || fallback.id,
|
|
1015
1027
|
parentRunId: fallback.parentRunId,
|
|
@@ -1020,7 +1032,7 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
|
|
|
1020
1032
|
...(status.pid ? { pid: status.pid } : {}),
|
|
1021
1033
|
...(status.sessionId ? { sessionId: status.sessionId } : {}),
|
|
1022
1034
|
mode: status.mode ?? fallback.mode,
|
|
1023
|
-
|
|
1035
|
+
...(sandbox ? { sandbox } : {}),
|
|
1024
1036
|
...(status.steps?.length === 1 && status.steps[0]?.model ? { model: status.steps[0].model } : {}),
|
|
1025
1037
|
...(status.steps?.length === 1 && status.steps[0]?.thinking ? { thinking: status.steps[0].thinking } : {}),
|
|
1026
1038
|
...(status.steps?.length === 1 && status.steps[0]?.sessionName ? { sessionName: status.steps[0].sessionName } : {}),
|
|
@@ -1052,40 +1064,40 @@ export function nestedSummaryFromAsyncStatus(status: AsyncStatus, asyncDir: stri
|
|
|
1052
1064
|
...(status.endedAt !== undefined ? { endedAt: status.endedAt } : {}),
|
|
1053
1065
|
lastUpdate: status.lastUpdate ?? fallback.ts,
|
|
1054
1066
|
...(status.sessionFile ? { sessionFile: status.sessionFile } : {}),
|
|
1055
|
-
|
|
1056
|
-
|
|
1057
|
-
|
|
1058
|
-
|
|
1059
|
-
|
|
1060
|
-
|
|
1061
|
-
|
|
1062
|
-
|
|
1063
|
-
|
|
1064
|
-
|
|
1065
|
-
|
|
1066
|
-
|
|
1067
|
-
|
|
1068
|
-
|
|
1069
|
-
|
|
1070
|
-
|
|
1071
|
-
|
|
1072
|
-
|
|
1073
|
-
|
|
1074
|
-
|
|
1075
|
-
|
|
1076
|
-
|
|
1077
|
-
|
|
1078
|
-
|
|
1079
|
-
|
|
1080
|
-
|
|
1081
|
-
|
|
1082
|
-
|
|
1083
|
-
|
|
1084
|
-
|
|
1085
|
-
|
|
1086
|
-
|
|
1087
|
-
|
|
1088
|
-
|
|
1067
|
+
...(status.steps?.length ? {
|
|
1068
|
+
steps: status.steps.map((step, index) => {
|
|
1069
|
+
const stepSandbox = validateSandboxProfileNameOptional(step.sandbox);
|
|
1070
|
+
return {
|
|
1071
|
+
agent: step.agent,
|
|
1072
|
+
...(step.sessionName ? { sessionName: step.sessionName } : {}),
|
|
1073
|
+
status: step.status,
|
|
1074
|
+
...(step.model ? { model: step.model } : {}),
|
|
1075
|
+
...(step.thinking ? { thinking: step.thinking } : {}),
|
|
1076
|
+
...(stepSandbox ? { sandbox: stepSandbox } : {}),
|
|
1077
|
+
...(step.sessionFile ? { sessionFile: step.sessionFile } : {}),
|
|
1078
|
+
...(step.activityState ? { activityState: step.activityState } : {}),
|
|
1079
|
+
...(step.lastActivityAt !== undefined ? { lastActivityAt: step.lastActivityAt } : {}),
|
|
1080
|
+
...(step.currentTool ? { currentTool: step.currentTool } : {}),
|
|
1081
|
+
...(step.currentToolStartedAt !== undefined ? { currentToolStartedAt: step.currentToolStartedAt } : {}),
|
|
1082
|
+
...(step.currentPath ? { currentPath: step.currentPath } : {}),
|
|
1083
|
+
...(step.turnCount !== undefined ? { turnCount: step.turnCount } : {}),
|
|
1084
|
+
...(step.toolCount !== undefined ? { toolCount: step.toolCount } : {}),
|
|
1085
|
+
...(step.startedAt !== undefined ? { startedAt: step.startedAt } : {}),
|
|
1086
|
+
...(step.endedAt !== undefined ? { endedAt: step.endedAt } : {}),
|
|
1087
|
+
...(step.error ? { error: step.error } : {}),
|
|
1088
|
+
...(step.launchResolvedExtensions ? { launchResolvedExtensions: step.launchResolvedExtensions } : {}),
|
|
1089
|
+
...runtimeAcknowledgedEntry(step.runtimeAcknowledgedExtensions),
|
|
1090
|
+
...(step.timedOut !== undefined ? { timedOut: step.timedOut } : {}),
|
|
1091
|
+
...(step.stopped !== undefined ? { stopped: step.stopped } : {}),
|
|
1092
|
+
...(step.turnBudget ? { turnBudget: step.turnBudget } : {}),
|
|
1093
|
+
...(step.turnBudgetExceeded !== undefined ? { turnBudgetExceeded: step.turnBudgetExceeded } : {}),
|
|
1094
|
+
...(step.wrapUpRequested !== undefined ? { wrapUpRequested: step.wrapUpRequested } : {}),
|
|
1095
|
+
...(step.processTerminal ? { processTerminal: sanitizeProcessTerminal(step.processTerminal, { runId: status.runId || fallback.id, runnerProcessInstanceId: step.processTerminal.runnerProcessInstanceId }, `${asyncDir}/status.json step ${index}`) } : {}),
|
|
1096
|
+
...(step.capabilityCeiling ? { capabilityCeiling: step.capabilityCeiling } : {}),
|
|
1097
|
+
...(step.capabilityAudit ? { capabilityAudit: step.capabilityAudit } : {}),
|
|
1098
|
+
};
|
|
1099
|
+
}).slice(0, MAX_STEPS),
|
|
1100
|
+
} : {}),
|
|
1089
1101
|
};
|
|
1090
1102
|
}
|
|
1091
1103
|
|
|
@@ -105,9 +105,10 @@ const VIEWER_SCRIPT = [
|
|
|
105
105
|
"if(state==='escape'){if(char==='[')state='csi';else if(char===']')state='osc';else if(char==='P'||char==='X'||char==='^'||char==='_')state='string';else if(code<32||code>47)state='text';continue}",
|
|
106
106
|
"if(state==='csi'){if(code>=64&&code<=126)state='text';continue}",
|
|
107
107
|
"if(state==='osc'){if(code===7)state='text';else if(code===27)state='osc-escape';continue}",
|
|
108
|
-
"
|
|
108
|
+
"const BACKSLASH=String.fromCharCode(92);",
|
|
109
|
+
"if(state==='osc-escape'){state=char===BACKSLASH?'text':code===27?'osc-escape':'osc';continue}",
|
|
109
110
|
"if(state==='string'){if(code===27)state='string-escape';continue}",
|
|
110
|
-
"if(state==='string-escape')state=char===
|
|
111
|
+
"if(state==='string-escape')state=char===BACKSLASH?'text':code===27?'string-escape':'string';",
|
|
111
112
|
"}return output}",
|
|
112
113
|
"function write(buffer){const output=sanitize(decoder.write(buffer));if(output)process.stdout.write(output)}",
|
|
113
114
|
"function pump(){",
|
|
@@ -53,13 +53,14 @@ export interface RunnerSubagentStep {
|
|
|
53
53
|
tools?: string[];
|
|
54
54
|
excludeTools?: string[];
|
|
55
55
|
allowNestedSubagents?: boolean;
|
|
56
|
+
/** Resolved selected-agent policy for launches made by this child. */
|
|
57
|
+
allowedAgents?: string[];
|
|
56
58
|
extensions?: string[];
|
|
57
59
|
subagentOnlyExtensions?: string[];
|
|
58
60
|
/** Private immutable host policy snapshot serialized to the native runner. */
|
|
59
61
|
requiredExtensions?: import("../../shared/required-child-extensions.ts").RequiredChildExtensionSnapshot;
|
|
60
62
|
mcpDirectTools?: string[];
|
|
61
63
|
mutationTools?: string[];
|
|
62
|
-
completionGuard?: boolean;
|
|
63
64
|
sandbox?: string;
|
|
64
65
|
permissionProfile?: string;
|
|
65
66
|
systemPrompt?: string | null;
|
|
@@ -5,20 +5,25 @@ import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
|
5
5
|
|
|
6
6
|
export const PI_CODING_AGENT_PACKAGE = "@earendil-works/pi-coding-agent";
|
|
7
7
|
export const PI_SUBAGENT_PI_BINARY_ENV = "PI_SUBAGENT_PI_BINARY";
|
|
8
|
+
export const PI_PACKAGE_DIR_ENV = "PI_PACKAGE_DIR";
|
|
8
9
|
|
|
9
10
|
export function findPiPackageRootFromEntry(
|
|
10
11
|
entryPoint: string,
|
|
12
|
+
deps: Pick<PiSpawnDeps, "platform" | "existsSync" | "readFileSync"> = {},
|
|
11
13
|
): string | undefined {
|
|
12
|
-
|
|
13
|
-
|
|
14
|
-
|
|
15
|
-
|
|
16
|
-
|
|
14
|
+
const pathApi = (deps.platform ?? process.platform) === "win32" ? path.win32 : path.posix;
|
|
15
|
+
const existsSync = deps.existsSync ?? fs.existsSync;
|
|
16
|
+
const readFileSync = deps.readFileSync ?? ((filePath, encoding) => fs.readFileSync(filePath, encoding));
|
|
17
|
+
let dir = pathApi.dirname(entryPoint);
|
|
18
|
+
while (dir !== pathApi.dirname(dir)) {
|
|
19
|
+
const packageJsonPath = pathApi.join(dir, "package.json");
|
|
20
|
+
if (existsSync(packageJsonPath)) {
|
|
21
|
+
const pkg = JSON.parse(readFileSync(packageJsonPath, "utf-8")) as {
|
|
17
22
|
name?: unknown;
|
|
18
23
|
};
|
|
19
24
|
if (pkg.name === PI_CODING_AGENT_PACKAGE) return dir;
|
|
20
25
|
}
|
|
21
|
-
dir =
|
|
26
|
+
dir = pathApi.dirname(dir);
|
|
22
27
|
}
|
|
23
28
|
return undefined;
|
|
24
29
|
}
|
|
@@ -59,6 +64,87 @@ export interface PiSpawnDeps {
|
|
|
59
64
|
env?: NodeJS.ProcessEnv;
|
|
60
65
|
}
|
|
61
66
|
|
|
67
|
+
export type RunningPiPackageRoot =
|
|
68
|
+
| { root: string; source: "argv" | "PI_PACKAGE_DIR" | "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT" | "bun-adjacent" | "bun-share" }
|
|
69
|
+
| { reason: string };
|
|
70
|
+
|
|
71
|
+
function validateRunningPiRoot(
|
|
72
|
+
root: string,
|
|
73
|
+
source: Exclude<RunningPiPackageRoot, { reason: string }>["source"],
|
|
74
|
+
readFileSync: (filePath: string, encoding: "utf-8") => string,
|
|
75
|
+
manifestPath: string,
|
|
76
|
+
): RunningPiPackageRoot {
|
|
77
|
+
const sourceLabel = source === "PI_SUBAGENTS_PI_CODING_AGENT_PACKAGE_ROOT" ? `${source} override` : source;
|
|
78
|
+
let parsed: unknown;
|
|
79
|
+
try {
|
|
80
|
+
parsed = JSON.parse(readFileSync(manifestPath, "utf-8"));
|
|
81
|
+
} catch (error) {
|
|
82
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
83
|
+
return { reason: `Could not read a valid Pi package manifest at ${manifestPath} (${sourceLabel}): ${message}` };
|
|
84
|
+
}
|
|
85
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed) || (parsed as { name?: unknown }).name !== PI_CODING_AGENT_PACKAGE) {
|
|
86
|
+
return { reason: `${manifestPath} is not ${PI_CODING_AGENT_PACKAGE} (${sourceLabel})` };
|
|
87
|
+
}
|
|
88
|
+
return { root, source };
|
|
89
|
+
}
|
|
90
|
+
|
|
91
|
+
/** Resolve only package roots that can be attributed to the process that owns this session. */
|
|
92
|
+
export function resolveRunningPiPackageRoot(deps: PiSpawnDeps = {}): RunningPiPackageRoot | undefined {
|
|
93
|
+
const env = deps.env ?? process.env;
|
|
94
|
+
const platform = deps.platform ?? process.platform;
|
|
95
|
+
const pathApi = platform === "win32" ? path.win32 : path.posix;
|
|
96
|
+
const argv1 = deps.argv1 ?? process.argv[1];
|
|
97
|
+
const readFileSync = deps.readFileSync ?? ((filePath, encoding) => fs.readFileSync(filePath, encoding));
|
|
98
|
+
const existsSync = deps.existsSync ?? fs.existsSync;
|
|
99
|
+
const realpathSync = deps.realpathSync ?? fs.realpathSync;
|
|
100
|
+
|
|
101
|
+
if (argv1) {
|
|
102
|
+
let entry: string | undefined;
|
|
103
|
+
try {
|
|
104
|
+
entry = realpathSync(argv1);
|
|
105
|
+
} catch {
|
|
106
|
+
// Virtual Bun entries and non-filesystem launchers continue to explicit host evidence.
|
|
107
|
+
}
|
|
108
|
+
if (entry) {
|
|
109
|
+
try {
|
|
110
|
+
const root = findPiPackageRootFromEntry(entry, { platform, existsSync, readFileSync });
|
|
111
|
+
if (root) return { root, source: "argv" };
|
|
112
|
+
} catch (error) {
|
|
113
|
+
return { reason: `Could not inspect the running Pi entry at ${entry}: ${error instanceof Error ? error.message : String(error)}` };
|
|
114
|
+
}
|
|
115
|
+
}
|
|
116
|
+
}
|
|
117
|
+
|
|
118
|
+
for (const [source, value] of [
|
|
119
|
+
[PI_PACKAGE_DIR_ENV, env[PI_PACKAGE_DIR_ENV]],
|
|
120
|
+
[PI_CODING_AGENT_PACKAGE_ROOT_ENV, env[PI_CODING_AGENT_PACKAGE_ROOT_ENV]],
|
|
121
|
+
] as const) {
|
|
122
|
+
const root = value?.trim();
|
|
123
|
+
if (root) return validateRunningPiRoot(root, source, readFileSync, pathApi.join(root, "package.json"));
|
|
124
|
+
}
|
|
125
|
+
|
|
126
|
+
const bunVersion = deps.bunVersion ?? process.versions.bun;
|
|
127
|
+
if (!bunVersion || !argv1 || !/^(?:\/\$bunfs\/|B:[\\/]~BUN[\\/])/.test(argv1)) return undefined;
|
|
128
|
+
const imagePath = deps.execPath ?? process.execPath;
|
|
129
|
+
let canonicalImage = imagePath;
|
|
130
|
+
try {
|
|
131
|
+
canonicalImage = realpathSync(imagePath);
|
|
132
|
+
} catch {
|
|
133
|
+
// A validated adjacent manifest can still establish ownership when canonicalization is unavailable.
|
|
134
|
+
}
|
|
135
|
+
const imageDir = pathApi.dirname(canonicalImage);
|
|
136
|
+
const candidates = [
|
|
137
|
+
{ root: imageDir, source: "bun-adjacent" as const },
|
|
138
|
+
{ root: pathApi.resolve(imageDir, "..", "share", "pi-coding-agent"), source: "bun-share" as const },
|
|
139
|
+
];
|
|
140
|
+
for (const candidate of candidates) {
|
|
141
|
+
const manifestPath = pathApi.join(candidate.root, "package.json");
|
|
142
|
+
if (!existsSync(manifestPath)) continue;
|
|
143
|
+
return validateRunningPiRoot(candidate.root, candidate.source, readFileSync, manifestPath);
|
|
144
|
+
}
|
|
145
|
+
return undefined;
|
|
146
|
+
}
|
|
147
|
+
|
|
62
148
|
/** Compiled Pi's entrypoint is virtual; execPath is the real (possibly renamed) image. */
|
|
63
149
|
export function resolveBunPiExecutable(deps: PiSpawnDeps = {}): string | undefined {
|
|
64
150
|
const bunVersion = deps.bunVersion ?? process.versions.bun;
|
|
@@ -30,7 +30,8 @@ export interface ProfileLaunchEnvInput {
|
|
|
30
30
|
permissionProfile?: string;
|
|
31
31
|
/** Parent-authoritative trust state for profile-aware project config merging. */
|
|
32
32
|
projectTrusted?: boolean;
|
|
33
|
-
/**
|
|
33
|
+
/** Trusted project cwd; profile project config applies when the child cwd is within it
|
|
34
|
+
* (equal or a subdirectory), mirroring the platform's ancestor-inheriting trust decisions. */
|
|
34
35
|
trustedProjectCwd?: string;
|
|
35
36
|
host: "parent" | "runner";
|
|
36
37
|
}
|
|
@@ -48,7 +49,14 @@ export interface ProfileLaunchEnv {
|
|
|
48
49
|
|
|
49
50
|
function hasTrustedProfileProjectCwd(input: Pick<ProfileLaunchEnvInput, "cwd" | "projectTrusted" | "trustedProjectCwd">): boolean {
|
|
50
51
|
if (input.projectTrusted !== true || !input.cwd || !input.trustedProjectCwd) return false;
|
|
51
|
-
|
|
52
|
+
// Platform trust is ancestor-inheriting (findNearestTrustEntry walks up from
|
|
53
|
+
// the child cwd): a child launched anywhere inside the trusted project tree —
|
|
54
|
+
// the project root or any subdirectory — inherits the trust decision observed
|
|
55
|
+
// at the trusted project cwd, so its project config participates without a
|
|
56
|
+
// separate trust decision (spec: 子目录启动继承信任).
|
|
57
|
+
const trusted = path.resolve(input.trustedProjectCwd);
|
|
58
|
+
const child = path.resolve(input.cwd);
|
|
59
|
+
return child === trusted || child.startsWith(`${trusted}${path.sep}`);
|
|
52
60
|
}
|
|
53
61
|
|
|
54
62
|
export function buildProfileLaunchEnv(input: ProfileLaunchEnvInput, toolPlan: Pick<PiLaunchToolPlan, "sandboxExtension">): ProfileLaunchEnv {
|
|
@@ -2,7 +2,16 @@ import * as fs from "node:fs";
|
|
|
2
2
|
import * as path from "node:path";
|
|
3
3
|
import type { Message } from "@earendil-works/pi-ai";
|
|
4
4
|
import type { OutputMode, SavedOutputReference } from "../../shared/types.ts";
|
|
5
|
-
|
|
5
|
+
|
|
6
|
+
const READ_ONLY_OUTPUT_TOOLS = new Set([
|
|
7
|
+
"read", "grep", "find", "ls", "web_search", "fetch_content", "get_search_content",
|
|
8
|
+
"source_check", "intercom", "contact_supervisor", "structured_output", "watchdog_diff",
|
|
9
|
+
]);
|
|
10
|
+
|
|
11
|
+
function hasOutputWriteCapability(tools: string[] | undefined, mcpDirectTools: string[] | undefined): boolean {
|
|
12
|
+
if ((mcpDirectTools?.length ?? 0) > 0 || tools === undefined) return true;
|
|
13
|
+
return tools.some((tool) => !READ_ONLY_OUTPUT_TOOLS.has(tool));
|
|
14
|
+
}
|
|
6
15
|
|
|
7
16
|
export interface SingleOutputSnapshot {
|
|
8
17
|
exists: boolean;
|
|
@@ -93,7 +102,7 @@ interface OutputInstructionCapabilities {
|
|
|
93
102
|
}
|
|
94
103
|
|
|
95
104
|
function formatOutputPathInstruction(outputPath: string, capabilities?: OutputInstructionCapabilities): string {
|
|
96
|
-
const delivery = !capabilities ||
|
|
105
|
+
const delivery = !capabilities || hasOutputWriteCapability(capabilities.tools, capabilities.mcpDirectTools)
|
|
97
106
|
? `Write your findings to exactly this path: ${outputPath}`
|
|
98
107
|
: [
|
|
99
108
|
"Return the complete artifact in your final response.",
|
|
@@ -3,12 +3,81 @@ import { createRequire } from "node:module";
|
|
|
3
3
|
import * as os from "node:os";
|
|
4
4
|
import * as path from "node:path";
|
|
5
5
|
import { pathToFileURL } from "node:url";
|
|
6
|
+
import type { Message } from "@earendil-works/pi-ai";
|
|
6
7
|
import { PI_CODING_AGENT_PACKAGE_ROOT_ENV } from "../../shared/utils.ts";
|
|
7
8
|
import type { JsonSchemaObject } from "../../shared/types.ts";
|
|
8
9
|
import type { ResolvedAcceptanceReportMode } from "./acceptance.ts";
|
|
9
10
|
|
|
10
11
|
export const MISSING_STRUCTURED_OUTPUT_CALL_ERROR = "Missing structured_output call; this step has outputSchema and must finish by calling structured_output.";
|
|
11
12
|
export const MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR = "Missing acceptanceReport in structured_output call; acceptance.report is \"on\".";
|
|
13
|
+
export const STRUCTURED_OUTPUT_REJECTION_ERROR = "structured_output was invoked but no valid output was captured.";
|
|
14
|
+
export const INVALID_STRUCTURED_OUTPUT_SCHEMA_ERROR = "Structured output invocation was rejected: invalid outputSchema.";
|
|
15
|
+
export const STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE_ERROR = "Structured output invocation was rejected: validator unavailable.";
|
|
16
|
+
export const MAX_STRUCTURED_OUTPUT_REJECTION_ERROR_BYTES = 4096;
|
|
17
|
+
|
|
18
|
+
function utf8Prefix(value: string, maxBytes: number): string {
|
|
19
|
+
if (Buffer.byteLength(value, "utf8") <= maxBytes) return value;
|
|
20
|
+
const suffix = "...";
|
|
21
|
+
const contentLimit = maxBytes - Buffer.byteLength(suffix, "utf8");
|
|
22
|
+
let bytes = 0;
|
|
23
|
+
let result = "";
|
|
24
|
+
for (const character of value) {
|
|
25
|
+
const characterBytes = Buffer.byteLength(character, "utf8");
|
|
26
|
+
if (bytes + characterBytes > contentLimit) break;
|
|
27
|
+
result += character;
|
|
28
|
+
bytes += characterBytes;
|
|
29
|
+
}
|
|
30
|
+
return result + suffix;
|
|
31
|
+
}
|
|
32
|
+
|
|
33
|
+
function messageText(content: unknown): string {
|
|
34
|
+
if (typeof content === "string") return content;
|
|
35
|
+
if (!Array.isArray(content)) return "";
|
|
36
|
+
return content
|
|
37
|
+
.filter((part): part is { type: "text"; text: string } => Boolean(part) && typeof part === "object" && (part as { type?: unknown }).type === "text" && typeof (part as { text?: unknown }).text === "string")
|
|
38
|
+
.map((part) => part.text)
|
|
39
|
+
.join("\n");
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function sanitizeStructuredOutputRejection(text: string): string {
|
|
43
|
+
const withoutControls = text.replace(/\x1b\[[0-?]*[ -/]*[@-~]/g, "").replace(/[\u0000-\u0008\u000b\u000c\u000e-\u001f\u007f]/g, "");
|
|
44
|
+
if (/invalid outputSchema(?:\s*:|$)/i.test(withoutControls)) return INVALID_STRUCTURED_OUTPUT_SCHEMA_ERROR;
|
|
45
|
+
if (/failed to validate structured output:|cannot load typebox\/compile/i.test(withoutControls)) return STRUCTURED_OUTPUT_VALIDATOR_UNAVAILABLE_ERROR;
|
|
46
|
+
const validationMarker = "Structured output validation failed:";
|
|
47
|
+
const markerIndex = withoutControls.indexOf(validationMarker);
|
|
48
|
+
const diagnostic = markerIndex >= 0 ? withoutControls.slice(markerIndex) : withoutControls;
|
|
49
|
+
const lines = diagnostic.split(/\r?\n/).filter((line) => {
|
|
50
|
+
const trimmed = line.trim();
|
|
51
|
+
return trimmed.length > 0
|
|
52
|
+
&& !/^at\s/.test(trimmed)
|
|
53
|
+
&& !/^(?:arguments?|parameters?|submitted value|input|outputSchema|schema|stack)\s*:/i.test(trimmed);
|
|
54
|
+
});
|
|
55
|
+
const sanitized = lines.join("\n")
|
|
56
|
+
.replace(/\b(received|actual|got)(?:\s+value)?\s*[:=]\s*(?:"(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\{[^\n]*\}|\[[^\n]*\]|\S+)/gi, "$1: [redacted]")
|
|
57
|
+
.trim();
|
|
58
|
+
return sanitized || STRUCTURED_OUTPUT_REJECTION_ERROR;
|
|
59
|
+
}
|
|
60
|
+
|
|
61
|
+
/** Returns bounded evidence from the latest failed structured_output result in a terminal transcript. */
|
|
62
|
+
export function formatStructuredOutputRejectionError(messages: readonly Message[]): string {
|
|
63
|
+
const toolCallIds = new Set<string>();
|
|
64
|
+
for (const message of messages) {
|
|
65
|
+
if (message.role !== "assistant" || !Array.isArray(message.content)) continue;
|
|
66
|
+
for (const part of message.content) {
|
|
67
|
+
const call = part as { type?: unknown; id?: unknown; name?: unknown };
|
|
68
|
+
if (call.type === "toolCall" && call.name === "structured_output" && typeof call.id === "string") toolCallIds.add(call.id);
|
|
69
|
+
}
|
|
70
|
+
}
|
|
71
|
+
for (let index = messages.length - 1; index >= 0; index--) {
|
|
72
|
+
const message = messages[index] as Message & { toolCallId?: unknown; toolName?: unknown; isError?: unknown };
|
|
73
|
+
if (message.role !== "toolResult" || message.isError !== true) continue;
|
|
74
|
+
const matchingName = message.toolName === "structured_output";
|
|
75
|
+
const matchingId = typeof message.toolCallId === "string" && toolCallIds.has(message.toolCallId);
|
|
76
|
+
if (!matchingName && !matchingId) continue;
|
|
77
|
+
return utf8Prefix(sanitizeStructuredOutputRejection(messageText(message.content)), MAX_STRUCTURED_OUTPUT_REJECTION_ERROR_BYTES);
|
|
78
|
+
}
|
|
79
|
+
return STRUCTURED_OUTPUT_REJECTION_ERROR;
|
|
80
|
+
}
|
|
12
81
|
|
|
13
82
|
export interface StructuredOutputRuntime {
|
|
14
83
|
schema: JsonSchemaObject;
|
|
@@ -75,7 +144,15 @@ export function createStructuredOutputToolParameters(schema: JsonSchemaObject, o
|
|
|
75
144
|
|
|
76
145
|
interface CompiledJsonSchema {
|
|
77
146
|
Check(value: unknown): boolean;
|
|
78
|
-
Errors(value: unknown): Iterable<
|
|
147
|
+
Errors(value: unknown): Iterable<JsonSchemaValidationError>;
|
|
148
|
+
}
|
|
149
|
+
|
|
150
|
+
interface JsonSchemaValidationError {
|
|
151
|
+
keyword?: string;
|
|
152
|
+
schemaPath?: string;
|
|
153
|
+
instancePath?: string;
|
|
154
|
+
params?: { failingKeyword?: string; requiredProperties?: string[] };
|
|
155
|
+
message?: string;
|
|
79
156
|
}
|
|
80
157
|
|
|
81
158
|
type CompileJsonSchema = (schema: unknown) => CompiledJsonSchema;
|
|
@@ -123,6 +200,142 @@ function loadCompile(): Promise<CompileJsonSchema> {
|
|
|
123
200
|
return cachedCompile;
|
|
124
201
|
}
|
|
125
202
|
|
|
203
|
+
function jsonPointerTarget(root: unknown, pointer: string): unknown {
|
|
204
|
+
if (pointer === "#") return root;
|
|
205
|
+
if (!pointer.startsWith("#/")) return undefined;
|
|
206
|
+
let current = root;
|
|
207
|
+
for (const encoded of pointer.slice(2).split("/")) {
|
|
208
|
+
if (!current || typeof current !== "object") return undefined;
|
|
209
|
+
const key = encoded.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
210
|
+
current = (current as Record<string, unknown>)[key];
|
|
211
|
+
}
|
|
212
|
+
return current;
|
|
213
|
+
}
|
|
214
|
+
|
|
215
|
+
function resolveLocalRefs(root: unknown, node: unknown): Record<string, unknown> | undefined {
|
|
216
|
+
const seen = new Set<unknown>();
|
|
217
|
+
while (node && typeof node === "object" && !Array.isArray(node) && !seen.has(node)) {
|
|
218
|
+
seen.add(node);
|
|
219
|
+
const record = node as Record<string, unknown>;
|
|
220
|
+
if (typeof record.$ref !== "string" || !record.$ref.startsWith("#")) return record;
|
|
221
|
+
node = jsonPointerTarget(root, record.$ref);
|
|
222
|
+
}
|
|
223
|
+
return undefined;
|
|
224
|
+
}
|
|
225
|
+
|
|
226
|
+
type InstanceSchemaStep = { kind: "property"; key: string } | { kind: "index"; index: number };
|
|
227
|
+
|
|
228
|
+
function traverseInstanceSchema(root: unknown, instancePath: string | undefined): { node: Record<string, unknown>; steps: InstanceSchemaStep[] } | undefined {
|
|
229
|
+
let node = resolveLocalRefs(root, root);
|
|
230
|
+
const steps: InstanceSchemaStep[] = [];
|
|
231
|
+
for (const encoded of instancePath?.replace(/^\//, "").split("/") ?? []) {
|
|
232
|
+
if (!encoded || !node) continue;
|
|
233
|
+
const key = encoded.replace(/~1/g, "/").replace(/~0/g, "~");
|
|
234
|
+
const properties = node.properties;
|
|
235
|
+
if (properties && typeof properties === "object" && !Array.isArray(properties) && key in properties) {
|
|
236
|
+
steps.push({ kind: "property", key });
|
|
237
|
+
node = resolveLocalRefs(root, (properties as Record<string, unknown>)[key]);
|
|
238
|
+
continue;
|
|
239
|
+
}
|
|
240
|
+
if (/^(0|[1-9]\d*)$/.test(key)) {
|
|
241
|
+
const index = Number(key);
|
|
242
|
+
const prefixItems = node.prefixItems;
|
|
243
|
+
const itemSchema = Array.isArray(prefixItems) && index < prefixItems.length ? prefixItems[index] : node.items;
|
|
244
|
+
if (itemSchema !== undefined) {
|
|
245
|
+
steps.push({ kind: "index", index });
|
|
246
|
+
node = resolveLocalRefs(root, itemSchema);
|
|
247
|
+
continue;
|
|
248
|
+
}
|
|
249
|
+
}
|
|
250
|
+
return undefined;
|
|
251
|
+
}
|
|
252
|
+
return node ? { node, steps } : undefined;
|
|
253
|
+
}
|
|
254
|
+
|
|
255
|
+
function conditionalTarget(root: unknown, schemaPath: string, instancePath: string | undefined): { node: Record<string, unknown>; steps: InstanceSchemaStep[] } | undefined {
|
|
256
|
+
const traversed = traverseInstanceSchema(root, instancePath);
|
|
257
|
+
if (!traversed) return undefined;
|
|
258
|
+
let pointer = schemaPath;
|
|
259
|
+
const seen = new Set<string>();
|
|
260
|
+
while (!seen.has(pointer)) {
|
|
261
|
+
seen.add(pointer);
|
|
262
|
+
const record = resolveLocalRefs(root, jsonPointerTarget(root, pointer));
|
|
263
|
+
if (!record) break;
|
|
264
|
+
if (record.if !== undefined) return { node: record, steps: traversed.steps };
|
|
265
|
+
if (typeof record.$ref !== "string" || !record.$ref.startsWith("#")) break;
|
|
266
|
+
pointer = record.$ref;
|
|
267
|
+
}
|
|
268
|
+
if (traversed.node.if !== undefined) return traversed;
|
|
269
|
+
return undefined;
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
function errorKey(error: JsonSchemaValidationError): string {
|
|
273
|
+
return JSON.stringify([error.keyword, error.instancePath, error.params, error.message]);
|
|
274
|
+
}
|
|
275
|
+
|
|
276
|
+
function branchDiagnosticSchema(schema: JsonSchemaObject, steps: InstanceSchemaStep[], branch: unknown): JsonSchemaObject {
|
|
277
|
+
const diagnostic: Record<string, unknown> = {};
|
|
278
|
+
for (const keyword of ["$schema", "$id", "$defs", "definitions"] as const) {
|
|
279
|
+
if (schema[keyword] !== undefined) diagnostic[keyword] = schema[keyword];
|
|
280
|
+
}
|
|
281
|
+
let target = diagnostic;
|
|
282
|
+
for (const step of steps) {
|
|
283
|
+
if (step.kind === "index") {
|
|
284
|
+
const index = step.index;
|
|
285
|
+
const prefixItems = Array.from({ length: index + 1 }, () => true as unknown);
|
|
286
|
+
const nested: Record<string, unknown> = {};
|
|
287
|
+
prefixItems[index] = nested;
|
|
288
|
+
target.prefixItems = prefixItems;
|
|
289
|
+
target.items = true;
|
|
290
|
+
target = nested;
|
|
291
|
+
} else {
|
|
292
|
+
const nested: Record<string, unknown> = {};
|
|
293
|
+
target.properties = { [step.key]: nested };
|
|
294
|
+
target = nested;
|
|
295
|
+
}
|
|
296
|
+
}
|
|
297
|
+
target.allOf = [branch];
|
|
298
|
+
return diagnostic as JsonSchemaObject;
|
|
299
|
+
}
|
|
300
|
+
|
|
301
|
+
function expandConditionalError(compile: CompileJsonSchema, schema: JsonSchemaObject, value: unknown, error: JsonSchemaValidationError): { schema: JsonSchemaObject; errors: JsonSchemaValidationError[] } | undefined {
|
|
302
|
+
const branch = error.params?.failingKeyword;
|
|
303
|
+
if (error.keyword !== "if" || (branch !== "then" && branch !== "else") || !error.schemaPath) return undefined;
|
|
304
|
+
try {
|
|
305
|
+
const target = conditionalTarget(schema, error.schemaPath, error.instancePath);
|
|
306
|
+
if (!target || target.node[branch] === undefined) return undefined;
|
|
307
|
+
const expandedSchema = branchDiagnosticSchema(schema, target.steps, target.node[branch]);
|
|
308
|
+
const expandedErrors = [...compile(expandedSchema).Errors(value)];
|
|
309
|
+
if (expandedErrors.length === 0) return undefined;
|
|
310
|
+
return { schema: expandedSchema, errors: expandedErrors };
|
|
311
|
+
} catch {
|
|
312
|
+
return undefined;
|
|
313
|
+
}
|
|
314
|
+
}
|
|
315
|
+
|
|
316
|
+
function formatValidationError(error: JsonSchemaValidationError): string[] {
|
|
317
|
+
const pathText = error.instancePath ? error.instancePath.replace(/^\//, "").replace(/\//g, ".") : "root";
|
|
318
|
+
if (error.keyword === "required" && error.params?.requiredProperties?.length) {
|
|
319
|
+
return error.params.requiredProperties.map((property) => `${pathText === "root" ? property : `${pathText}.${property}`}: is required`);
|
|
320
|
+
}
|
|
321
|
+
return [`${pathText}: ${error.message}`];
|
|
322
|
+
}
|
|
323
|
+
|
|
324
|
+
function expandedErrorMessages(compile: CompileJsonSchema, schema: JsonSchemaObject, value: unknown, error: JsonSchemaValidationError, limit: number, seen: Set<string>): string[] {
|
|
325
|
+
if (limit <= 0) return [];
|
|
326
|
+
const state = `${errorKey(error)}\0${JSON.stringify(schema)}`;
|
|
327
|
+
if (seen.has(state)) return formatValidationError(error).slice(0, limit);
|
|
328
|
+
seen.add(state);
|
|
329
|
+
const expanded = expandConditionalError(compile, schema, value, error);
|
|
330
|
+
if (!expanded) return formatValidationError(error).slice(0, limit);
|
|
331
|
+
const messages: string[] = [];
|
|
332
|
+
for (const candidate of expanded.errors) {
|
|
333
|
+
messages.push(...expandedErrorMessages(compile, expanded.schema, value, candidate, limit - messages.length, seen));
|
|
334
|
+
if (messages.length >= limit) break;
|
|
335
|
+
}
|
|
336
|
+
return messages;
|
|
337
|
+
}
|
|
338
|
+
|
|
126
339
|
export function assertJsonSchemaObject(schema: unknown, label = "outputSchema"): asserts schema is JsonSchemaObject {
|
|
127
340
|
if (!schema || typeof schema !== "object" || Array.isArray(schema)) {
|
|
128
341
|
throw new Error(`${label} must be a JSON Schema object.`);
|
|
@@ -156,12 +369,19 @@ export async function validateStructuredOutputValue(schema: JsonSchemaObject, va
|
|
|
156
369
|
return { status: "invalid", message: `invalid outputSchema: ${error instanceof Error ? error.message : String(error)}` };
|
|
157
370
|
}
|
|
158
371
|
if (validator.Check(value)) return { status: "valid" };
|
|
159
|
-
const
|
|
160
|
-
|
|
161
|
-
|
|
162
|
-
|
|
163
|
-
|
|
164
|
-
|
|
372
|
+
const originalErrors = [...validator.Errors(value)];
|
|
373
|
+
const errors: string[] = [];
|
|
374
|
+
const uniqueErrors = new Set<string>();
|
|
375
|
+
const seen = new Set<string>();
|
|
376
|
+
for (const error of originalErrors) {
|
|
377
|
+
for (const message of expandedErrorMessages(compile, schema, value, error, 8 - errors.length, seen)) {
|
|
378
|
+
if (!uniqueErrors.has(message)) {
|
|
379
|
+
uniqueErrors.add(message);
|
|
380
|
+
errors.push(message);
|
|
381
|
+
}
|
|
382
|
+
}
|
|
383
|
+
if (errors.length >= 8) break;
|
|
384
|
+
}
|
|
165
385
|
return { status: "invalid", message: errors.join("; ") || "schema validation failed" };
|
|
166
386
|
}
|
|
167
387
|
|