@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
|
@@ -1,38 +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
|
-
MCP_DIRECT_CHILD_TOOLS_ENV,
|
|
15
|
-
REQUIRED_CHILD_TOOLS_ENV,
|
|
16
|
-
writeChildToolDiagnostic,
|
|
17
|
-
type ChildToolDiagnostic,
|
|
18
|
-
} from "./tool-availability.ts";
|
|
19
|
-
import { TOOL_BUDGET_ENV, TOOL_BUDGET_ZERO_AUTH_ENV, decodeToolBudgetEnv, shouldBlockToolForBudget, toolBudgetBlockedMessage, toolBudgetSoftNudge } from "./tool-budget.ts";
|
|
20
|
-
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";
|
|
21
14
|
import { resolveCurrentSessionId } from "../../shared/session-identity.ts";
|
|
22
|
-
import {
|
|
15
|
+
import { getAgentDir } from "../../shared/utils.ts";
|
|
23
16
|
import { registerChildWatchdog } from "../../watchdog/register-child.ts";
|
|
24
|
-
import {
|
|
17
|
+
import type { ChildWatchdogConfig } from "../../watchdog/child-status.ts";
|
|
25
18
|
import { requestWatchdogPermission, type WatchdogPermissionRequest, type WatchdogPermissionResult } from "../../watchdog/permission-arbiter.ts";
|
|
26
19
|
import { SUBAGENT_WATCHDOG_WARNING_TYPE } from "../../watchdog/types.ts";
|
|
27
|
-
import { resolveWaitToolConfig } from "../background/wait-config.ts";
|
|
28
20
|
import { registerWaitTool } from "../background/wait-tool.ts";
|
|
29
21
|
import { drainOutstandingWork } from "../background/auto-drain.ts";
|
|
30
|
-
|
|
31
|
-
|
|
32
|
-
|
|
33
|
-
|
|
34
|
-
|
|
35
|
-
|
|
22
|
+
import {
|
|
23
|
+
childSupervisorMetadata,
|
|
24
|
+
evaluateChildToolDiagnostic,
|
|
25
|
+
type ChildPermissions,
|
|
26
|
+
type ChildRuntimeConfig,
|
|
27
|
+
} from "./child-runtime-config.ts";
|
|
36
28
|
|
|
37
29
|
const STRUCTURED_OUTPUT_INSTRUCTIONS = [
|
|
38
30
|
"This subagent step has a strict structured output contract.",
|
|
@@ -67,49 +59,13 @@ const PARENT_ONLY_CUSTOM_MESSAGE_TYPES = new Set([
|
|
|
67
59
|
"subagent-control-notice",
|
|
68
60
|
]);
|
|
69
61
|
const SUBAGENT_ORCHESTRATION_SKILL_NAME_PATTERN = /<name>\s*pi-subagents\s*<\/name>/;
|
|
70
|
-
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";
|
|
71
64
|
const SKILLS_HEADER = "\n\nThe following skills provide specialized instructions for specific tasks.";
|
|
72
65
|
const DATE_HEADER = "\nCurrent date:";
|
|
73
66
|
|
|
74
|
-
function
|
|
75
|
-
|
|
76
|
-
if (value === undefined) return undefined;
|
|
77
|
-
return value !== "0";
|
|
78
|
-
}
|
|
79
|
-
|
|
80
|
-
function readRequiredChildTools(): string[] | undefined {
|
|
81
|
-
const encoded = process.env[REQUIRED_CHILD_TOOLS_ENV]?.trim();
|
|
82
|
-
if (!encoded) return undefined;
|
|
83
|
-
const required = JSON.parse(encoded) as unknown;
|
|
84
|
-
if (!Array.isArray(required) || required.some((name) => typeof name !== "string" || !name)) {
|
|
85
|
-
throw new Error(`Invalid ${REQUIRED_CHILD_TOOLS_ENV} payload.`);
|
|
86
|
-
}
|
|
87
|
-
return required;
|
|
88
|
-
}
|
|
89
|
-
|
|
90
|
-
function readMcpDirectChildTools(): string[] | undefined {
|
|
91
|
-
const encoded = process.env[MCP_DIRECT_CHILD_TOOLS_ENV]?.trim();
|
|
92
|
-
if (!encoded) return undefined;
|
|
93
|
-
try {
|
|
94
|
-
const tools = JSON.parse(encoded) as unknown;
|
|
95
|
-
if (!Array.isArray(tools) || tools.some((name) => typeof name !== "string" || !name)) return undefined;
|
|
96
|
-
return tools;
|
|
97
|
-
} catch {
|
|
98
|
-
return undefined;
|
|
99
|
-
}
|
|
100
|
-
}
|
|
101
|
-
|
|
102
|
-
function refreshChildToolDiagnostic(pi: ExtensionAPI): ChildToolDiagnostic | undefined {
|
|
103
|
-
const filePath = process.env[CHILD_TOOL_DIAGNOSTIC_PATH_ENV]?.trim();
|
|
104
|
-
const required = readRequiredChildTools();
|
|
105
|
-
if (!filePath || !required) return undefined;
|
|
106
|
-
const available = pi.getAllTools().map((tool) => tool.name);
|
|
107
|
-
return writeChildToolDiagnostic(filePath, required, available, process.env[SUBAGENT_CHILD_AGENT_ENV]?.trim(), readMcpDirectChildTools());
|
|
108
|
-
}
|
|
109
|
-
|
|
110
|
-
function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI): void {
|
|
111
|
-
const outputPath = process.env[RUNTIME_EXTENSION_ACK_PATH_ENV]?.trim();
|
|
112
|
-
if (!outputPath) return;
|
|
67
|
+
function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI, sink: ((ids: string[]) => void) | undefined): void {
|
|
68
|
+
if (!sink) return;
|
|
113
69
|
const ids: string[] = [];
|
|
114
70
|
let finalized = false;
|
|
115
71
|
const acknowledge = (payload: unknown): undefined => {
|
|
@@ -121,7 +77,7 @@ function registerRuntimeExtensionAcknowledgements(pi: ExtensionAPI): void {
|
|
|
121
77
|
const finalize = (): undefined => {
|
|
122
78
|
if (finalized) return undefined;
|
|
123
79
|
finalized = true;
|
|
124
|
-
|
|
80
|
+
sink(ids);
|
|
125
81
|
return undefined;
|
|
126
82
|
};
|
|
127
83
|
try {
|
|
@@ -147,10 +103,80 @@ function findSectionEnd(prompt: string, startIndex: number, nextHeaders: string[
|
|
|
147
103
|
}
|
|
148
104
|
|
|
149
105
|
export function stripProjectContext(prompt: string): string {
|
|
150
|
-
const
|
|
151
|
-
if (
|
|
152
|
-
|
|
153
|
-
|
|
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)}`;
|
|
154
180
|
}
|
|
155
181
|
|
|
156
182
|
export function stripInheritedSkills(prompt: string): string {
|
|
@@ -176,19 +202,22 @@ function stripChildBoundaryInstructions(prompt: string): string {
|
|
|
176
202
|
|
|
177
203
|
export function rewriteSubagentPrompt(
|
|
178
204
|
prompt: string,
|
|
179
|
-
options: { inheritProjectContext: boolean; inheritSkills: boolean; fanoutChild?: boolean },
|
|
205
|
+
options: { inheritProjectContext: boolean; inheritGlobalContext: boolean; inheritSkills: boolean; fanoutChild?: boolean; structuredOutput?: boolean },
|
|
180
206
|
): string {
|
|
181
207
|
let rewritten = prompt;
|
|
182
208
|
if (!options.inheritProjectContext) {
|
|
183
209
|
rewritten = stripProjectContext(rewritten);
|
|
184
210
|
}
|
|
211
|
+
if (!options.inheritGlobalContext) {
|
|
212
|
+
rewritten = stripGlobalContext(rewritten);
|
|
213
|
+
}
|
|
185
214
|
if (!options.inheritSkills) {
|
|
186
215
|
rewritten = stripInheritedSkills(rewritten);
|
|
187
216
|
}
|
|
188
217
|
rewritten = stripSubagentOrchestrationSkill(rewritten);
|
|
189
218
|
rewritten = stripChildBoundaryInstructions(rewritten);
|
|
190
219
|
const boundary = options.fanoutChild ? CHILD_FANOUT_BOUNDARY_INSTRUCTIONS : CHILD_SUBAGENT_BOUNDARY_INSTRUCTIONS;
|
|
191
|
-
const structured =
|
|
220
|
+
const structured = options.structuredOutput ? `\n\n${STRUCTURED_OUTPUT_INSTRUCTIONS}` : "";
|
|
192
221
|
return `${boundary}${structured}\n\n${rewritten}`;
|
|
193
222
|
}
|
|
194
223
|
|
|
@@ -213,10 +242,27 @@ const PORTABLE_TOOL_ID_PATTERN = /^[a-zA-Z0-9_-]+$/;
|
|
|
213
242
|
const MAX_PORTABLE_TOOL_ID_LENGTH = 64;
|
|
214
243
|
const COMPOSITE_TOOL_ID_APIS = new Set([
|
|
215
244
|
"azure-openai-responses",
|
|
245
|
+
"cursor-native",
|
|
246
|
+
"openai-completions",
|
|
247
|
+
"openai-responses",
|
|
248
|
+
]);
|
|
249
|
+
const PROMPT_CACHE_KEY_APIS = new Set([
|
|
250
|
+
"azure-openai-responses",
|
|
251
|
+
"openai-codex-responses",
|
|
216
252
|
"openai-completions",
|
|
217
253
|
"openai-responses",
|
|
218
254
|
]);
|
|
219
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
|
+
}
|
|
265
|
+
|
|
220
266
|
function portableToolId(id: string): string {
|
|
221
267
|
if (PORTABLE_TOOL_ID_PATTERN.test(id) && id.length <= MAX_PORTABLE_TOOL_ID_LENGTH) return id;
|
|
222
268
|
const encoded = `tool_${Buffer.from(id).toString("base64url") || "empty"}`;
|
|
@@ -252,8 +298,8 @@ function stripAssistantSubagentToolCallBlocks(message: unknown): unknown | undef
|
|
|
252
298
|
return { ...m, content: filteredContent };
|
|
253
299
|
}
|
|
254
300
|
|
|
255
|
-
export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean } = {}): unknown[] {
|
|
256
|
-
const preserveCurrentFanoutToolHistory =
|
|
301
|
+
export function stripParentOnlySubagentMessages(messages: unknown[], options: { sanitizeToolIds?: boolean; preserveFanoutToolHistory?: boolean } = {}): unknown[] {
|
|
302
|
+
const preserveCurrentFanoutToolHistory = options.preserveFanoutToolHistory === true;
|
|
257
303
|
const sanitizeToolIds = options.sanitizeToolIds ?? true;
|
|
258
304
|
let changed = false;
|
|
259
305
|
const filtered: unknown[] = [];
|
|
@@ -286,24 +332,48 @@ export function formatSteerMessage(request: SteerRequest): string {
|
|
|
286
332
|
|
|
287
333
|
export function registerPermissionGate(
|
|
288
334
|
pi: ExtensionAPI,
|
|
335
|
+
permissions: ChildPermissions | undefined,
|
|
336
|
+
childWatchdog: ChildWatchdogConfig | undefined,
|
|
289
337
|
requestPermission: (request: WatchdogPermissionRequest) => Promise<WatchdogPermissionResult> = requestWatchdogPermission,
|
|
290
338
|
): void {
|
|
291
|
-
const rules =
|
|
292
|
-
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;
|
|
293
343
|
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: { toolName?: string; input?: unknown }, ctx: ExtensionContext) => unknown) => void;
|
|
294
344
|
onRuntimeEvent("tool_call", async (event, ctx) => {
|
|
295
345
|
const toolName = typeof event.toolName === "string" ? event.toolName : "tool";
|
|
296
346
|
const decision = permissionDecision(rules, toolName);
|
|
297
347
|
if (decision === "allow") return undefined;
|
|
298
348
|
if (decision === "deny") return { block: true, reason: `Blocked by pi-subagents permission rule: '${toolName}' is denied.` };
|
|
299
|
-
|
|
300
|
-
|
|
301
|
-
|
|
302
|
-
|
|
303
|
-
|
|
304
|
-
|
|
305
|
-
|
|
306
|
-
|
|
349
|
+
if (ctx.signal?.aborted) return { block: true, reason: "Blocked by pi-subagents permission rule: Watchdog permission decision was cancelled." };
|
|
350
|
+
let timeout: ReturnType<typeof setTimeout> | undefined;
|
|
351
|
+
let abort: (() => void) | undefined;
|
|
352
|
+
let result: WatchdogPermissionResult;
|
|
353
|
+
try {
|
|
354
|
+
result = await Promise.race([
|
|
355
|
+
requestPermission({
|
|
356
|
+
ctx,
|
|
357
|
+
toolName,
|
|
358
|
+
args: event.input ?? {},
|
|
359
|
+
rawWatchdogConfig,
|
|
360
|
+
auditPath: permissions.auditPath,
|
|
361
|
+
...(ctx.signal ? { signal: ctx.signal } : {}),
|
|
362
|
+
}),
|
|
363
|
+
new Promise<WatchdogPermissionResult>((resolve) => {
|
|
364
|
+
if (!ctx.signal) return;
|
|
365
|
+
abort = () => resolve({ approved: false, reason: "Watchdog permission decision was cancelled.", source: "watchdog" });
|
|
366
|
+
ctx.signal.addEventListener("abort", abort, { once: true });
|
|
367
|
+
}),
|
|
368
|
+
new Promise<never>((_, reject) => { timeout = setTimeout(() => reject(new Error(`Watchdog permission decision timed out after ${timeoutMs}ms.`)), timeoutMs); }),
|
|
369
|
+
]);
|
|
370
|
+
} catch (error) {
|
|
371
|
+
const reason = error instanceof Error ? error.message : String(error);
|
|
372
|
+
return { block: true, reason: `Blocked by pi-subagents permission rule: Watchdog permission arbiter failed closed: ${reason}` };
|
|
373
|
+
} finally {
|
|
374
|
+
if (timeout) clearTimeout(timeout);
|
|
375
|
+
if (abort) ctx.signal?.removeEventListener("abort", abort);
|
|
376
|
+
}
|
|
307
377
|
if (result.approved) return undefined;
|
|
308
378
|
return { block: true, reason: `Blocked by pi-subagents permission rule: ${result.reason}` };
|
|
309
379
|
});
|
|
@@ -331,245 +401,51 @@ function registerToolBudget(pi: ExtensionAPI, budget: ResolvedToolBudget | undef
|
|
|
331
401
|
});
|
|
332
402
|
}
|
|
333
403
|
|
|
334
|
-
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
|
|
339
|
-
|
|
340
|
-
|
|
341
|
-
|
|
342
|
-
|
|
343
|
-
}
|
|
344
|
-
|
|
345
|
-
|
|
346
|
-
|
|
347
|
-
|
|
348
|
-
|
|
349
|
-
|
|
350
|
-
|
|
351
|
-
|
|
352
|
-
|
|
353
|
-
let disposed = false;
|
|
354
|
-
let agentRunning = false;
|
|
355
|
-
let inTurn = false;
|
|
356
|
-
let awaitingSettlement = false;
|
|
357
|
-
let flushing = false;
|
|
358
|
-
let started = false;
|
|
359
|
-
let canSteer = typeof sendUserMessage === "function";
|
|
360
|
-
let watcher: fs.FSWatcher | undefined;
|
|
361
|
-
let interval: NodeJS.Timeout | undefined;
|
|
362
|
-
let safetyInterval: NodeJS.Timeout | undefined;
|
|
363
|
-
let settleFallback: NodeJS.Timeout | undefined;
|
|
364
|
-
const legacySettleFallbackMs = deps.legacySettleFallbackMs ?? STEERING_LEGACY_SETTLE_FALLBACK_MS;
|
|
365
|
-
const acknowledge = (request: SteerRequest, state: "delivered" | "queued" | "failed", message: string, deliveryStatus?: SteerDeliveryStatus): void => {
|
|
366
|
-
if (!ackDir || !Number.isInteger(childIndex) || childIndex < 0) return;
|
|
367
|
-
writeSteerAckAt(steerAckPathFromDir(ackDir, request.id), {
|
|
368
|
-
requestId: request.id,
|
|
369
|
-
index: childIndex,
|
|
370
|
-
ts: Date.now(),
|
|
371
|
-
state,
|
|
372
|
-
...(deliveryStatus ? { deliveryStatus } : {}),
|
|
373
|
-
message,
|
|
374
|
-
});
|
|
375
|
-
};
|
|
376
|
-
const publishCapability = (): void => {
|
|
377
|
-
if (!capabilityPath || !Number.isInteger(childIndex) || childIndex < 0) return;
|
|
378
|
-
writeSteerCapabilityAt(capabilityPath, { index: childIndex, pid: process.pid, readyAt: Date.now(), supported: canSteer });
|
|
379
|
-
};
|
|
380
|
-
const flush = (): void => {
|
|
381
|
-
if (disposed || flushing) return;
|
|
382
|
-
flushing = true;
|
|
383
|
-
try {
|
|
384
|
-
const requests = consumeSteerRequestsFromDir(steerInbox);
|
|
385
|
-
for (let index = 0; index < requests.length; index++) {
|
|
386
|
-
const request = requests[index]!;
|
|
387
|
-
if (!canSteer || typeof sendUserMessage !== "function") {
|
|
388
|
-
acknowledge(request, "failed", "Child Pi session does not support sendUserMessage steering.");
|
|
389
|
-
continue;
|
|
390
|
-
}
|
|
391
|
-
const requestedMode = request.mode ?? "steer";
|
|
392
|
-
const autoCanUseIdle = requestedMode === "auto" && !agentRunning && !awaitingSettlement;
|
|
393
|
-
const delivery = requestedMode === "follow_up" || (requestedMode === "auto" && (inTurn || awaitingSettlement)) ? "followUp" as const : "steer" as const;
|
|
394
|
-
const pendingFollowUps = [...pending.values()].reduce((count, entries) => count + entries.filter((entry) => entry.deliveryStatus === "queued").length, 0);
|
|
395
|
-
if (delivery === "followUp" && queued.length + pendingFollowUps >= MAX_STEER_QUEUE_SIZE) {
|
|
396
|
-
acknowledge(request, "failed", `Follow-up queue is full (${MAX_STEER_QUEUE_SIZE} messages).`);
|
|
397
|
-
continue;
|
|
398
|
-
}
|
|
399
|
-
const formatted = formatSteerMessage(request);
|
|
400
|
-
const entries = pending.get(formatted) ?? [];
|
|
401
|
-
entries.push({ request, deliveryStatus: delivery === "followUp" ? "queued" : "delivered" });
|
|
402
|
-
pending.set(formatted, entries);
|
|
403
|
-
try {
|
|
404
|
-
sendUserMessage(formatted, autoCanUseIdle ? undefined : { deliverAs: delivery });
|
|
405
|
-
} catch (error) {
|
|
406
|
-
entries.pop();
|
|
407
|
-
if (entries.length === 0) pending.delete(formatted);
|
|
408
|
-
acknowledge(request, "failed", error instanceof Error ? error.message : String(error));
|
|
409
|
-
for (const retry of requests.slice(index + 1)) writeSteerRequestToDir(steerInbox, retry);
|
|
410
|
-
break;
|
|
411
|
-
}
|
|
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}`);
|
|
412
423
|
}
|
|
413
|
-
|
|
414
|
-
|
|
415
|
-
}
|
|
416
|
-
};
|
|
417
|
-
const onInput = (event: unknown): undefined => {
|
|
418
|
-
if (disposed || !event || typeof event !== "object") return undefined;
|
|
419
|
-
const input = event as { source?: unknown; streamingBehavior?: unknown; text?: unknown; content?: unknown };
|
|
420
|
-
if (input.source !== "extension") return undefined;
|
|
421
|
-
const text = typeof input.text === "string" ? input.text : typeof input.content === "string" ? input.content : undefined;
|
|
422
|
-
if (!text) return undefined;
|
|
423
|
-
const entries = pending.get(text);
|
|
424
|
-
const entry = entries?.shift();
|
|
425
|
-
if (!entry) return undefined;
|
|
426
|
-
if (entries?.length === 0) pending.delete(text);
|
|
427
|
-
if (entry.deliveryStatus === "queued") {
|
|
428
|
-
queued.push({ request: entry.request, ready: !inTurn });
|
|
429
|
-
acknowledge(entry.request, "queued", "Pi queued the correlated follow-up input.", "queued");
|
|
430
|
-
} else {
|
|
431
|
-
acknowledge(entry.request, "delivered", "Pi accepted the correlated steering input.", "delivered");
|
|
432
|
-
}
|
|
433
|
-
return undefined;
|
|
434
|
-
};
|
|
435
|
-
const start = (): void => {
|
|
436
|
-
if (started || disposed) return;
|
|
437
|
-
try {
|
|
438
|
-
fs.mkdirSync(steerInbox, { recursive: true });
|
|
439
|
-
publishCapability();
|
|
440
|
-
} catch {
|
|
441
|
-
return;
|
|
442
|
-
}
|
|
443
|
-
started = true;
|
|
444
|
-
const startPolling = (): void => {
|
|
445
|
-
if (interval || disposed) return;
|
|
446
|
-
interval = (deps.timers?.setInterval ?? setInterval)(flush, 250) as NodeJS.Timeout;
|
|
447
|
-
interval.unref?.();
|
|
448
|
-
};
|
|
449
|
-
const startSafetyPolling = (): void => {
|
|
450
|
-
if (safetyInterval || disposed) return;
|
|
451
|
-
safetyInterval = (deps.timers?.setInterval ?? setInterval)(flush, deps.safetyPollIntervalMs ?? STEERING_SAFETY_POLL_INTERVAL_MS) as NodeJS.Timeout;
|
|
452
|
-
safetyInterval.unref?.();
|
|
453
|
-
};
|
|
454
|
-
if (!shouldUseNativeFsWatch("child-steering-inbox", deps.platform)) {
|
|
455
|
-
startPolling();
|
|
456
|
-
} else {
|
|
457
|
-
try {
|
|
458
|
-
watcher = (deps.watch ?? fs.watch)(resolveWatchPath(steerInbox, deps.nativeRealpath), () => flush());
|
|
459
|
-
watcher.on("error", startPolling);
|
|
460
|
-
startSafetyPolling();
|
|
461
|
-
} catch {
|
|
462
|
-
watcher = undefined;
|
|
463
|
-
startPolling();
|
|
424
|
+
if (required && params.acceptanceReport === undefined) {
|
|
425
|
+
throw new Error(MISSING_STRUCTURED_ACCEPTANCE_REPORT_ERROR);
|
|
464
426
|
}
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
return undefined;
|
|
471
|
-
};
|
|
472
|
-
const clearSettleFallback = (): void => {
|
|
473
|
-
if (!settleFallback) return;
|
|
474
|
-
clearTimeout(settleFallback);
|
|
475
|
-
settleFallback = undefined;
|
|
476
|
-
};
|
|
477
|
-
const markSettled = (): undefined => {
|
|
478
|
-
clearSettleFallback();
|
|
479
|
-
agentRunning = false;
|
|
480
|
-
inTurn = false;
|
|
481
|
-
awaitingSettlement = false;
|
|
482
|
-
return activate();
|
|
483
|
-
};
|
|
484
|
-
const armLegacySettleFallback = (): void => {
|
|
485
|
-
clearSettleFallback();
|
|
486
|
-
settleFallback = setTimeout(() => {
|
|
487
|
-
settleFallback = undefined;
|
|
488
|
-
if (disposed || !awaitingSettlement) return;
|
|
489
|
-
agentRunning = false;
|
|
490
|
-
inTurn = false;
|
|
491
|
-
awaitingSettlement = false;
|
|
492
|
-
activate();
|
|
493
|
-
}, legacySettleFallbackMs);
|
|
494
|
-
settleFallback.unref?.();
|
|
495
|
-
};
|
|
496
|
-
|
|
497
|
-
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: unknown) => unknown) => void;
|
|
498
|
-
// Register input before the watcher so an accepted extension input cannot race request dispatch.
|
|
499
|
-
onRuntimeEvent("input", onInput);
|
|
500
|
-
onRuntimeEvent("session_start", () => start());
|
|
501
|
-
onRuntimeEvent("agent_start", () => {
|
|
502
|
-
clearSettleFallback();
|
|
503
|
-
agentRunning = true;
|
|
504
|
-
awaitingSettlement = false;
|
|
505
|
-
return activate();
|
|
506
|
-
});
|
|
507
|
-
onRuntimeEvent("agent_end", (event) => {
|
|
508
|
-
inTurn = false;
|
|
509
|
-
if ((event as { willRetry?: unknown } | undefined)?.willRetry === true) {
|
|
510
|
-
clearSettleFallback();
|
|
511
|
-
agentRunning = true;
|
|
512
|
-
awaitingSettlement = true;
|
|
513
|
-
return activate();
|
|
514
|
-
}
|
|
515
|
-
agentRunning = true;
|
|
516
|
-
awaitingSettlement = true;
|
|
517
|
-
armLegacySettleFallback();
|
|
518
|
-
return activate();
|
|
519
|
-
});
|
|
520
|
-
onRuntimeEvent("agent_settled", markSettled);
|
|
521
|
-
onRuntimeEvent("session_compact", () => {
|
|
522
|
-
const unresolved = [...pending.values()].flat();
|
|
523
|
-
pending.clear();
|
|
524
|
-
for (const entry of unresolved) {
|
|
525
|
-
try {
|
|
526
|
-
writeSteerRequestToDir(steerInbox, { ...entry.request, mode: "follow_up" });
|
|
527
|
-
} catch (error) {
|
|
528
|
-
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
|
+
}
|
|
529
432
|
}
|
|
530
|
-
|
|
531
|
-
|
|
532
|
-
|
|
533
|
-
|
|
534
|
-
|
|
535
|
-
|
|
536
|
-
|
|
537
|
-
inTurn = true;
|
|
538
|
-
const next = queued.findIndex((entry) => entry.ready);
|
|
539
|
-
if (next >= 0) {
|
|
540
|
-
const [entry] = queued.splice(next, 1);
|
|
541
|
-
if (entry) acknowledge(entry.request, "delivered", "Pi delivered the queued follow-up at a turn boundary.", "delivered");
|
|
542
|
-
}
|
|
543
|
-
return activate();
|
|
544
|
-
});
|
|
545
|
-
onRuntimeEvent("turn_end", () => {
|
|
546
|
-
inTurn = false;
|
|
547
|
-
for (const entry of queued) entry.ready = true;
|
|
548
|
-
return activate();
|
|
549
|
-
});
|
|
550
|
-
for (const eventName of ["message_start", "message_update", "message_end", "tool_execution_start", "tool_execution_end"] as const) {
|
|
551
|
-
onRuntimeEvent(eventName, activate);
|
|
552
|
-
}
|
|
553
|
-
onRuntimeEvent("session_shutdown", () => {
|
|
554
|
-
for (const entry of queued) acknowledge(entry.request, "failed", "Run ended before queued follow-up delivery.", "queued");
|
|
555
|
-
for (const entries of pending.values()) {
|
|
556
|
-
for (const entry of entries) acknowledge(entry.request, "failed", "Run ended before Pi confirmed steering input delivery.");
|
|
557
|
-
}
|
|
558
|
-
disposed = true;
|
|
559
|
-
clearSettleFallback();
|
|
560
|
-
try { watcher?.close(); } catch {}
|
|
561
|
-
if (interval) (deps.timers?.clearInterval ?? clearInterval)(interval);
|
|
562
|
-
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
|
+
},
|
|
563
440
|
});
|
|
564
441
|
}
|
|
565
442
|
|
|
566
|
-
|
|
567
|
-
|
|
568
|
-
|
|
569
|
-
registerPermissionGate(pi);
|
|
570
|
-
registerToolBudget(pi,
|
|
571
|
-
registerChildWatchdog(pi);
|
|
572
|
-
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);
|
|
573
449
|
const waitState = {
|
|
574
450
|
baseCwd: "",
|
|
575
451
|
currentSessionId: null,
|
|
@@ -584,12 +460,13 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
584
460
|
watcherRestartTimer: null,
|
|
585
461
|
resultFileCoalescer: { schedule: () => false, clear: () => {} },
|
|
586
462
|
} as unknown as SubagentState;
|
|
587
|
-
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);
|
|
588
465
|
let nativeSupervisorClientRegistered = false;
|
|
589
466
|
const registerNativeSupervisorClientOnce = (): void => {
|
|
590
467
|
if (nativeSupervisorClientRegistered) return;
|
|
591
468
|
nativeSupervisorClientRegistered = true;
|
|
592
|
-
registerNativeSupervisorClient(pi);
|
|
469
|
+
registerNativeSupervisorClient(pi, supervisorMetadata);
|
|
593
470
|
};
|
|
594
471
|
const onRuntimeEvent = pi.on as unknown as (event: string, handler: (event: unknown, ctx?: ExtensionContext) => unknown) => void;
|
|
595
472
|
onRuntimeEvent("session_start", (_event: unknown, ctx?: ExtensionContext) => {
|
|
@@ -598,49 +475,24 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
598
475
|
registerNativeSupervisorClientOnce();
|
|
599
476
|
});
|
|
600
477
|
onRuntimeEvent("agent_start", () => {
|
|
601
|
-
|
|
478
|
+
if (!config.requiredTools) return;
|
|
479
|
+
const diagnostic = evaluateChildToolDiagnostic(config, pi.getAllTools().map((tool) => tool.name));
|
|
480
|
+
config.toolDiagnostic?.(diagnostic);
|
|
481
|
+
if (diagnostic) throw new Error(formatChildToolDiagnostic(diagnostic));
|
|
602
482
|
});
|
|
603
483
|
onRuntimeEvent("agent_end", async (_event: unknown, ctx: unknown) => {
|
|
604
484
|
if ((ctx as { hasUI?: boolean } | undefined)?.hasUI === true) return;
|
|
605
485
|
await drainOutstandingWork({ state: waitState, events: pi.events });
|
|
606
486
|
});
|
|
607
|
-
|
|
608
|
-
|
|
609
|
-
|
|
610
|
-
const schema = JSON.parse(fs.readFileSync(structuredSchemaPath, "utf-8")) as JsonSchemaObject;
|
|
611
|
-
const parameters = createStructuredOutputToolParameters(schema);
|
|
612
|
-
const registerTool = pi.registerTool as unknown as (tool: {
|
|
613
|
-
name: string;
|
|
614
|
-
label: string;
|
|
615
|
-
description: string;
|
|
616
|
-
parameters: unknown;
|
|
617
|
-
execute: (_id: string, params: { value: unknown }) => Promise<unknown>;
|
|
618
|
-
}) => void;
|
|
619
|
-
registerTool({
|
|
620
|
-
name: "structured_output",
|
|
621
|
-
label: "Structured Output",
|
|
622
|
-
description: "Submit the required final structured output for this subagent step. This terminates the step.",
|
|
623
|
-
parameters: parameters as never,
|
|
624
|
-
async execute(_id: string, params: { value: unknown }) {
|
|
625
|
-
const validation = await validateStructuredOutputValue(schema, params.value);
|
|
626
|
-
if (validation.status === "invalid") {
|
|
627
|
-
throw new Error(`Structured output validation failed: ${validation.message}`);
|
|
628
|
-
}
|
|
629
|
-
fs.mkdirSync(path.dirname(structuredOutputPath), { recursive: true });
|
|
630
|
-
fs.writeFileSync(structuredOutputPath, JSON.stringify(params.value), { mode: 0o600 });
|
|
631
|
-
return {
|
|
632
|
-
content: [{ type: "text", text: "Structured output captured." }],
|
|
633
|
-
details: { path: structuredOutputPath },
|
|
634
|
-
terminate: true,
|
|
635
|
-
};
|
|
636
|
-
},
|
|
637
|
-
});
|
|
638
|
-
}
|
|
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));
|
|
639
490
|
|
|
640
491
|
onRuntimeEvent("context", (event: unknown, ctx?: ExtensionContext) => {
|
|
641
492
|
if (!event || typeof event !== "object" || !("messages" in event) || !Array.isArray(event.messages)) return undefined;
|
|
642
493
|
const messages = stripParentOnlySubagentMessages(event.messages, {
|
|
643
494
|
sanitizeToolIds: !COMPOSITE_TOOL_ID_APIS.has(ctx?.model?.api ?? ""),
|
|
495
|
+
preserveFanoutToolHistory: config.fanoutChild,
|
|
644
496
|
});
|
|
645
497
|
if (messages === event.messages) return undefined;
|
|
646
498
|
return { messages };
|
|
@@ -649,20 +501,24 @@ export default function registerSubagentPromptRuntime(pi: ExtensionAPI): void {
|
|
|
649
501
|
onRuntimeEvent("before_agent_start", async (event: unknown) => {
|
|
650
502
|
if (!event || typeof event !== "object" || !("systemPrompt" in event) || typeof event.systemPrompt !== "string") return undefined;
|
|
651
503
|
registerNativeSupervisorClientOnce();
|
|
652
|
-
|
|
653
|
-
|
|
654
|
-
|
|
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);
|
|
655
510
|
}
|
|
656
511
|
|
|
657
|
-
const inheritProjectContext =
|
|
658
|
-
const
|
|
659
|
-
const fanoutChild = readBooleanEnv(SUBAGENT_FANOUT_CHILD_ENV);
|
|
512
|
+
const { inheritProjectContext, inheritGlobalContext, inheritSkills } = config;
|
|
513
|
+
const fanoutChild = config.fanoutChild;
|
|
660
514
|
let rewritten = event.systemPrompt;
|
|
661
|
-
if (inheritProjectContext !== undefined ||
|
|
515
|
+
if (inheritProjectContext !== undefined || inheritGlobalContext !== undefined || inheritSkills !== undefined || fanoutChild) {
|
|
662
516
|
rewritten = rewriteSubagentPrompt(event.systemPrompt, {
|
|
663
517
|
inheritProjectContext: inheritProjectContext ?? true,
|
|
518
|
+
inheritGlobalContext: inheritGlobalContext ?? true,
|
|
664
519
|
inheritSkills: inheritSkills ?? true,
|
|
665
|
-
fanoutChild
|
|
520
|
+
fanoutChild,
|
|
521
|
+
structuredOutput: Boolean(config.structuredOutput),
|
|
666
522
|
});
|
|
667
523
|
}
|
|
668
524
|
if (rewritten === event.systemPrompt) return;
|