@xzzpig/pi-subagents 0.8.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 +443 -0
- package/README.md +2 -2
- 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 +1 -1
- package/agents/scout.md +1 -1
- package/docs/agents.md +151 -39
- package/docs/configuration.md +81 -22
- package/docs/extension-api.md +69 -14
- package/docs/missions.md +2 -0
- package/docs/models.md +32 -9
- package/docs/observability.md +22 -20
- package/docs/tool-reference.md +123 -14
- package/docs/watchdog.md +92 -114
- package/docs/workflows.md +142 -4
- package/install.mjs +1 -1
- package/package.json +5 -4
- package/prompts/review-loop.md +2 -2
- package/skills/council-mode/SKILL.md +48 -243
- package/skills/council-mode/references/pass-contracts.md +150 -0
- package/skills/pi-subagents/SKILL.md +89 -35
- package/skills/pi-subagents/references/constraints-and-recipes.md +30 -234
- package/skills/pi-subagents/references/execution-controls.md +91 -15
- package/skills/pi-subagents/references/management-authoring-rpc.md +5 -5
- package/skills/pi-subagents/references/multi-lane-orchestration.md +13 -1
- package/skills/pi-subagents/references/prompting-and-roles.md +59 -31
- package/skills/pi-subagents/references/review-and-validation.md +73 -0
- package/src/agents/agent-management.ts +370 -114
- package/src/agents/agent-refinements.ts +4 -4
- package/src/agents/agent-serializer.ts +12 -2
- package/src/agents/agents.ts +919 -372
- 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-runs.ts +67 -4
- package/src/api/preflight.ts +48 -18
- package/src/api/shared-types.ts +6 -0
- package/src/extension/config.ts +90 -0
- package/src/extension/doctor.ts +5 -13
- package/src/extension/fanout-child.ts +14 -14
- package/src/extension/index.ts +115 -37
- package/src/extension/public-execution.ts +103 -15
- package/src/extension/rpc.ts +120 -25
- package/src/extension/schemas.ts +57 -21
- package/src/extension/tool-description.ts +48 -26
- package/src/inspectors/herdr/actions.ts +2 -1
- package/src/inspectors/herdr/inspector-runner.ts +21 -23
- package/src/inspectors/herdr/session-roots-codec.ts +42 -0
- package/src/integrations/herdr-status.ts +51 -3
- 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 +366 -128
- package/src/runs/background/async-job-tracker.ts +95 -15
- package/src/runs/background/async-resume.ts +45 -28
- package/src/runs/background/async-retention.ts +20 -3
- package/src/runs/background/async-status-snapshot.ts +23 -261
- package/src/runs/background/async-status.ts +189 -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 +74 -8
- package/src/runs/background/control-channel.ts +4 -205
- package/src/runs/background/fleet-view.ts +38 -22
- package/src/runs/background/inspect-rpc.ts +8 -8
- package/src/runs/background/notify.ts +238 -12
- 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 +39 -16
- 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 +84 -17
- 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 +10 -4
- package/src/runs/background/steering.ts +8 -15
- package/src/runs/background/subagent-runner.ts +676 -1161
- 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 +43 -2
- package/src/runs/background/wait-config.ts +23 -9
- package/src/runs/background/wait-tool.ts +26 -19
- package/src/runs/foreground/async-steering-action.ts +3 -19
- package/src/runs/foreground/execution.ts +468 -499
- package/src/runs/foreground/foreground-control.ts +13 -0
- package/src/runs/foreground/foreground-history.ts +23 -1
- package/src/runs/foreground/subagent-executor.ts +1172 -400
- package/src/runs/foreground/workflow-detach-reconcile.ts +140 -115
- 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 +138 -36
- 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 +32 -6
- 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 +6 -5
- package/src/runs/shared/cursor-agent-adapter.ts +114 -0
- package/src/runs/shared/dynamic-fanout.ts +3 -3
- 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 +348 -55
- package/src/runs/shared/fast-mode-extension.ts +5 -5
- 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 +139 -9
- package/src/runs/shared/model-fallback.ts +142 -14
- package/src/runs/shared/mutation-evidence.ts +57 -3
- 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 +12 -7
- package/src/runs/shared/parallel-handoff.ts +423 -7
- package/src/runs/shared/parallel-utils.ts +15 -7
- 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 +49 -9
- package/src/runs/shared/subagent-control.ts +6 -2
- package/src/runs/shared/subagent-prompt-runtime.ts +188 -365
- package/src/runs/shared/task-intent.ts +21 -7
- package/src/runs/shared/tool-availability.ts +18 -62
- 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 +8 -1
- 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 +19 -105
- package/src/shared/shortcuts.ts +17 -0
- package/src/shared/thinking-ceiling.ts +0 -6
- package/src/shared/types.ts +524 -70
- 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 +217 -82
- 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 +1429 -163
- 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/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 +988 -59
- 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 -935
- 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
|
@@ -1,39 +1,30 @@
|
|
|
1
1
|
import { createHash } from "node:crypto";
|
|
2
2
|
import * as fs from "node:fs";
|
|
3
3
|
import * as path from "node:path";
|
|
4
|
-
import type { ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
4
|
+
import type { BeforeProviderRequestEvent, ExtensionAPI, ExtensionContext } from "@earendil-works/pi-coding-agent";
|
|
5
5
|
import { registerNativeSupervisorClient } from "../../intercom/native-supervisor-channel.ts";
|
|
6
|
-
import {
|
|
7
|
-
import {
|
|
8
|
-
import {
|
|
9
|
-
import {
|
|
10
|
-
import {
|
|
11
|
-
import {
|
|
12
|
-
import {
|
|
13
|
-
|
|
14
|
-
formatChildToolDiagnostic,
|
|
15
|
-
MCP_DIRECT_CHILD_TOOLS_ENV,
|
|
16
|
-
REQUIRED_CHILD_TOOLS_ENV,
|
|
17
|
-
writeChildToolDiagnostic,
|
|
18
|
-
type ChildToolDiagnostic,
|
|
19
|
-
} from "./tool-availability.ts";
|
|
20
|
-
import { TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, decodeToolBudgetEnv, shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
|
|
21
|
-
import type { JsonSchemaObject, ResolvedToolBudget, SubagentState } from "../../shared/types.ts";
|
|
6
|
+
import { permissionDecision } from "./permissions.ts";
|
|
7
|
+
import type { SteerRequest } from "../background/control-channel.ts";
|
|
8
|
+
import { RUNTIME_EXTENSION_ACK_EVENT, isRuntimeAcknowledgedExtensionId } from "./runtime-acknowledged-extensions.ts";
|
|
9
|
+
import { createStructuredOutputToolParameters, MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR, validateStructuredOutputValue } from "./structured-output.ts";
|
|
10
|
+
import { validateAcceptanceReport } from "./acceptance.ts";
|
|
11
|
+
import { formatChildToolDiagnostic } from "./tool-availability.ts";
|
|
12
|
+
import { shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
|
|
13
|
+
import type { ResolvedToolBudget, SubagentState } from "../../shared/types.ts";
|
|
22
14
|
import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
|
|
23
|
-
import {
|
|
15
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
24
16
|
import { registerChildWatchdog } from "../../watchdog/register-child.ts";
|
|
25
|
-
import {
|
|
17
|
+
import type { ChildWatchdogConfig } from "../../watchdog/child-status.ts";
|
|
26
18
|
import { requestWatchdogPermission, type WatchdogPermissionRequest, type WatchdogPermissionResult } from "../../watchdog/permission-arbiter.ts";
|
|
27
19
|
import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../watchdog/types.ts";
|
|
28
|
-
import { resolveWaitToolConfig } from "../background/wait-config.ts";
|
|
29
20
|
import { registerWaitTool } from "../background/wait-tool.ts";
|
|
30
21
|
import { drainOutstandingWork } from "../background/auto-drain.ts";
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
36
|
-
|
|
22
|
+
import {
|
|
23
|
+
childSupervisorMetadata,
|
|
24
|
+
evaluateChildToolDiagnostic,
|
|
25
|
+
type ChildPermissions,
|
|
26
|
+
type ChildRuntimeConfig,
|
|
27
|
+
} from "./child-runtime-config.ts";
|
|
37
28
|
|
|
38
29
|
const STRUCTURED_OUTPUT_INSTRUCTIONS = [
|
|
39
30
|
"This subagent step has a strict structured output contract.",
|
|
@@ -68,49 +59,13 @@ const PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([
|
|
|
68
59
|
"subagent-control-notice",
|
|
69
60
|
]);
|
|
70
61
|
const SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\s*pi-subagents\s*<\/name>/;
|
|
71
|
-
const
|
|
62
|
+
const PROJECT_CONTEXT_XML_HEADER = "\n\n<project_context>\n\n";
|
|
63
|
+
const PROJECT_CONTEXT_LEGACY_HEADER = "\n\n# Project Context\n\nProject-specific instructions and guidelines:\n\n";
|
|
72
64
|
const SKILLS_HEADER = "\n\nThe following skills provide specialized instructions for specific tasks.";
|
|
73
65
|
const DATE_HEADER = "\nCurrent date:";
|
|
74
66
|
|
|
75
|
-
function
|
|
76
|
-
|
|
77
|
-
if (value === undefined) return undefined;
|
|
78
|
-
return value !== "0";
|
|
79
|
-
}
|
|
80
|
-
|
|
81
|
-
function readRequiredChildTools(): string[] | undefined {
|
|
82
|
-
const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();
|
|
83
|
-
if (!encoded) return undefined;
|
|
84
|
-
const required = JSON.parse(encoded) as unknown;
|
|
85
|
-
if (!Array.isArray(required) || required.some((name) => typeof name !== "string" || !name)) {
|
|
86
|
-
throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);
|
|
87
|
-
}
|
|
88
|
-
return required;
|
|
89
|
-
}
|
|
90
|
-
|
|
91
|
-
function readMcpDirectChildTools(): string[] | undefined {
|
|
92
|
-
const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();
|
|
93
|
-
if (!encoded) return undefined;
|
|
94
|
-
try {
|
|
95
|
-
const tools = JSON.parse(encoded) as unknown;
|
|
96
|
-
if (!Array.isArray(tools) || tools.some((name) => typeof name !== "string" || !name)) return undefined;
|
|
97
|
-
return tools;
|
|
98
|
-
} catch {
|
|
99
|
-
return undefined;
|
|
100
|
-
}
|
|
101
|
-
}
|
|
102
|
-
|
|
103
|
-
function refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {
|
|
104
|
-
const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();
|
|
105
|
-
const required = readRequiredChildTools();
|
|
106
|
-
if (!filePath || !required) return undefined;
|
|
107
|
-
const available = pi.getAllTools().map((tool) => tool.name);
|
|
108
|
-
return writeChildToolDiagnostic(filePath, required, available, process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(), readMcpDirectChildTools());
|
|
109
|
-
}
|
|
110
|
-
|
|
111
|
-
function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI): void {
|
|
112
|
-
const outputPath = process.env[RUNTIME_EXTENSION_ACK_PATH_ENV]?.trim();
|
|
113
|
-
if (!outputPath) return;
|
|
67
|
+
function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI, sink: ((ids: string[]) => void) | undefined): void {
|
|
68
|
+
if (!sink) return;
|
|
114
69
|
const ids: string[] = [];
|
|
115
70
|
let finalized = false;
|
|
116
71
|
const acknowledge = (payload: unknown): undefined => {
|
|
@@ -122,7 +77,7 @@ function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI): void {
|
|
|
122
77
|
const finalize = (): undefined => {
|
|
123
78
|
if (finalized) return undefined;
|
|
124
79
|
finalized = true;
|
|
125
|
-
|
|
80
|
+
sink(ids);
|
|
126
81
|
return undefined;
|
|
127
82
|
};
|
|
128
83
|
try {
|
|
@@ -148,10 +103,80 @@ function findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[
|
|
|
148
103
|
}
|
|
149
104
|
|
|
150
105
|
export function stripProjectContext(prompt: string): string {
|
|
151
|
-
const
|
|
152
|
-
if (
|
|
153
|
-
|
|
154
|
-
|
|
106
|
+
const xmlStartIndex = prompt.indexOf(PROJECT_CONTEXT_XML_HEADER);
|
|
107
|
+
if (xmlStartIndex !== -1) {
|
|
108
|
+
const closingTag = "</project_context>";
|
|
109
|
+
const closingIndex = prompt.indexOf(closingTag, xmlStartIndex + PROJECT_CONTEXT_XML_HEADER.length);
|
|
110
|
+
if (closingIndex !== -1) {
|
|
111
|
+
return `${prompt.slice(0, xmlStartIndex)}${prompt.slice(closingIndex + closingTag.length)}`;
|
|
112
|
+
}
|
|
113
|
+
}
|
|
114
|
+
const legacyStartIndex = prompt.indexOf(PROJECT_CONTEXT_LEGACY_HEADER);
|
|
115
|
+
if (legacyStartIndex === -1) return prompt;
|
|
116
|
+
const endIndex = findSectionEnd(prompt, legacyStartIndex + PROJECT_CONTEXT_LEGACY_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);
|
|
117
|
+
return `${prompt.slice(0, legacyStartIndex)}${prompt.slice(endIndex)}`;
|
|
118
|
+
}
|
|
119
|
+
|
|
120
|
+
const GLOBAL_CONTEXT_FILE_NAMES = new Set(["agents.md", "agents.override.md", "claude.md"]);
|
|
121
|
+
|
|
122
|
+
function canonicalDirectory(dir: string): string {
|
|
123
|
+
try {
|
|
124
|
+
return fs.realpathSync(dir);
|
|
125
|
+
} catch {
|
|
126
|
+
return path.resolve(dir);
|
|
127
|
+
}
|
|
128
|
+
}
|
|
129
|
+
|
|
130
|
+
function expandContextPath(filePath: string): string {
|
|
131
|
+
const home = process.env.HOME ?? process.env.USERPROFILE;
|
|
132
|
+
return filePath === "~"
|
|
133
|
+
? home ?? filePath
|
|
134
|
+
: /^~[\\/]/.test(filePath)
|
|
135
|
+
? path.join(home ?? "~", filePath.slice(2))
|
|
136
|
+
: filePath;
|
|
137
|
+
}
|
|
138
|
+
|
|
139
|
+
function isContextFilePath(filePath: string): boolean {
|
|
140
|
+
return GLOBAL_CONTEXT_FILE_NAMES.has(path.basename(expandContextPath(filePath)).toLowerCase());
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
function isGlobalContextFile(filePath: string): boolean {
|
|
144
|
+
const expanded = expandContextPath(filePath);
|
|
145
|
+
if (!isContextFilePath(filePath)) return false;
|
|
146
|
+
return canonicalDirectory(path.dirname(expanded)) === canonicalDirectory(getAgentDir());
|
|
147
|
+
}
|
|
148
|
+
|
|
149
|
+
function stripGlobalInstructionsFromXmlContext(context: string): string {
|
|
150
|
+
const block = /<project_instructions\s+path=(["'])(.*?)\1\s*>[\s\S]*?<\/project_instructions>\s*/gi;
|
|
151
|
+
return context.replace(block, (match, _quote: string, filePath: string) => isGlobalContextFile(filePath) ? "" : match);
|
|
152
|
+
}
|
|
153
|
+
|
|
154
|
+
function stripGlobalInstructionsFromLegacyContext(context: string): string {
|
|
155
|
+
const sections = [...context.matchAll(/^## ([^\r\n]+)(?:\r?\n|$)/gm)]
|
|
156
|
+
.filter((match) => isContextFilePath(match[1]!.trim()));
|
|
157
|
+
let rewritten = "";
|
|
158
|
+
let cursor = 0;
|
|
159
|
+
for (let index = 0; index < sections.length; index++) {
|
|
160
|
+
const section = sections[index]!;
|
|
161
|
+
const start = section.index!;
|
|
162
|
+
const end = sections[index + 1]?.index ?? context.length;
|
|
163
|
+
rewritten += context.slice(cursor, start);
|
|
164
|
+
if (!isGlobalContextFile(section[1]!.trim())) rewritten += context.slice(start, end);
|
|
165
|
+
cursor = end;
|
|
166
|
+
}
|
|
167
|
+
return `${rewritten}${context.slice(cursor)}`;
|
|
168
|
+
}
|
|
169
|
+
|
|
170
|
+
export function stripGlobalContext(prompt: string): string {
|
|
171
|
+
const rewrittenXml = prompt.replace(/<project_context>[\s\S]*?<\/project_context>/gi, (context) => {
|
|
172
|
+
const rewritten = stripGlobalInstructionsFromXmlContext(context);
|
|
173
|
+
return /<project_instructions\b/i.test(rewritten) ? rewritten : "";
|
|
174
|
+
});
|
|
175
|
+
const legacyStartIndex = rewrittenXml.indexOf(PROJECT_CONTEXT_LEGACY_HEADER);
|
|
176
|
+
if (legacyStartIndex === -1) return rewrittenXml;
|
|
177
|
+
const legacyEndIndex = findSectionEnd(rewrittenXml, legacyStartIndex + PROJECT_CONTEXT_LEGACY_HEADER.length, [SKILLS_HEADER, DATE_HEADER]);
|
|
178
|
+
const legacyContext = rewrittenXml.slice(legacyStartIndex, legacyEndIndex);
|
|
179
|
+
return `${rewrittenXml.slice(0, legacyStartIndex)}${stripGlobalInstructionsFromLegacyContext(legacyContext)}${rewrittenXml.slice(legacyEndIndex)}`;
|
|
155
180
|
}
|
|
156
181
|
|
|
157
182
|
export function stripInheritedSkills(prompt: string): string {
|
|
@@ -177,19 +202,22 @@ function stripChildBoundaryInstructions(prompt: string): string {
|
|
|
177
202
|
|
|
178
203
|
export function rewriteSubagentPrompt(
|
|
179
204
|
prompt: string,
|
|
180
|
-
options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },
|
|
205
|
+
options: { inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean; fanoutChild?: boolean; structuredOutput?: boolean },
|
|
181
206
|
): string {
|
|
182
207
|
let rewritten = prompt;
|
|
183
208
|
if (!options.inheritProjectContext) {
|
|
184
209
|
rewritten = stripProjectContext(rewritten);
|
|
185
210
|
}
|
|
211
|
+
if (!options.inheritGlobalContext) {
|
|
212
|
+
rewritten = stripGlobalContext(rewritten);
|
|
213
|
+
}
|
|
186
214
|
if (!options.inheritSkills) {
|
|
187
215
|
rewritten = stripInheritedSkills(rewritten);
|
|
188
216
|
}
|
|
189
217
|
rewritten = stripSubagentOrchestrationSkill(rewritten);
|
|
190
218
|
rewritten = stripChildBoundaryInstructions(rewritten);
|
|
191
219
|
const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;
|
|
192
|
-
const structured =
|
|
220
|
+
const structured = options.structuredOutput ? `\n\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : "";
|
|
193
221
|
return `${boundary}${structured}\n\n${rewritten}`;
|
|
194
222
|
}
|
|
195
223
|
|
|
@@ -214,9 +242,26 @@ const PORTABLE_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
|
|
214
242
|
const MAX_PORTABLE_TOOL_ID_LENGTH = 64;
|
|
215
243
|
const COMPOSITE_TOOL_ID_APIS = new Set([
|
|
216
244
|
"azure-openai-responses",
|
|
245
|
+
"cursor-native",
|
|
217
246
|
"openai-completions",
|
|
218
247
|
"openai-responses",
|
|
219
248
|
]);
|
|
249
|
+
const PROMPT_CACHE_KEY_APIS = new Set([
|
|
250
|
+
"azure-openai-responses",
|
|
251
|
+
"openai-codex-responses",
|
|
252
|
+
"openai-completions",
|
|
253
|
+
"openai-responses",
|
|
254
|
+
]);
|
|
255
|
+
|
|
256
|
+
export function rewriteForkCacheProviderRequest(event: BeforeProviderRequestEvent, ctx: Pick<ExtensionContext, "model"> | undefined, forkCacheKey: string | undefined): unknown {
|
|
257
|
+
const key = forkCacheKey?.trim();
|
|
258
|
+
if (!key || !PROMPT_CACHE_KEY_APIS.has(ctx?.model?.api ?? "")) return undefined;
|
|
259
|
+
if (!event || typeof event !== "object") return undefined;
|
|
260
|
+
const payload = event.payload;
|
|
261
|
+
if (!payload || typeof payload !== "object" || Array.isArray(payload)) return undefined;
|
|
262
|
+
if (typeof (payload as { prompt_cache_key?: unknown }).prompt_cache_key !== "string") return undefined;
|
|
263
|
+
return { ...payload, prompt_cache_key: key };
|
|
264
|
+
}
|
|
220
265
|
|
|
221
266
|
function portableToolId(id: string): string {
|
|
222
267
|
if (PORTABLE_TOOL_ID_PATTERN.test(id) && id.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return id;
|
|
@@ -253,8 +298,8 @@ function stripAssistantSubagentToolCallBlocks(message: unknown): unknown | undef
|
|
|
253
298
|
return { ...m, content: filteredContent };
|
|
254
299
|
}
|
|
255
300
|
|
|
256
|
-
export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean } = {}): unknown[] {
|
|
257
|
-
const preserveCurrentFanoutToolHistory =
|
|
301
|
+
export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
|
|
302
|
+
const preserveCurrentFanoutToolHistory = options.preserveFanoutToolHistory === true;
|
|
258
303
|
const sanitizeToolIds = options.sanitizeToolIds ?? true;
|
|
259
304
|
let changed = false;
|
|
260
305
|
const filtered: unknown[] = [];
|
|
@@ -287,23 +332,20 @@ export function formatSteerMessage(request: SteerRequest): string {
|
|
|
287
332
|
|
|
288
333
|
export function registerPermissionGate(
|
|
289
334
|
pi: ExtensionAPI,
|
|
335
|
+
permissions: ChildPermissions | undefined,
|
|
336
|
+
childWatchdog: ChildWatchdogConfig | undefined,
|
|
290
337
|
requestPermission: (request: WatchdogPermissionRequest) => Promise<WatchdogPermissionResult> = requestWatchdogPermission,
|
|
291
338
|
): void {
|
|
292
|
-
const rules =
|
|
293
|
-
if (!rules) return;
|
|
339
|
+
const rules = permissions?.rules;
|
|
340
|
+
if (!rules || Object.keys(rules).length === 0) return;
|
|
341
|
+
const rawWatchdogConfig = childWatchdog ? JSON.stringify(childWatchdog) : undefined;
|
|
342
|
+
const timeoutMs = childWatchdog?.agentEndTimeoutMs ?? 30_000;
|
|
294
343
|
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: { toolName?: string; input?: unknown }, ctx: ExtensionContext) => unknown) => void;
|
|
295
344
|
onRuntimeEvent("tool_call", async (event, ctx) => {
|
|
296
345
|
const toolName = typeof event.toolName === "string" ? event.toolName : "tool";
|
|
297
346
|
const decision = permissionDecision(rules, toolName);
|
|
298
347
|
if (decision === "allow") return undefined;
|
|
299
348
|
if (decision === "deny") return { block: true, reason: `Blocked by pi-subagents permission rule: '${toolName}' is denied.` };
|
|
300
|
-
const rawWatchdogConfig = process.env[CHILD_WATCHDOG_CONFIG_ENV];
|
|
301
|
-
let timeoutMs = 30_000;
|
|
302
|
-
try {
|
|
303
|
-
timeoutMs = decodeChildWatchdogConfig(rawWatchdogConfig)?.agentEndTimeoutMs ?? timeoutMs;
|
|
304
|
-
} catch {
|
|
305
|
-
// The arbiter reports invalid configuration with the concrete decode error.
|
|
306
|
-
}
|
|
307
349
|
if (ctx.signal?.aborted) return { block: true, reason: "Blocked by pi-subagents permission rule: Watchdog permission decision was cancelled." };
|
|
308
350
|
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
309
351
|
let abort: (() => void) | undefined;
|
|
@@ -315,7 +357,7 @@ export function registerPermissionGate(
|
|
|
315
357
|
toolName,
|
|
316
358
|
args: event.input ?? {},
|
|
317
359
|
rawWatchdogConfig,
|
|
318
|
-
auditPath:
|
|
360
|
+
auditPath: permissions.auditPath,
|
|
319
361
|
...(ctx.signal ? { signal: ctx.signal } : {}),
|
|
320
362
|
}),
|
|
321
363
|
new Promise<WatchdogPermissionResult>((resolve) => {
|
|
@@ -359,245 +401,51 @@ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undef
|
|
|
359
401
|
});
|
|
360
402
|
}
|
|
361
403
|
|
|
362
|
-
|
|
363
|
-
|
|
364
|
-
|
|
365
|
-
|
|
366
|
-
|
|
367
|
-
|
|
368
|
-
|
|
369
|
-
|
|
370
|
-
|
|
371
|
-
}
|
|
372
|
-
|
|
373
|
-
|
|
374
|
-
|
|
375
|
-
|
|
376
|
-
|
|
377
|
-
|
|
378
|
-
|
|
379
|
-
|
|
380
|
-
|
|
381
|
-
let disposed = false;
|
|
382
|
-
let agentRunning = false;
|
|
383
|
-
let inTurn = false;
|
|
384
|
-
let awaitingSettlement = false;
|
|
385
|
-
let flushing = false;
|
|
386
|
-
let started = false;
|
|
387
|
-
let canSteer = typeof sendUserMessage === "function";
|
|
388
|
-
let watcher: fs.FSWatcher | undefined;
|
|
389
|
-
let interval: NodeJS.Timeout | undefined;
|
|
390
|
-
let safetyInterval: NodeJS.Timeout | undefined;
|
|
391
|
-
let settleFallback: NodeJS.Timeout | undefined;
|
|
392
|
-
const legacySettleFallbackMs = deps.legacySettleFallbackMs ?? STEERING_LEGACY_SETTLE_FALLBACK_MS;
|
|
393
|
-
const acknowledge = (request: SteerRequest, state: "delivered" | "queued" | "failed", message: string, deliveryStatus?: SteerDeliveryStatus): void => {
|
|
394
|
-
if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;
|
|
395
|
-
writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {
|
|
396
|
-
requestId: request.id,
|
|
397
|
-
index: childIndex,
|
|
398
|
-
ts: Date.now(),
|
|
399
|
-
state,
|
|
400
|
-
...(deliveryStatus ? { deliveryStatus } : {}),
|
|
401
|
-
message,
|
|
402
|
-
});
|
|
403
|
-
};
|
|
404
|
-
const publishCapability = (): void => {
|
|
405
|
-
if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;
|
|
406
|
-
writeSteerCapabilityAt(capabilityPath, { index: childIndex, pid: process.pid, readyAt: Date.now(), supported: canSteer });
|
|
407
|
-
};
|
|
408
|
-
const flush = (): void => {
|
|
409
|
-
if (disposed || flushing) return;
|
|
410
|
-
flushing = true;
|
|
411
|
-
try {
|
|
412
|
-
const requests = consumeSteerRequestsFromDir(steerInbox);
|
|
413
|
-
for (let index = 0; index < requests.length; index++) {
|
|
414
|
-
const request = requests[index]!;
|
|
415
|
-
if (!canSteer || typeof sendUserMessage !== "function") {
|
|
416
|
-
acknowledge(request, "failed", "Child Pi session does not support sendUserMessage steering.");
|
|
417
|
-
continue;
|
|
418
|
-
}
|
|
419
|
-
const requestedMode = request.mode ?? "steer";
|
|
420
|
-
const autoCanUseIdle = requestedMode === "auto" && !agentRunning && !awaitingSettlement;
|
|
421
|
-
const delivery = requestedMode === "follow_up" || (requestedMode === "auto" && (inTurn || awaitingSettlement)) ? "followUp" as const : "steer" as const;
|
|
422
|
-
const pendingFollowUps = [...pending.values()].reduce((count, entries) => count + entries.filter((entry) => entry.deliveryStatus === "queued").length, 0);
|
|
423
|
-
if (delivery === "followUp" && queued.length + pendingFollowUps >= MAX_STEER_QUEUE_SIZE) {
|
|
424
|
-
acknowledge(request, "failed", `Follow-up queue is full (${MAX_STEER_QUEUE_SIZE} messages).`);
|
|
425
|
-
continue;
|
|
426
|
-
}
|
|
427
|
-
const formatted = formatSteerMessage(request);
|
|
428
|
-
const entries = pending.get(formatted) ?? [];
|
|
429
|
-
entries.push({ request, deliveryStatus: delivery === "followUp" ? "queued" : "delivered" });
|
|
430
|
-
pending.set(formatted, entries);
|
|
431
|
-
try {
|
|
432
|
-
sendUserMessage(formatted, autoCanUseIdle ? undefined : { deliverAs: delivery });
|
|
433
|
-
} catch (error) {
|
|
434
|
-
entries.pop();
|
|
435
|
-
if (entries.length === 0) pending.delete(formatted);
|
|
436
|
-
acknowledge(request, "failed", error instanceof Error ? error.message : String(error));
|
|
437
|
-
for (const retry of requests.slice(index + 1)) writeSteerRequestToDir(steerInbox, retry);
|
|
438
|
-
break;
|
|
439
|
-
}
|
|
404
|
+
function registerStructuredOutputTool(pi: ExtensionAPI, structured: NonNullable<ChildRuntimeConfig["structuredOutput"]>): void {
|
|
405
|
+
const required = structured.acceptanceReport === "required";
|
|
406
|
+
const parameters = createStructuredOutputToolParameters(structured.schema, { acceptanceReport: structured.acceptanceReport });
|
|
407
|
+
const registerTool = pi.registerTool as unknown as (tool: {
|
|
408
|
+
name: string;
|
|
409
|
+
label: string;
|
|
410
|
+
description: string;
|
|
411
|
+
parameters: unknown;
|
|
412
|
+
execute: (_id: string, params: { value: unknown; acceptanceReport?: unknown }) => Promise<unknown>;
|
|
413
|
+
}) => void;
|
|
414
|
+
registerTool({
|
|
415
|
+
name: "structured_output",
|
|
416
|
+
label: "Structured Output",
|
|
417
|
+
description: "Submit the required final structured output for this subagent step. This terminates the step.",
|
|
418
|
+
parameters,
|
|
419
|
+
async execute(_id: string, params: { value: unknown; acceptanceReport?: unknown }) {
|
|
420
|
+
const validation = await validateStructuredOutputValue(structured.schema, params.value);
|
|
421
|
+
if (validation.status === "invalid") {
|
|
422
|
+
throw new Error(`Structured output validation failed: ${validation.message}`);
|
|
440
423
|
}
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
}
|
|
444
|
-
};
|
|
445
|
-
const onInput = (event: unknown): undefined => {
|
|
446
|
-
if (disposed || !event || typeof event !== "object") return undefined;
|
|
447
|
-
const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };
|
|
448
|
-
if (input.source !== "extension") return undefined;
|
|
449
|
-
const text = typeof input.text === "string" ? input.text : typeof input.content === "string" ? input.content : undefined;
|
|
450
|
-
if (!text) return undefined;
|
|
451
|
-
const entries = pending.get(text);
|
|
452
|
-
const entry = entries?.shift();
|
|
453
|
-
if (!entry) return undefined;
|
|
454
|
-
if (entries?.length === 0) pending.delete(text);
|
|
455
|
-
if (entry.deliveryStatus === "queued") {
|
|
456
|
-
queued.push({ request: entry.request, ready: !inTurn });
|
|
457
|
-
acknowledge(entry.request, "queued", "Pi queued the correlated follow-up input.", "queued");
|
|
458
|
-
} else {
|
|
459
|
-
acknowledge(entry.request, "delivered", "Pi accepted the correlated steering input.", "delivered");
|
|
460
|
-
}
|
|
461
|
-
return undefined;
|
|
462
|
-
};
|
|
463
|
-
const start = (): void => {
|
|
464
|
-
if (started || disposed) return;
|
|
465
|
-
try {
|
|
466
|
-
fs.mkdirSync(steerInbox, { recursive: true });
|
|
467
|
-
publishCapability();
|
|
468
|
-
} catch {
|
|
469
|
-
return;
|
|
470
|
-
}
|
|
471
|
-
started = true;
|
|
472
|
-
const startPolling = (): void => {
|
|
473
|
-
if (interval || disposed) return;
|
|
474
|
-
interval = (deps.timers?.setInterval ?? setInterval)(flush, 250) as NodeJS.Timeout;
|
|
475
|
-
interval.unref?.();
|
|
476
|
-
};
|
|
477
|
-
const startSafetyPolling = (): void => {
|
|
478
|
-
if (safetyInterval || disposed) return;
|
|
479
|
-
safetyInterval = (deps.timers?.setInterval ?? setInterval)(flush, deps.safetyPollIntervalMs ?? STEERING_SAFETY_POLL_INTERVAL_MS) as NodeJS.Timeout;
|
|
480
|
-
safetyInterval.unref?.();
|
|
481
|
-
};
|
|
482
|
-
if (!shouldUseNativeFsWatch("child-steering-inbox", deps.platform)) {
|
|
483
|
-
startPolling();
|
|
484
|
-
} else {
|
|
485
|
-
try {
|
|
486
|
-
watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());
|
|
487
|
-
watcher.on("error", startPolling);
|
|
488
|
-
startSafetyPolling();
|
|
489
|
-
} catch {
|
|
490
|
-
watcher = undefined;
|
|
491
|
-
startPolling();
|
|
424
|
+
if (required && params.acceptanceReport === undefined) {
|
|
425
|
+
throw new Error(MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR);
|
|
492
426
|
}
|
|
493
|
-
|
|
494
|
-
|
|
495
|
-
|
|
496
|
-
|
|
497
|
-
|
|
498
|
-
return undefined;
|
|
499
|
-
};
|
|
500
|
-
const clearSettleFallback = (): void => {
|
|
501
|
-
if (!settleFallback) return;
|
|
502
|
-
clearTimeout(settleFallback);
|
|
503
|
-
settleFallback = undefined;
|
|
504
|
-
};
|
|
505
|
-
const markSettled = (): undefined => {
|
|
506
|
-
clearSettleFallback();
|
|
507
|
-
agentRunning = false;
|
|
508
|
-
inTurn = false;
|
|
509
|
-
awaitingSettlement = false;
|
|
510
|
-
return activate();
|
|
511
|
-
};
|
|
512
|
-
const armLegacySettleFallback = (): void => {
|
|
513
|
-
clearSettleFallback();
|
|
514
|
-
settleFallback = setTimeout(() => {
|
|
515
|
-
settleFallback = undefined;
|
|
516
|
-
if (disposed || !awaitingSettlement) return;
|
|
517
|
-
agentRunning = false;
|
|
518
|
-
inTurn = false;
|
|
519
|
-
awaitingSettlement = false;
|
|
520
|
-
activate();
|
|
521
|
-
}, legacySettleFallbackMs);
|
|
522
|
-
settleFallback.unref?.();
|
|
523
|
-
};
|
|
524
|
-
|
|
525
|
-
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: unknown) => unknown) => void;
|
|
526
|
-
// Register input before the watcher so an accepted extension input cannot race request dispatch.
|
|
527
|
-
onRuntimeEvent("input", onInput);
|
|
528
|
-
onRuntimeEvent("session_start", () => start());
|
|
529
|
-
onRuntimeEvent("agent_start", () => {
|
|
530
|
-
clearSettleFallback();
|
|
531
|
-
agentRunning = true;
|
|
532
|
-
awaitingSettlement = false;
|
|
533
|
-
return activate();
|
|
534
|
-
});
|
|
535
|
-
onRuntimeEvent("agent_end", (event) => {
|
|
536
|
-
inTurn = false;
|
|
537
|
-
if ((event as { willRetry?: unknown } | undefined)?.willRetry === true) {
|
|
538
|
-
clearSettleFallback();
|
|
539
|
-
agentRunning = true;
|
|
540
|
-
awaitingSettlement = true;
|
|
541
|
-
return activate();
|
|
542
|
-
}
|
|
543
|
-
agentRunning = true;
|
|
544
|
-
awaitingSettlement = true;
|
|
545
|
-
armLegacySettleFallback();
|
|
546
|
-
return activate();
|
|
547
|
-
});
|
|
548
|
-
onRuntimeEvent("agent_settled", markSettled);
|
|
549
|
-
onRuntimeEvent("session_compact", () => {
|
|
550
|
-
const unresolved = [...pending.values()].flat();
|
|
551
|
-
pending.clear();
|
|
552
|
-
for (const entry of unresolved) {
|
|
553
|
-
try {
|
|
554
|
-
writeSteerRequestToDir(steerInbox, { ...entry.request, mode: "follow_up" });
|
|
555
|
-
} catch (error) {
|
|
556
|
-
acknowledge(entry.request, "failed", `Could not retry steering after compaction: ${error instanceof Error ? error.message : String(error)}`);
|
|
427
|
+
if (required && params.acceptanceReport !== undefined) {
|
|
428
|
+
const acceptanceValidation = validateAcceptanceReport(params.acceptanceReport, "acceptanceReport");
|
|
429
|
+
if (!acceptanceValidation.report) {
|
|
430
|
+
throw new Error(`Invalid structured output acceptance report: ${acceptanceValidation.errors.join("; ")}`);
|
|
431
|
+
}
|
|
557
432
|
}
|
|
558
|
-
|
|
559
|
-
|
|
560
|
-
|
|
561
|
-
|
|
562
|
-
|
|
563
|
-
|
|
564
|
-
|
|
565
|
-
inTurn = true;
|
|
566
|
-
const next = queued.findIndex((entry) => entry.ready);
|
|
567
|
-
if (next >= 0) {
|
|
568
|
-
const [entry] = queued.splice(next, 1);
|
|
569
|
-
if (entry) acknowledge(entry.request, "delivered", "Pi delivered the queued follow-up at a turn boundary.", "delivered");
|
|
570
|
-
}
|
|
571
|
-
return activate();
|
|
572
|
-
});
|
|
573
|
-
onRuntimeEvent("turn_end", () => {
|
|
574
|
-
inTurn = false;
|
|
575
|
-
for (const entry of queued) entry.ready = true;
|
|
576
|
-
return activate();
|
|
577
|
-
});
|
|
578
|
-
for (const eventName of ["message_start", "message_update", "message_end", "tool_execution_start", "tool_execution_end"] as const) {
|
|
579
|
-
onRuntimeEvent(eventName, activate);
|
|
580
|
-
}
|
|
581
|
-
onRuntimeEvent("session_shutdown", () => {
|
|
582
|
-
for (const entry of queued) acknowledge(entry.request, "failed", "Run ended before queued follow-up delivery.", "queued");
|
|
583
|
-
for (const entries of pending.values()) {
|
|
584
|
-
for (const entry of entries) acknowledge(entry.request, "failed", "Run ended before Pi confirmed steering input delivery.");
|
|
585
|
-
}
|
|
586
|
-
disposed = true;
|
|
587
|
-
clearSettleFallback();
|
|
588
|
-
try { watcher?.close(); } catch {}
|
|
589
|
-
if (interval) (deps.timers?.clearInterval ?? clearInterval)(interval);
|
|
590
|
-
if (safetyInterval) (deps.timers?.clearInterval ?? clearInterval)(safetyInterval);
|
|
433
|
+
structured.capture(params.value, structured.acceptanceReport ? params.acceptanceReport : undefined);
|
|
434
|
+
return {
|
|
435
|
+
content: [{ type: "text", text: "Structured output captured." }],
|
|
436
|
+
details: {},
|
|
437
|
+
terminate: true,
|
|
438
|
+
};
|
|
439
|
+
},
|
|
591
440
|
});
|
|
592
441
|
}
|
|
593
442
|
|
|
594
|
-
|
|
595
|
-
|
|
596
|
-
|
|
597
|
-
registerPermissionGate(pi);
|
|
598
|
-
registerToolBudget(pi,
|
|
599
|
-
registerChildWatchdog(pi);
|
|
600
|
-
const waitToolEnabled = resolveWaitToolConfig().enabled;
|
|
443
|
+
/** Register every child-side hook the prompt runtime owns for one child session. */
|
|
444
|
+
export default function registerSubagentPromptRuntime(pi: ExtensionAPI, config: ChildRuntimeConfig): void {
|
|
445
|
+
registerRuntimeExtensionAcknowledgements(pi, config.runtimeAcknowledgements);
|
|
446
|
+
registerPermissionGate(pi, config.permissions, config.childWatchdog);
|
|
447
|
+
registerToolBudget(pi, config.toolBudget);
|
|
448
|
+
registerChildWatchdog(pi, config.childWatchdog, config.watchdogStatus);
|
|
601
449
|
const waitState = {
|
|
602
450
|
baseCwd: "",
|
|
603
451
|
currentSessionId: null,
|
|
@@ -612,12 +460,13 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
612
460
|
watcherRestartTimer: null,
|
|
613
461
|
resultFileCoalescer: { schedule: () => false, clear: () => {} },
|
|
614
462
|
} as unknown as SubagentState;
|
|
615
|
-
if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState,
|
|
463
|
+
if (typeof pi.registerTool === "function") registerWaitTool(pi, waitState, config.waitTool.enabled, undefined, config.waitTool.defaultTimeoutMs);
|
|
464
|
+
const supervisorMetadata = childSupervisorMetadata(config);
|
|
616
465
|
let nativeSupervisorClientRegistered = false;
|
|
617
466
|
const registerNativeSupervisorClientOnce = (): void => {
|
|
618
467
|
if (nativeSupervisorClientRegistered) return;
|
|
619
468
|
nativeSupervisorClientRegistered = true;
|
|
620
|
-
registerNativeSupervisorClient(pi);
|
|
469
|
+
registerNativeSupervisorClient(pi, supervisorMetadata);
|
|
621
470
|
};
|
|
622
471
|
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: ExtensionContext) => unknown) => void;
|
|
623
472
|
onRuntimeEvent("session_start", (_event: unknown, ctx?: ExtensionContext) => {
|
|
@@ -626,54 +475,24 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
626
475
|
registerNativeSupervisorClientOnce();
|
|
627
476
|
});
|
|
628
477
|
onRuntimeEvent("agent_start", () => {
|
|
629
|
-
|
|
478
|
+
if (!config.requiredTools) return;
|
|
479
|
+
const diagnostic = evaluateChildToolDiagnostic(config, pi.getAllTools().map((tool) => tool.name));
|
|
480
|
+
config.toolDiagnostic?.(diagnostic);
|
|
630
481
|
if (diagnostic) throw new Error(formatChildToolDiagnostic(diagnostic));
|
|
631
482
|
});
|
|
632
483
|
onRuntimeEvent("agent_end", async (_event: unknown, ctx: unknown) => {
|
|
633
484
|
if ((ctx as { hasUI?: boolean } | undefined)?.hasUI === true) return;
|
|
634
485
|
await drainOutstandingWork({ state: waitState, events: pi.events });
|
|
635
486
|
});
|
|
636
|
-
|
|
637
|
-
|
|
638
|
-
|
|
639
|
-
if (structuredOutputPath && structuredSchemaPath) {
|
|
640
|
-
const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, "utf-8")) as JsonSchemaObject;
|
|
641
|
-
const parameters = createStructuredOutputToolParameters(schema, { acceptanceReport: Boolean(structuredAcceptanceReportPath) });
|
|
642
|
-
const registerTool = pi.registerTool as unknown as (tool: {
|
|
643
|
-
name: string;
|
|
644
|
-
label: string;
|
|
645
|
-
description: string;
|
|
646
|
-
parameters: unknown;
|
|
647
|
-
execute: (_id: string, params: { value: unknown; acceptanceReport?: unknown }) => Promise<unknown>;
|
|
648
|
-
}) => void;
|
|
649
|
-
registerTool({
|
|
650
|
-
name: "structured_output",
|
|
651
|
-
label: "Structured Output",
|
|
652
|
-
description: "Submit the required final structured output for this subagent step. This terminates the step.",
|
|
653
|
-
parameters,
|
|
654
|
-
async execute(_id: string, params: { value: unknown; acceptanceReport?: unknown }) {
|
|
655
|
-
const validation = await validateStructuredOutputValue(schema, params.value);
|
|
656
|
-
if (validation.status === "invalid") {
|
|
657
|
-
throw new Error(`Structured output validation failed: ${validation.message}`);
|
|
658
|
-
}
|
|
659
|
-
fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });
|
|
660
|
-
fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });
|
|
661
|
-
if (structuredAcceptanceReportPath && params.acceptanceReport !== undefined) {
|
|
662
|
-
fs.writeFileSync(structuredAcceptanceReportPath, JSON.stringify(params.acceptanceReport), { mode: 0o600 });
|
|
663
|
-
}
|
|
664
|
-
return {
|
|
665
|
-
content: [{ type: "text", text: "Structured output captured." }],
|
|
666
|
-
details: { path: structuredOutputPath },
|
|
667
|
-
terminate: true,
|
|
668
|
-
};
|
|
669
|
-
},
|
|
670
|
-
});
|
|
671
|
-
}
|
|
487
|
+
if (config.structuredOutput) registerStructuredOutputTool(pi, config.structuredOutput);
|
|
488
|
+
|
|
489
|
+
onRuntimeEvent("before_provider_request", (event: unknown, ctx?: ExtensionContext) => rewriteForkCacheProviderRequest(event as BeforeProviderRequestEvent, ctx, config.forkCacheKey));
|
|
672
490
|
|
|
673
491
|
onRuntimeEvent("context", (event: unknown, ctx?: ExtensionContext) => {
|
|
674
492
|
if (!event || typeof event !== "object" || !("messages" in event) || !Array.isArray(event.messages)) return undefined;
|
|
675
493
|
const messages = stripParentOnlySubagentMessages(event.messages, {
|
|
676
494
|
sanitizeToolIds: !COMPOSITE_TOOL_ID_APIS.has(ctx?.model?.api ?? ""),
|
|
495
|
+
preserveFanoutToolHistory: config.fanoutChild,
|
|
677
496
|
});
|
|
678
497
|
if (messages === event.messages) return undefined;
|
|
679
498
|
return { messages };
|
|
@@ -682,20 +501,24 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
682
501
|
onRuntimeEvent("before_agent_start", async (event: unknown) => {
|
|
683
502
|
if (!event || typeof event !== "object" || !("systemPrompt" in event) || typeof event.systemPrompt !== "string") return undefined;
|
|
684
503
|
registerNativeSupervisorClientOnce();
|
|
685
|
-
|
|
686
|
-
|
|
687
|
-
|
|
504
|
+
// The intercom target is a routing address and always wins; the display
|
|
505
|
+
// name (agent + task excerpt, computed by the parent at launch) only
|
|
506
|
+
// applies when the bridge is not addressing this child.
|
|
507
|
+
const childSessionName = config.intercomSessionName || config.sessionName;
|
|
508
|
+
if (childSessionName && typeof pi.setSessionName === "function") {
|
|
509
|
+
pi.setSessionName(childSessionName);
|
|
688
510
|
}
|
|
689
511
|
|
|
690
|
-
const inheritProjectContext =
|
|
691
|
-
const
|
|
692
|
-
const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);
|
|
512
|
+
const { inheritProjectContext, inheritGlobalContext, inheritSkills } = config;
|
|
513
|
+
const fanoutChild = config.fanoutChild;
|
|
693
514
|
let rewritten = event.systemPrompt;
|
|
694
|
-
if (inheritProjectContext !== undefined ||
|
|
515
|
+
if (inheritProjectContext !== undefined || inheritGlobalContext !== undefined || inheritSkills !== undefined || fanoutChild) {
|
|
695
516
|
rewritten = rewriteSubagentPrompt(event.systemPrompt, {
|
|
696
517
|
inheritProjectContext: inheritProjectContext ?? true,
|
|
518
|
+
inheritGlobalContext: inheritGlobalContext ?? true,
|
|
697
519
|
inheritSkills: inheritSkills ?? true,
|
|
698
|
-
fanoutChild
|
|
520
|
+
fanoutChild,
|
|
521
|
+
structuredOutput: Boolean(config.structuredOutput),
|
|
699
522
|
});
|
|
700
523
|
}
|
|
701
524
|
if (rewritten === event.systemPrompt) return;
|