@xzzpig/pi-subagents 0.1.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 +1621 -0
- package/LICENSE +21 -0
- package/README.md +118 -0
- package/agents/delegate.md +14 -0
- package/agents/oracle.md +74 -0
- package/agents/researcher.md +52 -0
- package/agents/reviewer.md +79 -0
- package/agents/scout.md +50 -0
- package/agents/worker.md +58 -0
- package/index.ts +1 -0
- package/inspector-runner.mjs +11 -0
- package/install.mjs +93 -0
- package/package.json +105 -0
- package/prompts/gather-context-and-clarify.md +13 -0
- package/prompts/parallel-cleanup.md +59 -0
- package/prompts/parallel-research.md +50 -0
- package/prompts/parallel-review.md +54 -0
- package/prompts/review-loop.md +43 -0
- package/skills/pi-subagents/SKILL.md +41 -0
- package/skills/pi-subagents/references/constraints-and-recipes.md +251 -0
- package/skills/pi-subagents/references/execution-controls.md +428 -0
- package/skills/pi-subagents/references/management-authoring-rpc.md +161 -0
- package/skills/pi-subagents/references/prompting-and-roles.md +242 -0
- package/src/agents/agent-management.ts +1256 -0
- package/src/agents/agent-memory.ts +254 -0
- package/src/agents/agent-refinements.ts +624 -0
- package/src/agents/agent-scope.ts +6 -0
- package/src/agents/agent-selection.ts +25 -0
- package/src/agents/agent-serializer.ts +163 -0
- package/src/agents/agents.ts +1889 -0
- package/src/agents/chain-serializer.ts +280 -0
- package/src/agents/frontmatter.ts +149 -0
- package/src/agents/identity.ts +30 -0
- package/src/agents/proactive-skills.ts +194 -0
- package/src/agents/skills.ts +761 -0
- package/src/api/background-work.ts +197 -0
- package/src/api/capability-ceiling.ts +17 -0
- package/src/api/control-channel.ts +4 -0
- package/src/api/delegation.ts +119 -0
- package/src/api/external-runs.ts +129 -0
- package/src/api/intercom-bridge.ts +3 -0
- package/src/api/pi-args.ts +5 -0
- package/src/api/preflight.ts +403 -0
- package/src/api/shared-types.ts +19 -0
- package/src/extension/config.ts +76 -0
- package/src/extension/control-notices.ts +58 -0
- package/src/extension/doctor.ts +230 -0
- package/src/extension/fanout-child.ts +201 -0
- package/src/extension/index.ts +805 -0
- package/src/extension/public-execution.ts +71 -0
- package/src/extension/rpc.ts +653 -0
- package/src/extension/schemas.ts +375 -0
- package/src/extension/steering-notices.ts +35 -0
- package/src/extension/tool-description.ts +164 -0
- package/src/inspectors/herdr/actions.ts +229 -0
- package/src/inspectors/herdr/client.ts +130 -0
- package/src/inspectors/herdr/inspector-runner.ts +141 -0
- package/src/inspectors/herdr/project-panes.ts +154 -0
- package/src/integrations/herdr-status.ts +330 -0
- package/src/intercom/intercom-bridge.ts +187 -0
- package/src/intercom/native-supervisor-channel.ts +715 -0
- package/src/intercom/result-intercom.ts +421 -0
- package/src/missions/actions.ts +410 -0
- package/src/missions/goal-driver.ts +162 -0
- package/src/missions/lifecycle.ts +346 -0
- package/src/missions/store.ts +507 -0
- package/src/missions/types.ts +157 -0
- package/src/missions/workflow-state.ts +250 -0
- package/src/policy/authority.ts +46 -0
- package/src/profiles/profiles.ts +661 -0
- package/src/runs/background/async-execution.ts +1574 -0
- package/src/runs/background/async-job-tracker.ts +511 -0
- package/src/runs/background/async-resume.ts +539 -0
- package/src/runs/background/async-status.ts +542 -0
- package/src/runs/background/auto-drain.ts +67 -0
- package/src/runs/background/chain-append.ts +328 -0
- package/src/runs/background/chain-root-attachment.ts +199 -0
- package/src/runs/background/completion-batcher.ts +168 -0
- package/src/runs/background/completion-dedupe.ts +54 -0
- package/src/runs/background/control-channel.ts +692 -0
- package/src/runs/background/fleet-view.ts +540 -0
- package/src/runs/background/notify.ts +332 -0
- package/src/runs/background/parallel-groups.ts +45 -0
- package/src/runs/background/process-terminal.ts +280 -0
- package/src/runs/background/result-watcher.ts +414 -0
- package/src/runs/background/retained-children.ts +68 -0
- package/src/runs/background/run-id-resolver.ts +167 -0
- package/src/runs/background/run-status.ts +504 -0
- package/src/runs/background/scheduled-runs.ts +753 -0
- package/src/runs/background/stale-run-reconciler.ts +396 -0
- package/src/runs/background/steering.ts +239 -0
- package/src/runs/background/subagent-runner.ts +4718 -0
- package/src/runs/background/subagent-wait.ts +661 -0
- package/src/runs/background/top-level-async.ts +14 -0
- package/src/runs/background/wait-completions.ts +112 -0
- package/src/runs/background/wait-config.ts +36 -0
- package/src/runs/background/wait-subscriptions.ts +253 -0
- package/src/runs/background/wait-tool.ts +34 -0
- package/src/runs/foreground/async-steering-action.ts +256 -0
- package/src/runs/foreground/async-stop-action.ts +65 -0
- package/src/runs/foreground/chain-clarify.ts +1354 -0
- package/src/runs/foreground/chain-execution.ts +1527 -0
- package/src/runs/foreground/execution.ts +1868 -0
- package/src/runs/foreground/foreground-control.ts +132 -0
- package/src/runs/foreground/subagent-executor.ts +5532 -0
- package/src/runs/shared/acceptance.ts +1365 -0
- package/src/runs/shared/agent-contract.ts +38 -0
- package/src/runs/shared/capability-ceiling.ts +209 -0
- package/src/runs/shared/chain-outputs.ts +118 -0
- package/src/runs/shared/child-protocol.ts +401 -0
- package/src/runs/shared/completion-guard.ts +95 -0
- package/src/runs/shared/context-mode.ts +44 -0
- package/src/runs/shared/dynamic-fanout.ts +297 -0
- package/src/runs/shared/external-cli-runner.ts +130 -0
- package/src/runs/shared/long-running-guard.ts +220 -0
- package/src/runs/shared/mcp-direct-tool-allowlist.ts +406 -0
- package/src/runs/shared/model-fallback.ts +336 -0
- package/src/runs/shared/model-scope.ts +128 -0
- package/src/runs/shared/nested-events.ts +1076 -0
- package/src/runs/shared/nested-path.ts +52 -0
- package/src/runs/shared/nested-render.ts +123 -0
- package/src/runs/shared/parallel-handoff.ts +238 -0
- package/src/runs/shared/parallel-utils.ts +256 -0
- package/src/runs/shared/permissions.ts +95 -0
- package/src/runs/shared/pi-args.ts +808 -0
- package/src/runs/shared/pi-spawn.ts +163 -0
- package/src/runs/shared/process-signal.ts +19 -0
- package/src/runs/shared/run-history.ts +181 -0
- package/src/runs/shared/runtime-acknowledged-extensions.ts +71 -0
- package/src/runs/shared/session-lease.ts +299 -0
- package/src/runs/shared/single-output.ts +235 -0
- package/src/runs/shared/spawn-budget.ts +128 -0
- package/src/runs/shared/structured-output.ts +182 -0
- package/src/runs/shared/subagent-control.ts +231 -0
- package/src/runs/shared/subagent-prompt-runtime.ts +588 -0
- package/src/runs/shared/subagent-startup-retry.ts +104 -0
- package/src/runs/shared/task-intent.ts +181 -0
- package/src/runs/shared/tool-availability.ts +83 -0
- package/src/runs/shared/tool-budget.ts +80 -0
- package/src/runs/shared/turn-budget.ts +98 -0
- package/src/runs/shared/usage-budget.ts +65 -0
- package/src/runs/shared/workflow-graph.ts +231 -0
- package/src/runs/shared/worktree.ts +759 -0
- package/src/shared/accessible-dir.ts +47 -0
- package/src/shared/artifacts.ts +285 -0
- package/src/shared/atomic-json.ts +61 -0
- package/src/shared/child-transcript.ts +264 -0
- package/src/shared/file-coalescer.ts +40 -0
- package/src/shared/file-system-retry.ts +47 -0
- package/src/shared/fork-context.ts +213 -0
- package/src/shared/formatters.ts +133 -0
- package/src/shared/jsonl-writer.ts +81 -0
- package/src/shared/launch-contract.ts +124 -0
- package/src/shared/model-info.ts +81 -0
- package/src/shared/post-exit-stdio-guard.ts +85 -0
- package/src/shared/session-identity.ts +10 -0
- package/src/shared/session-tokens.ts +44 -0
- package/src/shared/settings.ts +501 -0
- package/src/shared/status-format.ts +55 -0
- package/src/shared/types.ts +2069 -0
- package/src/shared/utils.ts +613 -0
- package/src/slash/delegation-adapters.ts +434 -0
- package/src/slash/delegation-json.ts +108 -0
- package/src/slash/delegation-request.ts +166 -0
- package/src/slash/prompt-template-bridge.ts +383 -0
- package/src/slash/prompt-workflows.ts +300 -0
- package/src/slash/selector.ts +147 -0
- package/src/slash/slash-bridge.ts +192 -0
- package/src/slash/slash-commands.ts +994 -0
- package/src/slash/slash-live-state.ts +296 -0
- package/src/slash/subagents-admin.ts +432 -0
- package/src/tui/fleet-status.ts +564 -0
- package/src/tui/fleet-transcript.ts +577 -0
- package/src/tui/fleet.ts +879 -0
- package/src/tui/render-helpers.ts +80 -0
- package/src/tui/render.ts +2029 -0
- package/src/types/pi-runtime-compat.d.ts +8 -0
- package/src/watchdog/change-signature.ts +220 -0
- package/src/watchdog/child-status.ts +205 -0
- package/src/watchdog/emission-guard.ts +123 -0
- package/src/watchdog/lsp-diagnostics.ts +537 -0
- package/src/watchdog/model-selection.ts +167 -0
- package/src/watchdog/permission-arbiter.ts +145 -0
- package/src/watchdog/register-child.ts +117 -0
- package/src/watchdog/register-main.ts +440 -0
- package/src/watchdog/render.ts +54 -0
- package/src/watchdog/review.ts +302 -0
- package/src/watchdog/runtime.ts +868 -0
- package/src/watchdog/scope.ts +62 -0
- package/src/watchdog/settings.ts +568 -0
- package/src/watchdog/tool-actions.ts +155 -0
- package/src/watchdog/turn-delta.ts +161 -0
- package/src/watchdog/types.ts +198 -0
- package/src/watchdog/warning-format.ts +73 -0
- package/src/workflows/chat-progress.ts +140 -0
- package/src/workflows/scripted-workflow.ts +506 -0
|
@@ -0,0 +1,166 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type SubagentDelegationRequest,
|
|
3
|
+
} from "../api/delegation.ts";
|
|
4
|
+
import { validateToolBudgetConfig } from "../runs/shared/tool-budget.ts";
|
|
5
|
+
import { resolveTurnBudgetConfig } from "../runs/shared/turn-budget.ts";
|
|
6
|
+
import { cloneJsonWithinByteLimit } from "./delegation-json.ts";
|
|
7
|
+
|
|
8
|
+
export type SubagentDelegationParseResult =
|
|
9
|
+
| { ok: true; request: SubagentDelegationRequest }
|
|
10
|
+
| { ok: false; requestId?: string; ownerRunId?: string; nodeId?: string; error: string };
|
|
11
|
+
|
|
12
|
+
const supportedFields = new Set([
|
|
13
|
+
"requestId",
|
|
14
|
+
"ownerRunId",
|
|
15
|
+
"nodeId",
|
|
16
|
+
"agent",
|
|
17
|
+
"task",
|
|
18
|
+
"context",
|
|
19
|
+
"cwd",
|
|
20
|
+
"model",
|
|
21
|
+
"thinking",
|
|
22
|
+
"timeoutMs",
|
|
23
|
+
"turnBudget",
|
|
24
|
+
"toolBudget",
|
|
25
|
+
"skill",
|
|
26
|
+
"artifacts",
|
|
27
|
+
"result",
|
|
28
|
+
]);
|
|
29
|
+
|
|
30
|
+
const thinkingLevels = new Set(["off", "minimal", "low", "medium", "high", "xhigh", "max"]);
|
|
31
|
+
const MAX_SCHEMA_BYTES = 64 * 1024;
|
|
32
|
+
const MAX_TASK_BYTES = 1024 * 1024;
|
|
33
|
+
const MAX_CWD_BYTES = 32 * 1024;
|
|
34
|
+
const MAX_SHORT_TEXT_BYTES = 1024;
|
|
35
|
+
const MAX_SKILL_ENTRIES = 256;
|
|
36
|
+
const MAX_SKILL_AGGREGATE_BYTES = 64 * 1024;
|
|
37
|
+
|
|
38
|
+
function nonEmptyString(value: unknown): value is string {
|
|
39
|
+
return typeof value === "string" && value.trim().length > 0;
|
|
40
|
+
}
|
|
41
|
+
|
|
42
|
+
function validateId(value: unknown): string | undefined {
|
|
43
|
+
if (!nonEmptyString(value) || value.length > 256 || /[\r\n]/.test(value)) return undefined;
|
|
44
|
+
return value;
|
|
45
|
+
}
|
|
46
|
+
|
|
47
|
+
export function parseSubagentDelegationRequest(data: unknown): SubagentDelegationParseResult {
|
|
48
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) {
|
|
49
|
+
return { ok: false, error: "Delegation request must be an object." };
|
|
50
|
+
}
|
|
51
|
+
const value = data as Record<string, unknown>;
|
|
52
|
+
const requestId = validateId(value.requestId);
|
|
53
|
+
if (!requestId) {
|
|
54
|
+
return { ok: false, error: "Delegation requestId must be a non-empty string of at most 256 characters without newlines." };
|
|
55
|
+
}
|
|
56
|
+
const ownerRunId = validateId(value.ownerRunId);
|
|
57
|
+
if (!ownerRunId) {
|
|
58
|
+
return { ok: false, requestId, error: "Delegation ownerRunId must be a non-empty string of at most 256 characters without newlines." };
|
|
59
|
+
}
|
|
60
|
+
const nodeId = validateId(value.nodeId);
|
|
61
|
+
if (!nodeId) {
|
|
62
|
+
return { ok: false, requestId, ownerRunId, error: "Delegation nodeId must be a non-empty string of at most 256 characters without newlines." };
|
|
63
|
+
}
|
|
64
|
+
const identity = { requestId, ownerRunId, nodeId };
|
|
65
|
+
const unsupportedField = Object.keys(value).find((key) => !supportedFields.has(key));
|
|
66
|
+
if (unsupportedField) return { ok: false, ...identity, error: `Unsupported delegation field: ${unsupportedField}.` };
|
|
67
|
+
if (!nonEmptyString(value.agent)) return { ok: false, ...identity, error: "Delegation agent must be a non-empty string." };
|
|
68
|
+
if (!nonEmptyString(value.task)) return { ok: false, ...identity, error: "Delegation task must be a non-empty string." };
|
|
69
|
+
if (value.context !== "fresh" && value.context !== "fork") {
|
|
70
|
+
return { ok: false, ...identity, error: "Delegation context must be fresh or fork." };
|
|
71
|
+
}
|
|
72
|
+
if (!nonEmptyString(value.cwd)) return { ok: false, ...identity, error: "Delegation cwd must be a non-empty string." };
|
|
73
|
+
if (value.model !== undefined && !nonEmptyString(value.model)) {
|
|
74
|
+
return { ok: false, ...identity, error: "model must be a non-empty string when provided." };
|
|
75
|
+
}
|
|
76
|
+
if (value.timeoutMs !== undefined && (typeof value.timeoutMs !== "number" || !Number.isInteger(value.timeoutMs) || value.timeoutMs < 1)) {
|
|
77
|
+
return { ok: false, ...identity, error: "timeoutMs must be an integer >= 1." };
|
|
78
|
+
}
|
|
79
|
+
const timeoutMs = typeof value.timeoutMs === "number" ? value.timeoutMs : undefined;
|
|
80
|
+
if (timeoutMs !== undefined && timeoutMs > 2_147_483_647) {
|
|
81
|
+
return { ok: false, ...identity, error: "timeoutMs must be <= 2147483647." };
|
|
82
|
+
}
|
|
83
|
+
const turnBudget = resolveTurnBudgetConfig(value.turnBudget);
|
|
84
|
+
if (turnBudget.error) return { ok: false, ...identity, error: turnBudget.error };
|
|
85
|
+
if (value.toolBudget && typeof value.toolBudget === "object" && !Array.isArray(value.toolBudget)) {
|
|
86
|
+
const unsupportedToolBudgetField = Object.keys(value.toolBudget).find((key) => key !== "soft" && key !== "hard" && key !== "block");
|
|
87
|
+
if (unsupportedToolBudgetField) {
|
|
88
|
+
return { ok: false, ...identity, error: `toolBudget.${unsupportedToolBudgetField} is not supported.` };
|
|
89
|
+
}
|
|
90
|
+
}
|
|
91
|
+
const toolBudget = validateToolBudgetConfig(value.toolBudget, "toolBudget", { minimumHard: 0 });
|
|
92
|
+
if (toolBudget.error) return { ok: false, ...identity, error: toolBudget.error };
|
|
93
|
+
if (value.skill !== undefined) {
|
|
94
|
+
const validSkill = typeof value.skill === "boolean"
|
|
95
|
+
|| nonEmptyString(value.skill)
|
|
96
|
+
|| (Array.isArray(value.skill) && value.skill.length > 0 && value.skill.every(nonEmptyString));
|
|
97
|
+
if (!validSkill) {
|
|
98
|
+
return { ok: false, ...identity, error: "skill must be a boolean, non-empty string, or non-empty string array." };
|
|
99
|
+
}
|
|
100
|
+
}
|
|
101
|
+
if (value.artifacts !== undefined && typeof value.artifacts !== "boolean") {
|
|
102
|
+
return { ok: false, ...identity, error: "artifacts must be a boolean." };
|
|
103
|
+
}
|
|
104
|
+
if (Buffer.byteLength(value.task as string, "utf8") > MAX_TASK_BYTES) {
|
|
105
|
+
return { ok: false, ...identity, error: "Delegation task exceeds 1 MiB when UTF-8 encoded." };
|
|
106
|
+
}
|
|
107
|
+
if (Buffer.byteLength(value.cwd as string, "utf8") > MAX_CWD_BYTES) {
|
|
108
|
+
return { ok: false, ...identity, error: "Delegation cwd exceeds 32 KiB when UTF-8 encoded." };
|
|
109
|
+
}
|
|
110
|
+
if (Buffer.byteLength(value.agent as string, "utf8") > MAX_SHORT_TEXT_BYTES) {
|
|
111
|
+
return { ok: false, ...identity, error: "Delegation agent exceeds 1 KiB when UTF-8 encoded." };
|
|
112
|
+
}
|
|
113
|
+
if (typeof value.model === "string" && Buffer.byteLength(value.model, "utf8") > MAX_SHORT_TEXT_BYTES) {
|
|
114
|
+
return { ok: false, ...identity, error: "Delegation model exceeds 1 KiB when UTF-8 encoded." };
|
|
115
|
+
}
|
|
116
|
+
const skillEntries = typeof value.skill === "string" ? [value.skill] : Array.isArray(value.skill) ? value.skill as string[] : [];
|
|
117
|
+
if (skillEntries.length > MAX_SKILL_ENTRIES) {
|
|
118
|
+
return { ok: false, ...identity, error: "Delegation skill supports at most 256 entries." };
|
|
119
|
+
}
|
|
120
|
+
if (skillEntries.some((entry) => Buffer.byteLength(entry, "utf8") > MAX_SHORT_TEXT_BYTES)) {
|
|
121
|
+
return { ok: false, ...identity, error: "Delegation skill entry exceeds 1 KiB when UTF-8 encoded." };
|
|
122
|
+
}
|
|
123
|
+
if (skillEntries.reduce((total, entry) => total + Buffer.byteLength(entry, "utf8"), 0) > MAX_SKILL_AGGREGATE_BYTES) {
|
|
124
|
+
return { ok: false, ...identity, error: "Delegation skill entries exceed 64 KiB in aggregate when UTF-8 encoded." };
|
|
125
|
+
}
|
|
126
|
+
if (value.thinking !== undefined && (typeof value.thinking !== "string" || !thinkingLevels.has(value.thinking))) {
|
|
127
|
+
return { ok: false, ...identity, error: "thinking must be one of off, minimal, low, medium, high, xhigh, or max." };
|
|
128
|
+
}
|
|
129
|
+
if (!value.result || typeof value.result !== "object" || Array.isArray(value.result)) {
|
|
130
|
+
return { ok: false, ...identity, error: "result must be { kind: \"text\" } or { kind: \"structured\", schema: object }." };
|
|
131
|
+
}
|
|
132
|
+
const result = value.result as Record<string, unknown>;
|
|
133
|
+
let structuredSchema: Record<string, unknown> | undefined;
|
|
134
|
+
if (result.kind === "text") {
|
|
135
|
+
const unsupportedResultField = Object.keys(result).find((key) => key !== "kind");
|
|
136
|
+
if (unsupportedResultField) return { ok: false, ...identity, error: `result.${unsupportedResultField} is not supported for text results.` };
|
|
137
|
+
} else if (result.kind === "structured") {
|
|
138
|
+
const unsupportedResultField = Object.keys(result).find((key) => key !== "kind" && key !== "schema");
|
|
139
|
+
if (unsupportedResultField) return { ok: false, ...identity, error: `result.${unsupportedResultField} is not supported for structured results.` };
|
|
140
|
+
if (!result.schema || typeof result.schema !== "object" || Array.isArray(result.schema)) {
|
|
141
|
+
return { ok: false, ...identity, error: "result.schema must be a JSON Schema object." };
|
|
142
|
+
}
|
|
143
|
+
const inspectedSchema = cloneJsonWithinByteLimit(result.schema, MAX_SCHEMA_BYTES);
|
|
144
|
+
if (inspectedSchema.ok === false) {
|
|
145
|
+
return {
|
|
146
|
+
ok: false,
|
|
147
|
+
...identity,
|
|
148
|
+
error: inspectedSchema.reason === "too_large"
|
|
149
|
+
? "result.schema exceeds 64 KiB when encoded."
|
|
150
|
+
: "result.schema must be plain JSON data.",
|
|
151
|
+
};
|
|
152
|
+
}
|
|
153
|
+
structuredSchema = inspectedSchema.value as Record<string, unknown>;
|
|
154
|
+
} else {
|
|
155
|
+
return { ok: false, ...identity, error: "result.kind must be text or structured." };
|
|
156
|
+
}
|
|
157
|
+
return {
|
|
158
|
+
ok: true,
|
|
159
|
+
request: {
|
|
160
|
+
...value,
|
|
161
|
+
result: structuredSchema
|
|
162
|
+
? { kind: "structured", schema: structuredSchema }
|
|
163
|
+
: { kind: "text" },
|
|
164
|
+
} as unknown as SubagentDelegationRequest,
|
|
165
|
+
};
|
|
166
|
+
}
|
|
@@ -0,0 +1,383 @@
|
|
|
1
|
+
import {
|
|
2
|
+
SUBAGENT_DELEGATION_CANCEL_EVENT,
|
|
3
|
+
SUBAGENT_DELEGATION_REQUEST_EVENT,
|
|
4
|
+
SUBAGENT_DELEGATION_RESPONSE_EVENT,
|
|
5
|
+
SUBAGENT_DELEGATION_STARTED_EVENT,
|
|
6
|
+
SUBAGENT_DELEGATION_UPDATE_EVENT,
|
|
7
|
+
type SubagentDelegationInvalidResponse,
|
|
8
|
+
type SubagentDelegationRequest,
|
|
9
|
+
type SubagentDelegationResponse,
|
|
10
|
+
} from "../api/delegation.ts";
|
|
11
|
+
import { parseSubagentDelegationRequest } from "./delegation-request.ts";
|
|
12
|
+
import {
|
|
13
|
+
parsePromptTemplateRequest,
|
|
14
|
+
toDelegationUpdate,
|
|
15
|
+
toPromptTemplateResponse,
|
|
16
|
+
toSubagentDelegationExecutionParams,
|
|
17
|
+
toSubagentDelegationResponse,
|
|
18
|
+
toSubagentDelegationUpdate,
|
|
19
|
+
type DelegatedSubagentExecutionParams,
|
|
20
|
+
type PromptTemplateBridgeResult,
|
|
21
|
+
type PromptTemplateDelegationRequest,
|
|
22
|
+
type PromptTemplateDelegationResponse,
|
|
23
|
+
} from "./delegation-adapters.ts";
|
|
24
|
+
|
|
25
|
+
export const PROMPT_TEMPLATE_SUBAGENT_REQUEST_EVENT = SUBAGENT_DELEGATION_REQUEST_EVENT;
|
|
26
|
+
export const PROMPT_TEMPLATE_SUBAGENT_STARTED_EVENT = SUBAGENT_DELEGATION_STARTED_EVENT;
|
|
27
|
+
export const PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT = SUBAGENT_DELEGATION_RESPONSE_EVENT;
|
|
28
|
+
export const PROMPT_TEMPLATE_SUBAGENT_UPDATE_EVENT = SUBAGENT_DELEGATION_UPDATE_EVENT;
|
|
29
|
+
export const PROMPT_TEMPLATE_SUBAGENT_CANCEL_EVENT = SUBAGENT_DELEGATION_CANCEL_EVENT;
|
|
30
|
+
|
|
31
|
+
export interface PromptTemplateBridgeEvents {
|
|
32
|
+
on(event: string, handler: (data: unknown) => void): (() => void) | void;
|
|
33
|
+
emit(event: string, data: unknown): void;
|
|
34
|
+
}
|
|
35
|
+
|
|
36
|
+
interface PromptTemplateBridgeOptions<Ctx extends { cwd?: string }> {
|
|
37
|
+
events: PromptTemplateBridgeEvents;
|
|
38
|
+
getContext: () => Ctx | null;
|
|
39
|
+
execute: (
|
|
40
|
+
requestId: string,
|
|
41
|
+
params: DelegatedSubagentExecutionParams,
|
|
42
|
+
signal: AbortSignal,
|
|
43
|
+
ctx: Ctx,
|
|
44
|
+
onUpdate: (result: PromptTemplateBridgeResult) => void,
|
|
45
|
+
) => Promise<PromptTemplateBridgeResult>;
|
|
46
|
+
/** Concurrent-safe executor for structured delegation requests. */
|
|
47
|
+
executeStructured?: (
|
|
48
|
+
requestId: string,
|
|
49
|
+
params: DelegatedSubagentExecutionParams,
|
|
50
|
+
signal: AbortSignal,
|
|
51
|
+
ctx: Ctx,
|
|
52
|
+
onUpdate: (result: PromptTemplateBridgeResult) => void,
|
|
53
|
+
) => Promise<PromptTemplateBridgeResult>;
|
|
54
|
+
}
|
|
55
|
+
|
|
56
|
+
function hasStructuredDelegationMarker(data: unknown): boolean {
|
|
57
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return false;
|
|
58
|
+
const value = data as Record<string, unknown>;
|
|
59
|
+
return Object.hasOwn(value, "ownerRunId")
|
|
60
|
+
|| Object.hasOwn(value, "nodeId")
|
|
61
|
+
|| Object.hasOwn(value, "result")
|
|
62
|
+
|| Object.hasOwn(value, "version");
|
|
63
|
+
}
|
|
64
|
+
|
|
65
|
+
function validId(value: unknown): value is string {
|
|
66
|
+
return typeof value === "string" && value.trim().length > 0 && value.length <= 256 && !/[\r\n]/.test(value);
|
|
67
|
+
}
|
|
68
|
+
|
|
69
|
+
export function registerPromptTemplateDelegationBridge<Ctx extends { cwd?: string }>(
|
|
70
|
+
options: PromptTemplateBridgeOptions<Ctx>,
|
|
71
|
+
): {
|
|
72
|
+
cancelAll: () => void;
|
|
73
|
+
dispose: () => void;
|
|
74
|
+
} {
|
|
75
|
+
const legacyControllers = new Map<string, AbortController>();
|
|
76
|
+
const pendingLegacyCancels = new Map<string, true>();
|
|
77
|
+
const attemptControllers = new Map<string, AbortController>();
|
|
78
|
+
const pendingAttemptCancels = new Map<string, true>();
|
|
79
|
+
const activeOwnedNodes = new Map<string, { attemptKey: string; controller: AbortController }>();
|
|
80
|
+
const settledAttempts = new Map<string, true>();
|
|
81
|
+
const subscriptions: Array<() => void> = [];
|
|
82
|
+
let disposed = false;
|
|
83
|
+
let identitySaturated = false;
|
|
84
|
+
|
|
85
|
+
const subscribe = (event: string, handler: (data: unknown) => void): void => {
|
|
86
|
+
const unsubscribe = options.events.on(event, handler);
|
|
87
|
+
if (typeof unsubscribe === "function") subscriptions.push(unsubscribe);
|
|
88
|
+
};
|
|
89
|
+
const ownsLegacyRequest = (requestId: string, controller: AbortController): boolean =>
|
|
90
|
+
!disposed && legacyControllers.get(requestId) === controller;
|
|
91
|
+
const ownsAttempt = (attemptKey: string, controller: AbortController): boolean =>
|
|
92
|
+
!disposed && attemptControllers.get(attemptKey) === controller;
|
|
93
|
+
const boundedRemember = (map: Map<string, true>, key: string): void => {
|
|
94
|
+
map.delete(key);
|
|
95
|
+
map.set(key, true);
|
|
96
|
+
while (map.size > 256) {
|
|
97
|
+
const oldest = map.keys().next().value;
|
|
98
|
+
if (typeof oldest !== "string") break;
|
|
99
|
+
map.delete(oldest);
|
|
100
|
+
}
|
|
101
|
+
};
|
|
102
|
+
const rememberIdentity = (map: Map<string, true>, key: string): void => {
|
|
103
|
+
if (map.has(key) || identitySaturated) return;
|
|
104
|
+
if (map.size >= 8_192) {
|
|
105
|
+
identitySaturated = true;
|
|
106
|
+
return;
|
|
107
|
+
}
|
|
108
|
+
map.set(key, true);
|
|
109
|
+
if (map.size === 8_192) {
|
|
110
|
+
// Exact cancellation and terminal-attempt facts are security state, not an
|
|
111
|
+
// LRU cache. Once full, fail closed rather than evicting identity facts.
|
|
112
|
+
identitySaturated = true;
|
|
113
|
+
}
|
|
114
|
+
};
|
|
115
|
+
const nodeKey = (ownerRunId: string, nodeId: string): string => JSON.stringify([ownerRunId, nodeId]);
|
|
116
|
+
const attemptKey = (requestId: string, ownerRunId: string, nodeId: string): string => JSON.stringify([requestId, ownerRunId, nodeId]);
|
|
117
|
+
const rememberPendingLegacyCancel = (requestId: string): void => {
|
|
118
|
+
boundedRemember(pendingLegacyCancels, requestId);
|
|
119
|
+
};
|
|
120
|
+
const emitTerminal = (key: string, payload: SubagentDelegationResponse): void => {
|
|
121
|
+
if (disposed || settledAttempts.has(key)) return;
|
|
122
|
+
rememberIdentity(settledAttempts, key);
|
|
123
|
+
options.events.emit(SUBAGENT_DELEGATION_RESPONSE_EVENT, payload);
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
subscribe(PROMPT_TEMPLATE_SUBAGENT_CANCEL_EVENT, (data) => {
|
|
127
|
+
if (!data || typeof data !== "object" || Array.isArray(data)) return;
|
|
128
|
+
const value = data as Record<string, unknown>;
|
|
129
|
+
const requestId = value.requestId;
|
|
130
|
+
if (!validId(requestId)) return;
|
|
131
|
+
if (hasStructuredDelegationMarker(data)) {
|
|
132
|
+
if (Object.keys(value).some((key) => key !== "requestId" && key !== "ownerRunId" && key !== "nodeId")) return;
|
|
133
|
+
const ownerRunId = value.ownerRunId;
|
|
134
|
+
const nodeId = value.nodeId;
|
|
135
|
+
if (!validId(ownerRunId) || !validId(nodeId)) return;
|
|
136
|
+
const key = attemptKey(requestId, ownerRunId, nodeId);
|
|
137
|
+
const controller = attemptControllers.get(key);
|
|
138
|
+
if (controller) controller.abort();
|
|
139
|
+
else rememberIdentity(pendingAttemptCancels, key);
|
|
140
|
+
return;
|
|
141
|
+
}
|
|
142
|
+
const controller = legacyControllers.get(requestId);
|
|
143
|
+
if (controller) {
|
|
144
|
+
controller.abort();
|
|
145
|
+
return;
|
|
146
|
+
}
|
|
147
|
+
rememberPendingLegacyCancel(requestId);
|
|
148
|
+
});
|
|
149
|
+
|
|
150
|
+
subscribe(PROMPT_TEMPLATE_SUBAGENT_REQUEST_EVENT, async (data) => {
|
|
151
|
+
const structuredPayload = hasStructuredDelegationMarker(data);
|
|
152
|
+
let requestId: string;
|
|
153
|
+
let params: DelegatedSubagentExecutionParams;
|
|
154
|
+
let structuredRequest: SubagentDelegationRequest | undefined;
|
|
155
|
+
let key: string | undefined;
|
|
156
|
+
let legacyRequest: PromptTemplateDelegationRequest | undefined;
|
|
157
|
+
|
|
158
|
+
if (structuredPayload) {
|
|
159
|
+
const parsed = parseSubagentDelegationRequest(data);
|
|
160
|
+
if (parsed.ok === false) {
|
|
161
|
+
if (!disposed && parsed.requestId) {
|
|
162
|
+
const payload = {
|
|
163
|
+
requestId: parsed.requestId,
|
|
164
|
+
...(parsed.ownerRunId ? { ownerRunId: parsed.ownerRunId } : {}),
|
|
165
|
+
...(parsed.nodeId ? { nodeId: parsed.nodeId } : {}),
|
|
166
|
+
status: "invalid_request",
|
|
167
|
+
error: parsed.error,
|
|
168
|
+
} satisfies SubagentDelegationInvalidResponse;
|
|
169
|
+
if (parsed.ownerRunId && parsed.nodeId) {
|
|
170
|
+
const attemptedKey = attemptKey(parsed.requestId, parsed.ownerRunId, parsed.nodeId);
|
|
171
|
+
if (!attemptControllers.has(attemptedKey)) emitTerminal(attemptedKey, payload);
|
|
172
|
+
} else {
|
|
173
|
+
options.events.emit(SUBAGENT_DELEGATION_RESPONSE_EVENT, payload);
|
|
174
|
+
}
|
|
175
|
+
}
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
structuredRequest = parsed.request;
|
|
179
|
+
requestId = parsed.request.requestId;
|
|
180
|
+
key = attemptKey(requestId, parsed.request.ownerRunId, parsed.request.nodeId);
|
|
181
|
+
params = toSubagentDelegationExecutionParams(parsed.request);
|
|
182
|
+
} else {
|
|
183
|
+
if (data && typeof data === "object" && !Array.isArray(data)) {
|
|
184
|
+
const legacy = data as Record<string, unknown>;
|
|
185
|
+
if ((legacy.tasks !== undefined || legacy.worktree !== undefined) && typeof legacy.requestId === "string" && legacy.requestId) {
|
|
186
|
+
options.events.emit(PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT, {
|
|
187
|
+
requestId: legacy.requestId,
|
|
188
|
+
messages: [],
|
|
189
|
+
isError: true,
|
|
190
|
+
errorText: "Legacy prompt-template tasks/worktree orchestration was removed; use workflowScript.",
|
|
191
|
+
});
|
|
192
|
+
return;
|
|
193
|
+
}
|
|
194
|
+
}
|
|
195
|
+
legacyRequest = parsePromptTemplateRequest(data);
|
|
196
|
+
if (!legacyRequest) return;
|
|
197
|
+
options.events.emit(PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT, {
|
|
198
|
+
...legacyRequest,
|
|
199
|
+
messages: [],
|
|
200
|
+
isError: true,
|
|
201
|
+
errorText: "Legacy prompt-template direct delegation was removed; use workflowScript through the subagent tool or structured delegation.",
|
|
202
|
+
} satisfies PromptTemplateDelegationResponse);
|
|
203
|
+
return;
|
|
204
|
+
}
|
|
205
|
+
|
|
206
|
+
if (!structuredRequest && legacyControllers.has(requestId)) return;
|
|
207
|
+
if (structuredRequest && key) {
|
|
208
|
+
if (attemptControllers.has(key) || settledAttempts.has(key)) return;
|
|
209
|
+
if (pendingAttemptCancels.delete(key)) {
|
|
210
|
+
emitTerminal(key, {
|
|
211
|
+
requestId,
|
|
212
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
213
|
+
nodeId: structuredRequest.nodeId,
|
|
214
|
+
status: "cancelled",
|
|
215
|
+
});
|
|
216
|
+
return;
|
|
217
|
+
}
|
|
218
|
+
if (identitySaturated) {
|
|
219
|
+
options.events.emit(SUBAGENT_DELEGATION_RESPONSE_EVENT, {
|
|
220
|
+
requestId,
|
|
221
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
222
|
+
nodeId: structuredRequest.nodeId,
|
|
223
|
+
status: "unavailable_context",
|
|
224
|
+
error: "Delegation identity capacity is exhausted for this extension context.",
|
|
225
|
+
} satisfies SubagentDelegationResponse);
|
|
226
|
+
return;
|
|
227
|
+
}
|
|
228
|
+
const active = activeOwnedNodes.get(nodeKey(structuredRequest.ownerRunId, structuredRequest.nodeId));
|
|
229
|
+
if (active) {
|
|
230
|
+
emitTerminal(key, {
|
|
231
|
+
requestId,
|
|
232
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
233
|
+
nodeId: structuredRequest.nodeId,
|
|
234
|
+
status: "duplicate_node",
|
|
235
|
+
});
|
|
236
|
+
return;
|
|
237
|
+
}
|
|
238
|
+
}
|
|
239
|
+
const ctx = options.getContext();
|
|
240
|
+
if (!ctx) {
|
|
241
|
+
if (structuredRequest && key) {
|
|
242
|
+
emitTerminal(key, {
|
|
243
|
+
requestId,
|
|
244
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
245
|
+
nodeId: structuredRequest.nodeId,
|
|
246
|
+
status: "unavailable_context",
|
|
247
|
+
error: "No active extension context for delegated subagent execution.",
|
|
248
|
+
});
|
|
249
|
+
} else if (legacyRequest) {
|
|
250
|
+
options.events.emit(PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT, {
|
|
251
|
+
...legacyRequest,
|
|
252
|
+
messages: [],
|
|
253
|
+
isError: true,
|
|
254
|
+
errorText: "No active extension context for delegated subagent execution.",
|
|
255
|
+
} satisfies PromptTemplateDelegationResponse);
|
|
256
|
+
}
|
|
257
|
+
return;
|
|
258
|
+
}
|
|
259
|
+
|
|
260
|
+
const controller = new AbortController();
|
|
261
|
+
if (structuredRequest && key) {
|
|
262
|
+
attemptControllers.set(key, controller);
|
|
263
|
+
activeOwnedNodes.set(nodeKey(structuredRequest.ownerRunId, structuredRequest.nodeId), { attemptKey: key, controller });
|
|
264
|
+
} else {
|
|
265
|
+
legacyControllers.set(requestId, controller);
|
|
266
|
+
if (pendingLegacyCancels.delete(requestId)) controller.abort();
|
|
267
|
+
}
|
|
268
|
+
if (controller.signal.aborted) {
|
|
269
|
+
if (structuredRequest && key) {
|
|
270
|
+
emitTerminal(key, {
|
|
271
|
+
requestId,
|
|
272
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
273
|
+
nodeId: structuredRequest.nodeId,
|
|
274
|
+
status: "cancelled",
|
|
275
|
+
});
|
|
276
|
+
activeOwnedNodes.delete(nodeKey(structuredRequest.ownerRunId, structuredRequest.nodeId));
|
|
277
|
+
} else if (legacyRequest) {
|
|
278
|
+
options.events.emit(PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT, {
|
|
279
|
+
...legacyRequest,
|
|
280
|
+
messages: [],
|
|
281
|
+
isError: true,
|
|
282
|
+
errorText: "Delegated prompt cancelled.",
|
|
283
|
+
} satisfies PromptTemplateDelegationResponse);
|
|
284
|
+
}
|
|
285
|
+
if (key) attemptControllers.delete(key);
|
|
286
|
+
else legacyControllers.delete(requestId);
|
|
287
|
+
return;
|
|
288
|
+
}
|
|
289
|
+
|
|
290
|
+
options.events.emit(
|
|
291
|
+
structuredRequest ? SUBAGENT_DELEGATION_STARTED_EVENT : PROMPT_TEMPLATE_SUBAGENT_STARTED_EVENT,
|
|
292
|
+
structuredRequest
|
|
293
|
+
? { requestId, ownerRunId: structuredRequest.ownerRunId, nodeId: structuredRequest.nodeId }
|
|
294
|
+
: { requestId },
|
|
295
|
+
);
|
|
296
|
+
|
|
297
|
+
try {
|
|
298
|
+
const executeRequest = structuredRequest && options.executeStructured
|
|
299
|
+
? options.executeStructured
|
|
300
|
+
: options.execute;
|
|
301
|
+
const result = await executeRequest(
|
|
302
|
+
requestId,
|
|
303
|
+
params,
|
|
304
|
+
controller.signal,
|
|
305
|
+
ctx,
|
|
306
|
+
(update) => {
|
|
307
|
+
if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
|
|
308
|
+
if (structuredRequest) {
|
|
309
|
+
const payload = toSubagentDelegationUpdate(structuredRequest, update);
|
|
310
|
+
if (payload) options.events.emit(SUBAGENT_DELEGATION_UPDATE_EVENT, payload);
|
|
311
|
+
return;
|
|
312
|
+
}
|
|
313
|
+
const payload = toDelegationUpdate(requestId, update);
|
|
314
|
+
if (payload) options.events.emit(PROMPT_TEMPLATE_SUBAGENT_UPDATE_EVENT, payload);
|
|
315
|
+
},
|
|
316
|
+
);
|
|
317
|
+
if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
|
|
318
|
+
if (structuredRequest && key) {
|
|
319
|
+
emitTerminal(key, toSubagentDelegationResponse(structuredRequest, result, controller.signal.aborted));
|
|
320
|
+
} else if (legacyRequest) {
|
|
321
|
+
options.events.emit(
|
|
322
|
+
PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT,
|
|
323
|
+
controller.signal.aborted
|
|
324
|
+
? { ...legacyRequest, messages: [], isError: true, errorText: "Delegated prompt cancelled." }
|
|
325
|
+
: toPromptTemplateResponse(legacyRequest, result),
|
|
326
|
+
);
|
|
327
|
+
}
|
|
328
|
+
} catch (error) {
|
|
329
|
+
if (key ? !ownsAttempt(key, controller) : !ownsLegacyRequest(requestId, controller)) return;
|
|
330
|
+
if (structuredRequest && key) {
|
|
331
|
+
emitTerminal(key, {
|
|
332
|
+
requestId,
|
|
333
|
+
ownerRunId: structuredRequest.ownerRunId,
|
|
334
|
+
nodeId: structuredRequest.nodeId,
|
|
335
|
+
status: controller.signal.aborted ? "cancelled" : "failed",
|
|
336
|
+
...(controller.signal.aborted ? {} : { error: error instanceof Error ? error.message : String(error) }),
|
|
337
|
+
});
|
|
338
|
+
} else if (legacyRequest) {
|
|
339
|
+
options.events.emit(PROMPT_TEMPLATE_SUBAGENT_RESPONSE_EVENT, {
|
|
340
|
+
...legacyRequest,
|
|
341
|
+
messages: [],
|
|
342
|
+
isError: true,
|
|
343
|
+
errorText: error instanceof Error ? error.message : String(error),
|
|
344
|
+
} satisfies PromptTemplateDelegationResponse);
|
|
345
|
+
}
|
|
346
|
+
} finally {
|
|
347
|
+
if (key) {
|
|
348
|
+
if (attemptControllers.get(key) === controller) attemptControllers.delete(key);
|
|
349
|
+
} else if (legacyControllers.get(requestId) === controller) legacyControllers.delete(requestId);
|
|
350
|
+
if (structuredRequest) {
|
|
351
|
+
const ownedNodeKey = nodeKey(structuredRequest.ownerRunId, structuredRequest.nodeId);
|
|
352
|
+
if (activeOwnedNodes.get(ownedNodeKey)?.controller === controller) activeOwnedNodes.delete(ownedNodeKey);
|
|
353
|
+
}
|
|
354
|
+
}
|
|
355
|
+
});
|
|
356
|
+
|
|
357
|
+
return {
|
|
358
|
+
cancelAll: () => {
|
|
359
|
+
for (const controller of legacyControllers.values()) controller.abort();
|
|
360
|
+
for (const controller of attemptControllers.values()) controller.abort();
|
|
361
|
+
legacyControllers.clear();
|
|
362
|
+
attemptControllers.clear();
|
|
363
|
+
pendingLegacyCancels.clear();
|
|
364
|
+
pendingAttemptCancels.clear();
|
|
365
|
+
activeOwnedNodes.clear();
|
|
366
|
+
settledAttempts.clear();
|
|
367
|
+
identitySaturated = false;
|
|
368
|
+
},
|
|
369
|
+
dispose: () => {
|
|
370
|
+
disposed = true;
|
|
371
|
+
for (const controller of legacyControllers.values()) controller.abort();
|
|
372
|
+
for (const controller of attemptControllers.values()) controller.abort();
|
|
373
|
+
legacyControllers.clear();
|
|
374
|
+
attemptControllers.clear();
|
|
375
|
+
for (const unsubscribe of subscriptions) unsubscribe();
|
|
376
|
+
subscriptions.length = 0;
|
|
377
|
+
pendingLegacyCancels.clear();
|
|
378
|
+
pendingAttemptCancels.clear();
|
|
379
|
+
activeOwnedNodes.clear();
|
|
380
|
+
settledAttempts.clear();
|
|
381
|
+
},
|
|
382
|
+
};
|
|
383
|
+
}
|