@xzzpig/pi-subagents 0.7.0 → 0.9.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 +456 -4
- package/README.md +3 -3
- package/agents/claude-code-writer.md +15 -0
- package/agents/claude-code.md +15 -0
- package/agents/codex-exec-writer.md +15 -0
- package/agents/codex-exec.md +15 -0
- package/agents/cursor-agent-writer.md +14 -0
- package/agents/cursor-agent.md +14 -0
- package/agents/reviewer.md +13 -3
- package/agents/scout.md +1 -1
- package/docs/agents.md +154 -42
- package/docs/configuration.md +85 -26
- package/docs/extension-api.md +81 -16
- package/docs/missions.md +2 -0
- package/docs/models.md +75 -11
- package/docs/observability.md +34 -21
- package/docs/tool-reference.md +142 -18
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +148 -4
- package/index.ts +10 -1
- package/install.mjs +1 -1
- package/package.json +7 -6
- package/prompts/council.md +19 -7
- package/prompts/parallel-review.md +5 -1
- package/prompts/review-loop.md +11 -7
- package/skills/council-mode/SKILL.md +44 -215
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +90 -32
- package/skills/pi-subagents/references/constraints-and-recipes.md +34 -223
- package/skills/pi-subagents/references/execution-controls.md +104 -19
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +16 -4
- package/skills/pi-subagents/references/prompting-and-roles.md +71 -36
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +471 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +16 -4
- package/src/agents/agents.ts +1076 -351
- package/src/agents/builtin-names.ts +6 -0
- package/src/agents/runtime-agent-events.ts +70 -0
- package/src/agents/runtime-agent-registry.ts +31 -20
- package/src/api/agents.ts +10 -5
- package/src/api/background-work.ts +12 -3
- package/src/api/capability-ceiling.ts +0 -1
- package/src/api/{pi-args.ts → child-tool-plan.ts} +1 -1
- package/src/api/delegation.ts +0 -7
- package/src/api/external-job-provider.ts +10 -1
- package/src/api/external-runs.ts +67 -4
- package/src/api/preflight.ts +97 -34
- package/src/api/project-panes.ts +2 -0
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +15 -13
- package/src/extension/fanout-child.ts +17 -16
- package/src/extension/index.ts +139 -41
- package/src/extension/public-execution.ts +113 -22
- package/src/extension/rpc.ts +182 -13
- package/src/extension/schemas.ts +63 -21
- package/src/extension/tool-description.ts +48 -23
- package/src/extension/tool-result.ts +19 -0
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/client.ts +3 -3
- package/src/inspectors/herdr/focus.ts +55 -0
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/project-panes.ts +228 -44
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +75 -5
- package/src/intercom/native-supervisor-channel.ts +138 -60
- package/src/intercom/result-intercom.ts +2 -0
- package/src/intercom/supervisor-ui.ts +243 -0
- package/src/profiles/profiles.ts +5 -6
- package/src/runs/background/active-async-capacity.ts +103 -18
- package/src/runs/background/async-execution.ts +492 -125
- package/src/runs/background/async-job-tracker.ts +127 -28
- package/src/runs/background/async-resume.ts +67 -29
- package/src/runs/background/async-retention.ts +21 -4
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +199 -14
- package/src/runs/background/auto-drain.ts +1 -1
- package/src/runs/background/chain-append.ts +8 -3
- package/src/runs/background/chain-root-attachment.ts +79 -8
- package/src/runs/background/control-channel.ts +101 -214
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +295 -8
- package/src/runs/background/process-terminal.ts +16 -0
- package/src/runs/background/result-delivery-ownership.ts +45 -0
- package/src/runs/background/result-files.ts +28 -14
- package/src/runs/background/result-watcher.ts +43 -19
- package/src/runs/background/resume-guidance.ts +2 -2
- package/src/runs/background/retained-children.ts +1 -1
- package/src/runs/background/run-child-session.ts +613 -0
- package/src/runs/background/run-status.ts +99 -18
- package/src/runs/background/runner-aliases.ts +125 -0
- package/src/runs/background/runner-child-sessions.ts +31 -0
- package/src/runs/background/scheduled-runs.ts +174 -18
- package/src/runs/background/stale-run-reconciler.ts +13 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +959 -1159
- package/src/runs/background/subagent-wait.ts +86 -31
- package/src/runs/background/terminal-run-index.ts +1 -1
- package/src/runs/background/wait-completions.ts +45 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +27 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/async-stop-action.ts +23 -2
- package/src/runs/foreground/execution.ts +585 -481
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +26 -3
- package/src/runs/foreground/subagent-executor.ts +1549 -410
- package/src/runs/foreground/workflow-detach-reconcile.ts +141 -104
- package/src/runs/foreground/workflow-foreground-steering.ts +24 -98
- package/src/runs/shared/abort-recovery.ts +119 -0
- package/src/runs/shared/acceptance.ts +147 -39
- package/src/runs/shared/agent-contract.ts +1 -1
- package/src/runs/shared/async-status-projection.ts +565 -0
- package/src/runs/shared/background-process-options.ts +9 -0
- package/src/runs/shared/capability-ceiling.ts +2 -2
- package/src/runs/shared/child-hooks.ts +25 -0
- package/src/runs/shared/child-identity.ts +62 -0
- package/src/runs/shared/child-launch-plan.ts +151 -0
- package/src/runs/shared/child-launch.ts +314 -0
- package/src/runs/shared/child-lifecycle.ts +25 -0
- package/src/runs/shared/child-runtime-config.ts +126 -0
- package/src/runs/shared/child-session.ts +342 -0
- package/src/runs/shared/child-tool-plan.ts +540 -0
- package/src/runs/shared/claude-code-adapter.ts +133 -0
- package/src/runs/shared/codex-exec-adapter.ts +129 -0
- package/src/runs/shared/completion-evidence.ts +89 -0
- package/src/runs/shared/completion-guard.ts +57 -6
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +4 -4
- package/src/runs/shared/extension-bindings.ts +78 -0
- package/src/runs/shared/external-cli-contract.ts +167 -0
- package/src/runs/shared/external-cli-preflight.ts +138 -0
- package/src/runs/shared/external-cli-runner.ts +349 -54
- package/src/runs/shared/external-job-bridge.ts +53 -37
- package/src/runs/shared/external-job-runner.ts +126 -23
- package/src/runs/shared/fast-mode-extension.ts +10 -0
- package/src/runs/shared/host-step-status.ts +231 -0
- package/src/runs/shared/lane-metadata.ts +126 -0
- package/src/runs/shared/launch-cwd.ts +16 -0
- package/src/runs/shared/long-running-guard.ts +2 -1
- package/src/runs/shared/mcp-config-sources.ts +422 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +222 -158
- package/src/runs/shared/mcp-direct-tool-grant.ts +194 -0
- package/src/runs/shared/model-exclusions.ts +141 -10
- package/src/runs/shared/model-fallback.ts +187 -33
- package/src/runs/shared/model-scope.ts +106 -39
- package/src/runs/shared/mutation-evidence.ts +199 -0
- package/src/runs/shared/nested-events.ts +38 -48
- package/src/runs/shared/nested-path.ts +0 -14
- package/src/runs/shared/nested-render.ts +9 -5
- package/src/runs/shared/orca-progress-tabs.ts +83 -16
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +28 -5
- package/src/runs/shared/permissions.ts +1 -14
- package/src/runs/shared/pi-spawn.ts +69 -35
- package/src/runs/shared/process-signal.ts +16 -0
- package/src/runs/shared/run-fanout-budget.ts +0 -13
- package/src/runs/shared/run-history.ts +21 -1
- package/src/runs/shared/runtime-acknowledged-extensions.ts +0 -27
- package/src/runs/shared/single-output.ts +89 -22
- package/src/runs/shared/structured-output.ts +61 -7
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +216 -360
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -64
- package/src/runs/shared/tool-budget.ts +0 -14
- package/src/runs/shared/tool-timeout.ts +1 -1
- package/src/runs/shared/workflow-graph.ts +16 -0
- package/src/runs/shared/worktree-cleanup-plan.ts +866 -0
- package/src/runs/shared/worktree.ts +571 -62
- package/src/shared/atomic-json.ts +3 -1
- package/src/shared/child-session-name.ts +46 -0
- package/src/shared/extension-context.ts +24 -0
- package/src/shared/fork-context.ts +21 -12
- package/src/shared/fork-session-cwd.ts +27 -0
- package/src/shared/formatters.ts +18 -3
- package/src/shared/jsonl-writer.ts +11 -0
- package/src/shared/launch-contract.ts +20 -6
- package/src/shared/pruned-fork.ts +450 -0
- package/src/shared/session-file-trust.ts +19 -0
- package/src/shared/session-tokens.ts +14 -3
- package/src/shared/settings.ts +21 -102
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +46 -0
- package/src/shared/types.ts +644 -75
- package/src/shared/utils.ts +60 -93
- package/src/shared/workflow-child-permit.ts +207 -0
- package/src/slash/delegation-adapters.ts +1 -9
- package/src/slash/delegation-request.ts +0 -4
- package/src/slash/prompt-template-bridge.ts +37 -1
- package/src/slash/slash-bridge.ts +1 -2
- package/src/slash/slash-commands.ts +383 -116
- package/src/slash/slash-live-state.ts +22 -11
- package/src/slash/subagents-admin.ts +29 -12
- package/src/tui/fleet-native-transcript.ts +4 -0
- package/src/tui/fleet-status.ts +278 -90
- package/src/tui/fleet-transcript.ts +11 -5
- package/src/tui/fleet.ts +54 -28
- package/src/tui/render-helpers.ts +31 -0
- package/src/tui/render.ts +1433 -166
- package/src/watchdog/change-signature.ts +40 -1
- package/src/watchdog/child-status.ts +54 -34
- package/src/watchdog/diff-tool.ts +77 -0
- package/src/watchdog/emission-guard.ts +5 -3
- package/src/watchdog/guidance.ts +20 -0
- package/src/watchdog/permission-arbiter.ts +59 -52
- package/src/watchdog/register-child.ts +28 -25
- package/src/watchdog/register-main.ts +10 -9
- package/src/watchdog/render.ts +4 -5
- package/src/watchdog/review.ts +15 -4
- package/src/watchdog/rules.ts +70 -0
- package/src/watchdog/runtime.ts +75 -92
- package/src/watchdog/scope.ts +0 -11
- package/src/watchdog/settings.ts +48 -104
- package/src/watchdog/turn-delta.ts +1 -1
- package/src/watchdog/types.ts +18 -32
- package/src/watchdog/warning-format.ts +0 -1
- package/src/workflows/chat-progress.ts +7 -3
- package/src/workflows/host-command.ts +235 -0
- package/src/workflows/scripted-workflow.ts +1142 -69
- package/src/workflows/workflow-checklist.ts +439 -0
- package/src/workflows/workflow-child-summary.ts +121 -0
- package/src/workflows/workflow-preflight.ts +297 -0
- package/src/workflows/workflow-receipt.ts +232 -6
- package/src/workflows/workflow-resources.ts +150 -0
- package/src/workflows/workflow-settlement.ts +246 -0
- package/src/runs/shared/child-protocol.ts +0 -401
- package/src/runs/shared/pi-args.ts +0 -858
- package/src/runs/shared/subagent-startup-retry.ts +0 -116
- package/src/runs/shared/turn-budget.ts +0 -98
- package/src/shared/post-exit-stdio-guard.ts +0 -85
|
@@ -0,0 +1,540 @@
|
|
|
1
|
+
/**
|
|
2
|
+
* Child tool plan: which builtin tools, MCP tools, runtime hooks, and extension
|
|
3
|
+
* files a child launch gets, and how that resolution is reported. Both the
|
|
4
|
+
* foreground path and the async runner build their session launch from this.
|
|
5
|
+
*/
|
|
6
|
+
import { createHash } from "node:crypto";
|
|
7
|
+
import * as fs from "node:fs";
|
|
8
|
+
import * as path from "node:path";
|
|
9
|
+
import { fileURLToPath } from "node:url";
|
|
10
|
+
import {
|
|
11
|
+
formatUnresolvedMcpDirectToolSelectors,
|
|
12
|
+
resolveMcpDirectToolResolution,
|
|
13
|
+
type McpRuntimeSnapshotHost,
|
|
14
|
+
type ResolvedMcpDirectToolSelection,
|
|
15
|
+
} from "./mcp-direct-tool-allowlist.ts";
|
|
16
|
+
import {
|
|
17
|
+
TEMP_ROOT_DIR,
|
|
18
|
+
type JsonSchemaObject,
|
|
19
|
+
type LaunchResolvedChildExtensionsV1,
|
|
20
|
+
} from "../../shared/types.ts";
|
|
21
|
+
import { THINKING_LEVELS } from "../../shared/model-info.ts";
|
|
22
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
23
|
+
import type { PermissionRules } from "./permissions.ts";
|
|
24
|
+
import {
|
|
25
|
+
capabilityCeilingAgentRestrictionSources,
|
|
26
|
+
intersectSubagentCapabilityCeilings,
|
|
27
|
+
isAgentAllowedByCapabilityCeiling,
|
|
28
|
+
type ResolvedSubagentCapabilityCeiling,
|
|
29
|
+
type SubagentCapabilityAudit,
|
|
30
|
+
} from "./capability-ceiling.ts";
|
|
31
|
+
|
|
32
|
+
const MAX_LAUNCH_RESOLVED_EXTENSION_IDS = 32;
|
|
33
|
+
const PROMPT_RUNTIME_EXTENSION_PATH = path.join(
|
|
34
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
35
|
+
"subagent-prompt-runtime.ts",
|
|
36
|
+
);
|
|
37
|
+
const FANOUT_CHILD_EXTENSION_PATH = path.join(
|
|
38
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
39
|
+
"..",
|
|
40
|
+
"..",
|
|
41
|
+
"extension",
|
|
42
|
+
"fanout-child.ts",
|
|
43
|
+
);
|
|
44
|
+
const FAST_MODE_EXTENSION_PATH = path.join(
|
|
45
|
+
path.dirname(fileURLToPath(import.meta.url)),
|
|
46
|
+
"fast-mode-extension.ts",
|
|
47
|
+
);
|
|
48
|
+
const SUBAGENT_RUNTIME_EXTENSION_PATHS = new Set([
|
|
49
|
+
PROMPT_RUNTIME_EXTENSION_PATH,
|
|
50
|
+
FANOUT_CHILD_EXTENSION_PATH,
|
|
51
|
+
FAST_MODE_EXTENSION_PATH,
|
|
52
|
+
].map((extensionPath) => path.normalize(extensionPath)));
|
|
53
|
+
|
|
54
|
+
/** True for the extension files pi-subagents itself installs in child sessions. */
|
|
55
|
+
export function isSubagentRuntimeExtensionPath(extensionPath: string): boolean {
|
|
56
|
+
return SUBAGENT_RUNTIME_EXTENSION_PATHS.has(path.normalize(extensionPath));
|
|
57
|
+
}
|
|
58
|
+
const FAST_MODE_ALLOWED_MODELS = new Set([
|
|
59
|
+
"openai-codex/gpt-5.6-luna",
|
|
60
|
+
"openai-codex/gpt-5.6-sol",
|
|
61
|
+
]);
|
|
62
|
+
const OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH = 64;
|
|
63
|
+
|
|
64
|
+
export function deriveForkPromptCacheKey(parentSessionId: string | undefined): string | undefined {
|
|
65
|
+
const parent = parentSessionId?.trim();
|
|
66
|
+
if (!parent) return undefined;
|
|
67
|
+
const digest = createHash("sha256").update(parent).digest("hex").slice(0, OPENAI_PROMPT_CACHE_KEY_MAX_LENGTH - "pi-fork:".length);
|
|
68
|
+
return `pi-fork:${digest}`;
|
|
69
|
+
}
|
|
70
|
+
|
|
71
|
+
function sanitizeSupervisorChannelSegment(value: string): string {
|
|
72
|
+
return (
|
|
73
|
+
value
|
|
74
|
+
.trim()
|
|
75
|
+
.replace(/[^A-Za-z0-9._-]+/g, "-")
|
|
76
|
+
.replace(/^-+|-+$/g, "") || "unknown"
|
|
77
|
+
);
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function supervisorChannelDir(
|
|
81
|
+
runId: string,
|
|
82
|
+
agent: string,
|
|
83
|
+
childIndex: number,
|
|
84
|
+
): string {
|
|
85
|
+
return path.join(
|
|
86
|
+
TEMP_ROOT_DIR,
|
|
87
|
+
"supervisor-channels",
|
|
88
|
+
`${sanitizeSupervisorChannelSegment(runId)}-${sanitizeSupervisorChannelSegment(agent)}-${childIndex}`,
|
|
89
|
+
);
|
|
90
|
+
}
|
|
91
|
+
|
|
92
|
+
export function applyThinkingSuffix(
|
|
93
|
+
model: string | undefined,
|
|
94
|
+
thinking: string | false | undefined,
|
|
95
|
+
replaceExisting = false,
|
|
96
|
+
): string | undefined {
|
|
97
|
+
if (!model || !thinking) return model;
|
|
98
|
+
const colonIdx = model.lastIndexOf(":");
|
|
99
|
+
if (
|
|
100
|
+
colonIdx !== -1 &&
|
|
101
|
+
THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
|
|
102
|
+
) {
|
|
103
|
+
return replaceExisting ? `${model.slice(0, colonIdx)}:${thinking}` : model;
|
|
104
|
+
}
|
|
105
|
+
return `${model}:${thinking}`;
|
|
106
|
+
}
|
|
107
|
+
|
|
108
|
+
function stripThinkingSuffix(model: string): string {
|
|
109
|
+
const colonIdx = model.lastIndexOf(":");
|
|
110
|
+
if (colonIdx === -1) return model;
|
|
111
|
+
return THINKING_LEVELS.some((level) => level === model.substring(colonIdx + 1))
|
|
112
|
+
? model.slice(0, colonIdx)
|
|
113
|
+
: model;
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
function resolveFastModeExtension(input: Pick<ResolvePiLaunchToolPlanInput, "fast" | "model" | "modelCandidates" | "agentName">): string[] {
|
|
117
|
+
if (!input.fast) return [];
|
|
118
|
+
const candidates = (input.modelCandidates?.length ? input.modelCandidates : input.model ? [input.model] : [])
|
|
119
|
+
.map(stripThinkingSuffix);
|
|
120
|
+
if (candidates.length === 0) {
|
|
121
|
+
throw new Error(`fast mode requires an explicit supported native OpenAI-Codex model${input.agentName ? ` for agent '${input.agentName}'` : ""}.`);
|
|
122
|
+
}
|
|
123
|
+
const unsupported = candidates.filter((model) => !FAST_MODE_ALLOWED_MODELS.has(model));
|
|
124
|
+
if (unsupported.length > 0) {
|
|
125
|
+
throw new Error(`fast mode supports only ${[...FAST_MODE_ALLOWED_MODELS].join(", ")}; unsupported model${unsupported.length === 1 ? "" : "s"}: ${unsupported.join(", ")}.`);
|
|
126
|
+
}
|
|
127
|
+
return [FAST_MODE_EXTENSION_PATH];
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
export interface ResolvePiLaunchToolPlanInput {
|
|
131
|
+
tools?: string[];
|
|
132
|
+
excludeTools?: string[];
|
|
133
|
+
allowNestedSubagents?: boolean;
|
|
134
|
+
extensions?: string[];
|
|
135
|
+
subagentOnlyExtensions?: string[];
|
|
136
|
+
mcpDirectTools?: string[];
|
|
137
|
+
cwd?: string;
|
|
138
|
+
requireReadTool?: boolean;
|
|
139
|
+
structuredOutput?:
|
|
140
|
+
| boolean
|
|
141
|
+
| {
|
|
142
|
+
schema: JsonSchemaObject;
|
|
143
|
+
schemaPath: string;
|
|
144
|
+
outputPath: string;
|
|
145
|
+
};
|
|
146
|
+
fast?: boolean;
|
|
147
|
+
model?: string;
|
|
148
|
+
modelCandidates?: readonly string[];
|
|
149
|
+
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
150
|
+
inheritedCapabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
151
|
+
agentName?: string;
|
|
152
|
+
permissionRules?: PermissionRules;
|
|
153
|
+
runtimeSnapshotHost?: McpRuntimeSnapshotHost;
|
|
154
|
+
}
|
|
155
|
+
|
|
156
|
+
export interface PiLaunchToolPlan {
|
|
157
|
+
capabilityCeiling?: ResolvedSubagentCapabilityCeiling;
|
|
158
|
+
requestedBuiltinTools: string[];
|
|
159
|
+
declaredBuiltinTools: string[];
|
|
160
|
+
excludeTools: string[];
|
|
161
|
+
toolExtensionPaths: string[];
|
|
162
|
+
resolvedMcpSelections: ResolvedMcpDirectToolSelection[];
|
|
163
|
+
effectiveMcpSelections: ResolvedMcpDirectToolSelection[];
|
|
164
|
+
effectiveMcpTools: string[];
|
|
165
|
+
explicitToolAllowlist: boolean;
|
|
166
|
+
internalTools: string[];
|
|
167
|
+
effectiveToolAllowlist: string[];
|
|
168
|
+
requiredChildTools: string[];
|
|
169
|
+
fanoutAuthorized: boolean;
|
|
170
|
+
runtimeExtensions: string[];
|
|
171
|
+
configuredExtensions: string[];
|
|
172
|
+
extensionArgs: string[];
|
|
173
|
+
disableAmbientExtensions: boolean;
|
|
174
|
+
capabilityAudit?: SubagentCapabilityAudit;
|
|
175
|
+
/** Non-fatal launch warnings; they do not change behavior. */
|
|
176
|
+
warnings: string[];
|
|
177
|
+
}
|
|
178
|
+
|
|
179
|
+
function extensionIdentifier(value: string): string {
|
|
180
|
+
return `sha256:${createHash("sha256").update(path.normalize(value.trim())).digest("hex").slice(0, 16)}`;
|
|
181
|
+
}
|
|
182
|
+
|
|
183
|
+
function boundedExtensionIdentifiers(values: string[]): {
|
|
184
|
+
ids: string[];
|
|
185
|
+
omitted: number;
|
|
186
|
+
} {
|
|
187
|
+
const ids = [...new Set(values.map(extensionIdentifier))];
|
|
188
|
+
return {
|
|
189
|
+
ids: ids.slice(0, MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
|
|
190
|
+
omitted: Math.max(0, ids.length - MAX_LAUNCH_RESOLVED_EXTENSION_IDS),
|
|
191
|
+
};
|
|
192
|
+
}
|
|
193
|
+
|
|
194
|
+
function hasPermissionRules(rules: PermissionRules | undefined): boolean {
|
|
195
|
+
return rules !== undefined && Object.keys(rules).length > 0;
|
|
196
|
+
}
|
|
197
|
+
|
|
198
|
+
/**
|
|
199
|
+
* Children are pi sessions inside the parent or the runner process; a spawned
|
|
200
|
+
* `pi` received extra MCP server definitions as a CLI argument, but a session
|
|
201
|
+
* has no such input. Selecting a server that exists only in pi-mcp-adapter's
|
|
202
|
+
* runtime snapshot therefore cannot work and fails the launch.
|
|
203
|
+
*/
|
|
204
|
+
export function formatRuntimeSnapshotMcpServersError(agentName: string | undefined, serverNames: readonly string[]): string {
|
|
205
|
+
const subject = agentName ? `Agent '${agentName}'` : "Subagent";
|
|
206
|
+
return `${subject} selects MCP tools from servers that exist only in pi-mcp-adapter's runtime snapshot (${serverNames.join(", ")}). MCP servers from the runtime snapshot cannot be provided to in-process children; MCP tools must come from an ambient adapter extension in a background child (\`async: true\`), so add the server to the adapter's configuration file instead.`;
|
|
207
|
+
}
|
|
208
|
+
|
|
209
|
+
export function projectLaunchResolvedChildExtensions(
|
|
210
|
+
toolPlan: Pick<
|
|
211
|
+
PiLaunchToolPlan,
|
|
212
|
+
| "runtimeExtensions"
|
|
213
|
+
| "configuredExtensions"
|
|
214
|
+
| "extensionArgs"
|
|
215
|
+
| "disableAmbientExtensions"
|
|
216
|
+
>,
|
|
217
|
+
): LaunchResolvedChildExtensionsV1 {
|
|
218
|
+
const runtime = boundedExtensionIdentifiers(toolPlan.runtimeExtensions);
|
|
219
|
+
const configured = boundedExtensionIdentifiers(toolPlan.configuredExtensions);
|
|
220
|
+
const effective = boundedExtensionIdentifiers(toolPlan.extensionArgs);
|
|
221
|
+
return {
|
|
222
|
+
version: 1,
|
|
223
|
+
source: "launch-resolved",
|
|
224
|
+
disableAmbientExtensions: toolPlan.disableAmbientExtensions,
|
|
225
|
+
runtime: runtime.ids,
|
|
226
|
+
configured: configured.ids,
|
|
227
|
+
effective: effective.ids,
|
|
228
|
+
omitted: {
|
|
229
|
+
runtime: runtime.omitted,
|
|
230
|
+
configured: configured.omitted,
|
|
231
|
+
effective: effective.omitted,
|
|
232
|
+
},
|
|
233
|
+
};
|
|
234
|
+
}
|
|
235
|
+
|
|
236
|
+
/**
|
|
237
|
+
* Resolve the permission-system extension entry point when installed.
|
|
238
|
+
* Returns the absolute path to the extension's main module, or undefined
|
|
239
|
+
* when the package is not installed. Callers can check `autoInject` config
|
|
240
|
+
* to decide whether to include it in child sessions.
|
|
241
|
+
*/
|
|
242
|
+
export function resolvePermissionSystemExtension(): string | undefined {
|
|
243
|
+
const agentDir = getAgentDir();
|
|
244
|
+
const candidates = [
|
|
245
|
+
// Fork: the @xzzpig fork takes priority so child processes inherit the
|
|
246
|
+
// same permission system the parent session loads from settings.json.
|
|
247
|
+
// When only the upstream package is installed, behavior is unchanged.
|
|
248
|
+
path.join(
|
|
249
|
+
agentDir,
|
|
250
|
+
"npm",
|
|
251
|
+
"node_modules",
|
|
252
|
+
"@xzzpig",
|
|
253
|
+
"pi-permission-system",
|
|
254
|
+
),
|
|
255
|
+
// npm-scoped package (most common)
|
|
256
|
+
path.join(
|
|
257
|
+
agentDir,
|
|
258
|
+
"npm",
|
|
259
|
+
"node_modules",
|
|
260
|
+
"@gotgenes",
|
|
261
|
+
"pi-permission-system",
|
|
262
|
+
),
|
|
263
|
+
// direct extension directory (some layouts)
|
|
264
|
+
path.join(agentDir, "extensions", "pi-permission-system"),
|
|
265
|
+
];
|
|
266
|
+
const errors: Error[] = [];
|
|
267
|
+
for (const extDir of candidates) {
|
|
268
|
+
if (!fs.existsSync(extDir)) continue;
|
|
269
|
+
const pkgPath = path.join(extDir, "package.json");
|
|
270
|
+
if (!fs.existsSync(pkgPath)) {
|
|
271
|
+
errors.push(new Error(`Permission-system package manifest is missing at ${pkgPath}.`));
|
|
272
|
+
continue;
|
|
273
|
+
}
|
|
274
|
+
try {
|
|
275
|
+
let pkg: { pi?: { extensions?: string[] } };
|
|
276
|
+
const parsed: unknown = JSON.parse(fs.readFileSync(pkgPath, "utf-8"));
|
|
277
|
+
if (!parsed || typeof parsed !== "object" || Array.isArray(parsed)) {
|
|
278
|
+
throw new Error("manifest root must be an object");
|
|
279
|
+
}
|
|
280
|
+
pkg = parsed as typeof pkg;
|
|
281
|
+
const extensions = pkg.pi?.extensions;
|
|
282
|
+
const entry = Array.isArray(extensions) ? extensions[0] : undefined;
|
|
283
|
+
if (typeof entry !== "string" || !entry.trim()) {
|
|
284
|
+
throw new Error(
|
|
285
|
+
`Permission-system package manifest at ${pkgPath} must declare pi.extensions[0] as a non-empty string.`,
|
|
286
|
+
);
|
|
287
|
+
}
|
|
288
|
+
const resolved = path.resolve(extDir, entry);
|
|
289
|
+
if (fs.existsSync(resolved)) return resolved;
|
|
290
|
+
throw new Error(
|
|
291
|
+
`Permission-system extension entry ${JSON.stringify(entry)} in ${pkgPath} does not exist at ${resolved}.`,
|
|
292
|
+
);
|
|
293
|
+
} catch (error) {
|
|
294
|
+
const message = error instanceof Error ? error.message : String(error);
|
|
295
|
+
errors.push(message.startsWith("Permission-system") ? new Error(message) : new Error(`Cannot read permission-system package manifest at ${pkgPath}: ${message}`));
|
|
296
|
+
}
|
|
297
|
+
}
|
|
298
|
+
if (errors.length > 0) throw errors[0]!;
|
|
299
|
+
return undefined;
|
|
300
|
+
}
|
|
301
|
+
|
|
302
|
+
export function resolvePiLaunchToolPlan(
|
|
303
|
+
input: ResolvePiLaunchToolPlanInput,
|
|
304
|
+
): PiLaunchToolPlan {
|
|
305
|
+
const capabilityCeiling = intersectSubagentCapabilityCeilings(
|
|
306
|
+
input.capabilityCeiling,
|
|
307
|
+
input.inheritedCapabilityCeiling,
|
|
308
|
+
);
|
|
309
|
+
const allowedToolSet =
|
|
310
|
+
capabilityCeiling?.allowedTools === undefined
|
|
311
|
+
? undefined
|
|
312
|
+
: new Set(capabilityCeiling.allowedTools);
|
|
313
|
+
const requestedBuiltinTools =
|
|
314
|
+
input.tools?.filter(
|
|
315
|
+
(tool) =>
|
|
316
|
+
!(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
|
|
317
|
+
) ?? [];
|
|
318
|
+
if (input.requireReadTool && allowedToolSet && !allowedToolSet.has("read")) {
|
|
319
|
+
throw new Error(
|
|
320
|
+
`Capability ceiling from ${capabilityCeiling?.sources.join(", ") || "unknown source"} excludes required tool 'read' for lazy skill loading.`,
|
|
321
|
+
);
|
|
322
|
+
}
|
|
323
|
+
const declaredBuiltinTools =
|
|
324
|
+
input.tools === undefined
|
|
325
|
+
? allowedToolSet
|
|
326
|
+
? [...allowedToolSet]
|
|
327
|
+
: []
|
|
328
|
+
: (input.requireReadTool &&
|
|
329
|
+
requestedBuiltinTools.length > 0 &&
|
|
330
|
+
!requestedBuiltinTools.includes("read") &&
|
|
331
|
+
!allowedToolSet
|
|
332
|
+
? ["read", ...requestedBuiltinTools]
|
|
333
|
+
: requestedBuiltinTools
|
|
334
|
+
).filter((tool) => !allowedToolSet || allowedToolSet.has(tool));
|
|
335
|
+
const excludeTools = [...new Set((input.excludeTools ?? []).map((tool) => tool.trim()).filter(Boolean))];
|
|
336
|
+
const excludedToolSet = new Set(excludeTools);
|
|
337
|
+
const effectiveDeclaredBuiltinTools = declaredBuiltinTools.filter((tool) => !excludedToolSet.has(tool));
|
|
338
|
+
const fanoutAuthorized = effectiveDeclaredBuiltinTools.includes("subagent") || (
|
|
339
|
+
input.allowNestedSubagents === true &&
|
|
340
|
+
!excludedToolSet.has("subagent") &&
|
|
341
|
+
(!allowedToolSet || allowedToolSet.has("subagent"))
|
|
342
|
+
);
|
|
343
|
+
const toolExtensionPaths: string[] = capabilityCeiling?.denyExtensions
|
|
344
|
+
? []
|
|
345
|
+
: (input.tools ?? []).filter(
|
|
346
|
+
(tool) =>
|
|
347
|
+
!requestedBuiltinTools.includes(tool) &&
|
|
348
|
+
(tool.includes("/") || tool.endsWith(".ts") || tool.endsWith(".js")),
|
|
349
|
+
);
|
|
350
|
+
const mcpResolution = capabilityCeiling?.denyExtensions
|
|
351
|
+
? { selections: [], unresolvedSelectors: [] }
|
|
352
|
+
: resolveMcpDirectToolResolution(input.mcpDirectTools, input.cwd, input.runtimeSnapshotHost);
|
|
353
|
+
if (mcpResolution.runtimeServerNames?.length) {
|
|
354
|
+
throw new Error(formatRuntimeSnapshotMcpServersError(input.agentName, mcpResolution.runtimeServerNames));
|
|
355
|
+
}
|
|
356
|
+
if (mcpResolution.unresolvedSelectors.length > 0) {
|
|
357
|
+
throw new Error(formatUnresolvedMcpDirectToolSelectors(mcpResolution.unresolvedSelectors));
|
|
358
|
+
}
|
|
359
|
+
const resolvedMcpSelections = mcpResolution.selections;
|
|
360
|
+
const resolvedMcpNames = new Set(resolvedMcpSelections.map((selection) => selection.name));
|
|
361
|
+
const legacyMcpNameCounts = countLegacyUnderscoreMcpToolNames(resolvedMcpSelections);
|
|
362
|
+
const effectiveMcpSelections = resolvedMcpSelections.filter(
|
|
363
|
+
(selection) =>
|
|
364
|
+
!allowedToolSet ||
|
|
365
|
+
allowedToolSet.has(selection.name) ||
|
|
366
|
+
isLegacyUnderscoreMcpToolAllowed(selection, allowedToolSet, resolvedMcpNames, legacyMcpNameCounts),
|
|
367
|
+
).filter((selection) => !excludedToolSet.has(selection.name));
|
|
368
|
+
const effectiveMcpTools = effectiveMcpSelections.map(
|
|
369
|
+
(selection) => selection.name,
|
|
370
|
+
);
|
|
371
|
+
const explicitToolAllowlist =
|
|
372
|
+
input.tools !== undefined ||
|
|
373
|
+
(input.mcpDirectTools?.length ?? 0) > 0 ||
|
|
374
|
+
allowedToolSet !== undefined;
|
|
375
|
+
const internalTools = (input.structuredOutput ? ["structured_output"] : []).filter((tool) => !excludedToolSet.has(tool));
|
|
376
|
+
const effectiveToolAllowlist = [
|
|
377
|
+
...new Set([
|
|
378
|
+
...effectiveDeclaredBuiltinTools,
|
|
379
|
+
...effectiveMcpTools,
|
|
380
|
+
...internalTools,
|
|
381
|
+
]),
|
|
382
|
+
];
|
|
383
|
+
// Supervisor-coordination names stay in the --tools allowlist but are never
|
|
384
|
+
// strict requirements: children register contact_supervisor at runtime through
|
|
385
|
+
// the native supervisor channel (or pi-intercom). The pre-0.50 bridge always
|
|
386
|
+
// appended intercom alongside contact_supervisor, so that exact pairing is
|
|
387
|
+
// legacy plumbing, not a user demand for an external intercom provider;
|
|
388
|
+
// a lone intercom entry stays strictly required (#1207).
|
|
389
|
+
const legacySupervisorPairing = effectiveDeclaredBuiltinTools.includes("contact_supervisor");
|
|
390
|
+
const requiredChildTools = explicitToolAllowlist
|
|
391
|
+
? [
|
|
392
|
+
...new Set([
|
|
393
|
+
...(input.tools !== undefined ? effectiveDeclaredBuiltinTools : []),
|
|
394
|
+
...(input.mcpDirectTools?.length ? effectiveMcpTools : []),
|
|
395
|
+
...internalTools,
|
|
396
|
+
].filter((tool) => tool !== "contact_supervisor" && (!legacySupervisorPairing || tool !== "intercom"))),
|
|
397
|
+
]
|
|
398
|
+
: [];
|
|
399
|
+
const permSystemExt = capabilityCeiling?.denyExtensions
|
|
400
|
+
? undefined
|
|
401
|
+
: hasPermissionRules(input.permissionRules)
|
|
402
|
+
? resolvePermissionSystemExtension()
|
|
403
|
+
: undefined;
|
|
404
|
+
if (input.fast && capabilityCeiling?.denyExtensions) throw new Error("fast mode requires a child runtime extension, but this launch denies extensions.");
|
|
405
|
+
const fastModeExtensions = resolveFastModeExtension({ fast: input.fast, model: input.model, modelCandidates: input.modelCandidates, agentName: input.agentName });
|
|
406
|
+
const runtimeExtensions = [
|
|
407
|
+
PROMPT_RUNTIME_EXTENSION_PATH,
|
|
408
|
+
...fastModeExtensions,
|
|
409
|
+
...(fanoutAuthorized ? [FANOUT_CHILD_EXTENSION_PATH] : []),
|
|
410
|
+
...(permSystemExt ? [permSystemExt] : []),
|
|
411
|
+
];
|
|
412
|
+
const disableAmbientExtensions =
|
|
413
|
+
capabilityCeiling?.denyExtensions === true ||
|
|
414
|
+
input.extensions !== undefined;
|
|
415
|
+
const warnings: string[] = [];
|
|
416
|
+
// An explicit empty list disables ambient extensions, including model providers.
|
|
417
|
+
if (capabilityCeiling?.denyExtensions !== true && Array.isArray(input.extensions) && input.extensions.length === 0) {
|
|
418
|
+
const agentLabel = input.agentName ? ` for agent '${input.agentName}'` : "";
|
|
419
|
+
warnings.push(
|
|
420
|
+
`extensions: [] override${agentLabel} disables ALL ambient extensions for this child (not just "adds nothing"), `
|
|
421
|
+
+ "including any model-provider extension needed to resolve a provider-qualified model. "
|
|
422
|
+
+ "List the extensions this child actually needs instead of an empty array.",
|
|
423
|
+
);
|
|
424
|
+
}
|
|
425
|
+
const configuredExtensions = capabilityCeiling?.denyExtensions
|
|
426
|
+
? []
|
|
427
|
+
: [
|
|
428
|
+
...toolExtensionPaths,
|
|
429
|
+
...(input.extensions ?? []),
|
|
430
|
+
...(input.subagentOnlyExtensions ?? []),
|
|
431
|
+
];
|
|
432
|
+
const extensionArgs = disableAmbientExtensions
|
|
433
|
+
? [...new Set([...runtimeExtensions, ...configuredExtensions])]
|
|
434
|
+
: [
|
|
435
|
+
...new Set([
|
|
436
|
+
...runtimeExtensions,
|
|
437
|
+
...toolExtensionPaths,
|
|
438
|
+
...(input.subagentOnlyExtensions ?? []),
|
|
439
|
+
]),
|
|
440
|
+
];
|
|
441
|
+
const requestedToolNames =
|
|
442
|
+
input.tools !== undefined
|
|
443
|
+
? [
|
|
444
|
+
...new Set([
|
|
445
|
+
...requestedBuiltinTools,
|
|
446
|
+
...resolvedMcpSelections.map((selection) => selection.name),
|
|
447
|
+
]),
|
|
448
|
+
]
|
|
449
|
+
: undefined;
|
|
450
|
+
const capabilityAudit = capabilityCeiling
|
|
451
|
+
? ({
|
|
452
|
+
ceiling: capabilityCeiling,
|
|
453
|
+
...(requestedToolNames ? { requestedTools: requestedToolNames } : {}),
|
|
454
|
+
effectiveTools: effectiveToolAllowlist,
|
|
455
|
+
...(excludeTools.length > 0 ? { excludeTools } : {}),
|
|
456
|
+
removedTools:
|
|
457
|
+
requestedToolNames?.filter(
|
|
458
|
+
(tool) => !effectiveToolAllowlist.includes(tool),
|
|
459
|
+
) ?? [],
|
|
460
|
+
internalTools,
|
|
461
|
+
extensionsDenied: capabilityCeiling.denyExtensions,
|
|
462
|
+
removedExtensionCount: capabilityCeiling.denyExtensions
|
|
463
|
+
? (input.extensions?.length ?? 0) +
|
|
464
|
+
(input.subagentOnlyExtensions?.length ?? 0) +
|
|
465
|
+
(input.tools ?? []).filter(
|
|
466
|
+
(tool) =>
|
|
467
|
+
tool.includes("/") ||
|
|
468
|
+
tool.endsWith(".ts") ||
|
|
469
|
+
tool.endsWith(".js"),
|
|
470
|
+
).length
|
|
471
|
+
: 0,
|
|
472
|
+
requestedMcpToolCount: input.mcpDirectTools?.length ?? 0,
|
|
473
|
+
effectiveMcpTools,
|
|
474
|
+
agentAllowed:
|
|
475
|
+
input.agentName === undefined
|
|
476
|
+
? true
|
|
477
|
+
: isAgentAllowedByCapabilityCeiling(
|
|
478
|
+
input.agentName,
|
|
479
|
+
capabilityCeiling,
|
|
480
|
+
),
|
|
481
|
+
...(capabilityCeilingAgentRestrictionSources(capabilityCeiling)
|
|
482
|
+
? {
|
|
483
|
+
agentRestrictionSources:
|
|
484
|
+
capabilityCeilingAgentRestrictionSources(capabilityCeiling),
|
|
485
|
+
}
|
|
486
|
+
: {}),
|
|
487
|
+
} satisfies SubagentCapabilityAudit)
|
|
488
|
+
: undefined;
|
|
489
|
+
return {
|
|
490
|
+
...(capabilityCeiling ? { capabilityCeiling } : {}),
|
|
491
|
+
requestedBuiltinTools,
|
|
492
|
+
declaredBuiltinTools,
|
|
493
|
+
excludeTools,
|
|
494
|
+
toolExtensionPaths,
|
|
495
|
+
resolvedMcpSelections,
|
|
496
|
+
effectiveMcpSelections,
|
|
497
|
+
effectiveMcpTools,
|
|
498
|
+
explicitToolAllowlist,
|
|
499
|
+
internalTools,
|
|
500
|
+
effectiveToolAllowlist,
|
|
501
|
+
requiredChildTools,
|
|
502
|
+
fanoutAuthorized,
|
|
503
|
+
runtimeExtensions,
|
|
504
|
+
configuredExtensions,
|
|
505
|
+
extensionArgs,
|
|
506
|
+
disableAmbientExtensions,
|
|
507
|
+
warnings,
|
|
508
|
+
...(capabilityAudit ? { capabilityAudit } : {}),
|
|
509
|
+
};
|
|
510
|
+
}
|
|
511
|
+
|
|
512
|
+
// Capability ceilings persisted before #1685 may still name hyphenated MCP server prefixes with underscores.
|
|
513
|
+
function countLegacyUnderscoreMcpToolNames(selections: readonly ResolvedMcpDirectToolSelection[]): Map<string, number> {
|
|
514
|
+
const counts = new Map<string, number>();
|
|
515
|
+
for (const selection of selections) {
|
|
516
|
+
const legacyName = legacyUnderscoreMcpToolName(selection);
|
|
517
|
+
if (legacyName !== selection.name) counts.set(legacyName, (counts.get(legacyName) ?? 0) + 1);
|
|
518
|
+
}
|
|
519
|
+
return counts;
|
|
520
|
+
}
|
|
521
|
+
|
|
522
|
+
function isLegacyUnderscoreMcpToolAllowed(
|
|
523
|
+
selection: ResolvedMcpDirectToolSelection,
|
|
524
|
+
allowedToolSet: ReadonlySet<string>,
|
|
525
|
+
resolvedMcpNames: ReadonlySet<string>,
|
|
526
|
+
legacyMcpNameCounts: ReadonlyMap<string, number>,
|
|
527
|
+
): boolean {
|
|
528
|
+
const legacyName = legacyUnderscoreMcpToolName(selection);
|
|
529
|
+
return legacyMcpNameCounts.get(legacyName) === 1 && !resolvedMcpNames.has(legacyName) && allowedToolSet.has(legacyName);
|
|
530
|
+
}
|
|
531
|
+
|
|
532
|
+
function legacyUnderscoreMcpToolName(selection: ResolvedMcpDirectToolSelection): string {
|
|
533
|
+
const slash = selection.selector.indexOf("/");
|
|
534
|
+
if (slash < 1) return selection.name;
|
|
535
|
+
const toolName = selection.selector.slice(slash + 1);
|
|
536
|
+
const suffix = `_${toolName}`;
|
|
537
|
+
if (!selection.name.endsWith(suffix)) return selection.name;
|
|
538
|
+
const prefix = selection.name.slice(0, -suffix.length);
|
|
539
|
+
return `${prefix.replace(/-/g, "_")}${suffix}`;
|
|
540
|
+
}
|
|
@@ -0,0 +1,133 @@
|
|
|
1
|
+
import { parseExternalCliJsonlEvent, type ExternalCliParser, type ExternalCliParserProgress, type ExternalCliParserTerminal } from "./external-cli-runner.ts";
|
|
2
|
+
import type { ExternalCliPreflightSpec } from "./external-cli-preflight.ts";
|
|
3
|
+
|
|
4
|
+
const MAX_EVENT_TYPE_LENGTH = 128;
|
|
5
|
+
const MAX_ERROR_LENGTH = 4_096;
|
|
6
|
+
|
|
7
|
+
export const CLAUDE_CODE_ADAPTER_ID = "claude-code" as const;
|
|
8
|
+
export const CLAUDE_CODE_WRITER_ADAPTER_ID = "claude-code-writer" as const;
|
|
9
|
+
export const CLAUDE_CODE_WRITER_TOOLS = "Read,Write,Edit,Glob,Grep" as const;
|
|
10
|
+
export const CLAUDE_CODE_ENV_ALLOWLIST = [
|
|
11
|
+
"PATH",
|
|
12
|
+
"HOME",
|
|
13
|
+
"USERPROFILE",
|
|
14
|
+
"USER",
|
|
15
|
+
"LOGNAME",
|
|
16
|
+
"TMPDIR",
|
|
17
|
+
"CLAUDE_CONFIG_DIR",
|
|
18
|
+
"ANTHROPIC_API_KEY",
|
|
19
|
+
"ANTHROPIC_AUTH_TOKEN",
|
|
20
|
+
"ANTHROPIC_BASE_URL",
|
|
21
|
+
"CLAUDE_CODE_OAUTH_TOKEN",
|
|
22
|
+
"CLAUDE_CODE_USE_BEDROCK",
|
|
23
|
+
"CLAUDE_CODE_USE_VERTEX",
|
|
24
|
+
"CLAUDE_CODE_USE_FOUNDRY",
|
|
25
|
+
"AWS_PROFILE",
|
|
26
|
+
"AWS_REGION",
|
|
27
|
+
"AWS_DEFAULT_REGION",
|
|
28
|
+
"AWS_ACCESS_KEY_ID",
|
|
29
|
+
"AWS_SECRET_ACCESS_KEY",
|
|
30
|
+
"AWS_SESSION_TOKEN",
|
|
31
|
+
"AWS_BEARER_TOKEN_BEDROCK",
|
|
32
|
+
"GOOGLE_APPLICATION_CREDENTIALS",
|
|
33
|
+
"CLOUD_ML_REGION",
|
|
34
|
+
"ANTHROPIC_VERTEX_PROJECT_ID",
|
|
35
|
+
"HTTP_PROXY",
|
|
36
|
+
"HTTPS_PROXY",
|
|
37
|
+
"NO_PROXY",
|
|
38
|
+
"http_proxy",
|
|
39
|
+
"https_proxy",
|
|
40
|
+
"no_proxy",
|
|
41
|
+
"SSL_CERT_FILE",
|
|
42
|
+
"SSL_CERT_DIR",
|
|
43
|
+
] as const;
|
|
44
|
+
|
|
45
|
+
function terminalError(event: Record<string, unknown>): string {
|
|
46
|
+
for (const value of [event.error, event.result]) {
|
|
47
|
+
if (typeof value === "string" && value.trim()) return value.trim().slice(0, MAX_ERROR_LENGTH);
|
|
48
|
+
}
|
|
49
|
+
if (Array.isArray(event.errors)) {
|
|
50
|
+
const messages = event.errors.filter((value): value is string => typeof value === "string" && Boolean(value.trim()));
|
|
51
|
+
if (messages.length > 0) return messages.join("; ").slice(0, MAX_ERROR_LENGTH);
|
|
52
|
+
}
|
|
53
|
+
const subtype = typeof event.subtype === "string" && event.subtype ? event.subtype : "unknown";
|
|
54
|
+
return `Claude Code reported terminal result ${subtype}.`;
|
|
55
|
+
}
|
|
56
|
+
|
|
57
|
+
export function createClaudeCodeJsonlParser(): ExternalCliParser {
|
|
58
|
+
let eventCount = 0;
|
|
59
|
+
let terminal: ExternalCliParserTerminal | undefined;
|
|
60
|
+
return {
|
|
61
|
+
parseLine(line): ExternalCliParserProgress {
|
|
62
|
+
const event = parseExternalCliJsonlEvent(line, "Claude Code", MAX_EVENT_TYPE_LENGTH);
|
|
63
|
+
if (terminal && event.type === "result") throw new Error("Claude Code emitted a duplicate terminal result.");
|
|
64
|
+
eventCount += 1;
|
|
65
|
+
if (!terminal && event.type === "result") {
|
|
66
|
+
if (event.subtype === "success" && event.is_error === false && typeof event.result === "string" && event.result.trim()) {
|
|
67
|
+
terminal = { state: "completed", output: event.result.trim() };
|
|
68
|
+
} else {
|
|
69
|
+
terminal = { state: "failed", error: terminalError(event) };
|
|
70
|
+
}
|
|
71
|
+
}
|
|
72
|
+
return { phase: terminal ? terminal.state : "streaming", eventCount };
|
|
73
|
+
},
|
|
74
|
+
finish(): ExternalCliParserTerminal | undefined {
|
|
75
|
+
return terminal;
|
|
76
|
+
},
|
|
77
|
+
};
|
|
78
|
+
}
|
|
79
|
+
|
|
80
|
+
export function resolveClaudeCodeLaunch(input: {
|
|
81
|
+
adapter: typeof CLAUDE_CODE_ADAPTER_ID | typeof CLAUDE_CODE_WRITER_ADAPTER_ID;
|
|
82
|
+
command: string;
|
|
83
|
+
/** Test-only executable prefix for a fake Claude Code process. */
|
|
84
|
+
commandPrefixArgs?: readonly string[];
|
|
85
|
+
}): {
|
|
86
|
+
command: string;
|
|
87
|
+
args: string[];
|
|
88
|
+
finalOutputPath?: undefined;
|
|
89
|
+
promptFilePath?: undefined;
|
|
90
|
+
temporaryDirectories?: undefined;
|
|
91
|
+
environment: { allowlist: readonly string[] };
|
|
92
|
+
preflight: ExternalCliPreflightSpec;
|
|
93
|
+
parser: ExternalCliParser;
|
|
94
|
+
} {
|
|
95
|
+
const writer = input.adapter === CLAUDE_CODE_WRITER_ADAPTER_ID;
|
|
96
|
+
const prefix = [...(input.commandPrefixArgs ?? [])];
|
|
97
|
+
const args = [
|
|
98
|
+
...prefix,
|
|
99
|
+
"-p",
|
|
100
|
+
"--input-format", "text",
|
|
101
|
+
"--output-format", "stream-json",
|
|
102
|
+
"--verbose",
|
|
103
|
+
"--permission-mode", writer ? "acceptEdits" : "plan",
|
|
104
|
+
"--tools", writer ? CLAUDE_CODE_WRITER_TOOLS : "",
|
|
105
|
+
"--strict-mcp-config",
|
|
106
|
+
"--mcp-config", '{"mcpServers":{}}',
|
|
107
|
+
"--setting-sources", "user",
|
|
108
|
+
"--no-session-persistence",
|
|
109
|
+
"--disable-slash-commands",
|
|
110
|
+
"--no-chrome",
|
|
111
|
+
];
|
|
112
|
+
return {
|
|
113
|
+
command: input.command,
|
|
114
|
+
args,
|
|
115
|
+
environment: { allowlist: CLAUDE_CODE_ENV_ALLOWLIST },
|
|
116
|
+
preflight: {
|
|
117
|
+
id: input.adapter,
|
|
118
|
+
versionArgs: [...prefix, "--version"],
|
|
119
|
+
helpArgs: [...prefix, "--help"],
|
|
120
|
+
validate(result) {
|
|
121
|
+
// Claude Code now publishes both semver (`2.1.259 (Claude Code)`) and
|
|
122
|
+
// calendar/platform (`2026.4.24 macos-arm64 (2026-04-27)`) versions.
|
|
123
|
+
// The launch flags are validated from --help below, so only require a
|
|
124
|
+
// recognizable release identifier here rather than one display format.
|
|
125
|
+
if (!/^(?:\d+\.\d+\.\d+(?:[-+][0-9A-Za-z.-]+)? \(Claude Code\)|\d{4}\.\d{1,2}\.\d{1,2} [A-Za-z0-9._-]+ \(\d{4}-\d{2}-\d{2}\))$/.test(result.version)) throw new Error(`Unsupported Claude Code version response: ${JSON.stringify(result.version)}.`);
|
|
126
|
+
for (const required of ["Claude Code - starts an interactive session", "--print", "--input-format", "stream-json", "--verbose", "--permission-mode", writer ? "acceptEdits" : "plan", "--tools", "--strict-mcp-config", "--mcp-config", "--setting-sources", "--no-session-persistence", "--disable-slash-commands", "--no-chrome"]) {
|
|
127
|
+
if (!result.help.includes(required)) throw new Error(`Claude Code help does not document required option ${JSON.stringify(required)}.`);
|
|
128
|
+
}
|
|
129
|
+
},
|
|
130
|
+
},
|
|
131
|
+
parser: createClaudeCodeJsonlParser(),
|
|
132
|
+
};
|
|
133
|
+
}
|