@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,434 @@
|
|
|
1
|
+
import {
|
|
2
|
+
type SubagentDelegationRequest,
|
|
3
|
+
type SubagentDelegationResponse,
|
|
4
|
+
type SubagentDelegationStatus,
|
|
5
|
+
type SubagentDelegationThinking,
|
|
6
|
+
type SubagentDelegationUpdate,
|
|
7
|
+
type SubagentDelegationValue,
|
|
8
|
+
} from "../api/delegation.ts";
|
|
9
|
+
import type { AcceptanceInput, AgentContract, EffectsProjection, ExecutionProjection, JsonSchemaObject, ReviewProjection, ToolBudgetConfig, TurnBudgetConfig, Usage } from "../shared/types.ts";
|
|
10
|
+
import { cloneJsonWithinByteLimit } from "./delegation-json.ts";
|
|
11
|
+
|
|
12
|
+
export interface PromptTemplateDelegationRequest {
|
|
13
|
+
requestId: string;
|
|
14
|
+
agent: string;
|
|
15
|
+
task: string;
|
|
16
|
+
context: "fresh" | "fork";
|
|
17
|
+
model: string;
|
|
18
|
+
cwd: string;
|
|
19
|
+
}
|
|
20
|
+
|
|
21
|
+
export interface PromptTemplateDelegationResponse extends PromptTemplateDelegationRequest {
|
|
22
|
+
messages: unknown[];
|
|
23
|
+
contentText?: string;
|
|
24
|
+
isError: boolean;
|
|
25
|
+
errorText?: string;
|
|
26
|
+
}
|
|
27
|
+
|
|
28
|
+
interface PromptTemplateDelegationTaskProgress {
|
|
29
|
+
index?: number;
|
|
30
|
+
agent: string;
|
|
31
|
+
status?: string;
|
|
32
|
+
currentTool?: string;
|
|
33
|
+
currentToolArgs?: string;
|
|
34
|
+
recentOutput?: string;
|
|
35
|
+
recentOutputLines?: string[];
|
|
36
|
+
recentTools?: Array<{ tool: string; args: string }>;
|
|
37
|
+
model?: string;
|
|
38
|
+
toolCount?: number;
|
|
39
|
+
durationMs?: number;
|
|
40
|
+
tokens?: number;
|
|
41
|
+
}
|
|
42
|
+
|
|
43
|
+
export interface PromptTemplateDelegationUpdate {
|
|
44
|
+
requestId: string;
|
|
45
|
+
runId?: string;
|
|
46
|
+
currentTool?: string;
|
|
47
|
+
currentToolArgs?: string;
|
|
48
|
+
recentOutput?: string;
|
|
49
|
+
recentOutputLines?: string[];
|
|
50
|
+
recentTools?: Array<{ tool: string; args: string }>;
|
|
51
|
+
model?: string;
|
|
52
|
+
toolCount?: number;
|
|
53
|
+
durationMs?: number;
|
|
54
|
+
tokens?: number;
|
|
55
|
+
taskProgress?: PromptTemplateDelegationTaskProgress[];
|
|
56
|
+
}
|
|
57
|
+
|
|
58
|
+
interface DelegationAcceptanceSnapshot {
|
|
59
|
+
status: string;
|
|
60
|
+
evidenceStatus?: string;
|
|
61
|
+
explicit?: boolean;
|
|
62
|
+
}
|
|
63
|
+
|
|
64
|
+
export interface PromptTemplateBridgeResult {
|
|
65
|
+
isError?: boolean;
|
|
66
|
+
content?: unknown;
|
|
67
|
+
details?: {
|
|
68
|
+
mode?: "single" | "parallel" | "chain" | "workflow" | "management";
|
|
69
|
+
runId?: string;
|
|
70
|
+
timedOut?: boolean;
|
|
71
|
+
stopped?: boolean;
|
|
72
|
+
results?: Array<{
|
|
73
|
+
agent?: string;
|
|
74
|
+
messages?: unknown[];
|
|
75
|
+
finalOutput?: string;
|
|
76
|
+
toolCalls?: Array<{ text?: string; expandedText?: string }>;
|
|
77
|
+
exitCode?: number;
|
|
78
|
+
error?: string;
|
|
79
|
+
model?: string;
|
|
80
|
+
thinking?: string;
|
|
81
|
+
structuredOutput?: unknown;
|
|
82
|
+
interrupted?: boolean;
|
|
83
|
+
timedOut?: boolean;
|
|
84
|
+
stopped?: boolean;
|
|
85
|
+
turnBudgetExceeded?: boolean;
|
|
86
|
+
toolBudgetBlocked?: boolean;
|
|
87
|
+
structuredOutputFailed?: boolean;
|
|
88
|
+
savedOutputPath?: string;
|
|
89
|
+
sessionFile?: string;
|
|
90
|
+
agentContract?: AgentContract;
|
|
91
|
+
execution?: ExecutionProjection;
|
|
92
|
+
acceptance?: DelegationAcceptanceSnapshot;
|
|
93
|
+
review?: ReviewProjection;
|
|
94
|
+
effects?: EffectsProjection;
|
|
95
|
+
usage?: Usage;
|
|
96
|
+
progressSummary?: { toolCount?: number; durationMs?: number; tokens?: number };
|
|
97
|
+
skillsWarning?: string;
|
|
98
|
+
outputSaveError?: string;
|
|
99
|
+
transcriptError?: string;
|
|
100
|
+
}>;
|
|
101
|
+
progress?: Array<{
|
|
102
|
+
index?: number;
|
|
103
|
+
agent?: string;
|
|
104
|
+
status?: string;
|
|
105
|
+
currentTool?: string;
|
|
106
|
+
currentToolArgs?: string;
|
|
107
|
+
recentOutput?: string[];
|
|
108
|
+
recentTools?: Array<{ tool?: string; args?: string }>;
|
|
109
|
+
toolCount?: number;
|
|
110
|
+
durationMs?: number;
|
|
111
|
+
tokens?: number;
|
|
112
|
+
}>;
|
|
113
|
+
};
|
|
114
|
+
}
|
|
115
|
+
|
|
116
|
+
export interface DelegatedSubagentExecutionParams {
|
|
117
|
+
agent?: string;
|
|
118
|
+
task?: string;
|
|
119
|
+
context: "fresh" | "fork";
|
|
120
|
+
model?: string;
|
|
121
|
+
cwd: string;
|
|
122
|
+
timeoutMs?: number;
|
|
123
|
+
turnBudget?: TurnBudgetConfig;
|
|
124
|
+
/** Internal-only strict turn-boundary enforcement for structured foreground delegation. */
|
|
125
|
+
enforceHardTurnLimit?: boolean;
|
|
126
|
+
toolBudget?: ToolBudgetConfig;
|
|
127
|
+
skill?: string | string[] | boolean;
|
|
128
|
+
output?: string | boolean;
|
|
129
|
+
outputMode?: "inline" | "file-only";
|
|
130
|
+
outputSchema?: JsonSchemaObject;
|
|
131
|
+
agentContract?: AgentContract;
|
|
132
|
+
acceptance?: AcceptanceInput;
|
|
133
|
+
artifacts?: boolean;
|
|
134
|
+
/** Internal-only thinking override accepted by executeDelegated. */
|
|
135
|
+
delegatedThinkingOverride?: SubagentDelegationThinking;
|
|
136
|
+
/** Internal-only capability accepted and stripped by executeDelegated. */
|
|
137
|
+
delegatedAllowZeroToolBudget?: true;
|
|
138
|
+
async: false;
|
|
139
|
+
foregroundOnly: true;
|
|
140
|
+
clarify: false;
|
|
141
|
+
}
|
|
142
|
+
|
|
143
|
+
export function parsePromptTemplateRequest(data: unknown): PromptTemplateDelegationRequest | undefined {
|
|
144
|
+
if (!data || typeof data !== "object") return undefined;
|
|
145
|
+
const value = data as Partial<PromptTemplateDelegationRequest> & { tasks?: unknown; worktree?: unknown };
|
|
146
|
+
if (value.tasks !== undefined || value.worktree !== undefined) return undefined;
|
|
147
|
+
if (typeof value.requestId !== "string" || !value.requestId) return undefined;
|
|
148
|
+
if (typeof value.agent !== "string" || !value.agent) return undefined;
|
|
149
|
+
if (typeof value.task !== "string" || !value.task) return undefined;
|
|
150
|
+
if (typeof value.model !== "string" || !value.model) return undefined;
|
|
151
|
+
if (typeof value.cwd !== "string" || !value.cwd) return undefined;
|
|
152
|
+
if (value.context !== "fresh" && value.context !== "fork") return undefined;
|
|
153
|
+
return {
|
|
154
|
+
requestId: value.requestId,
|
|
155
|
+
agent: value.agent,
|
|
156
|
+
task: value.task,
|
|
157
|
+
context: value.context,
|
|
158
|
+
model: value.model,
|
|
159
|
+
cwd: value.cwd,
|
|
160
|
+
};
|
|
161
|
+
}
|
|
162
|
+
|
|
163
|
+
function firstTextContent(content: unknown): string | undefined {
|
|
164
|
+
if (!Array.isArray(content)) return undefined;
|
|
165
|
+
for (const part of content) {
|
|
166
|
+
if (!part || typeof part !== "object") continue;
|
|
167
|
+
if ((part as { type?: string }).type !== "text") continue;
|
|
168
|
+
const text = (part as { text?: unknown }).text;
|
|
169
|
+
if (typeof text === "string" && text.trim()) return text.trim();
|
|
170
|
+
}
|
|
171
|
+
return undefined;
|
|
172
|
+
}
|
|
173
|
+
|
|
174
|
+
function filterRecentOutput(lines: string[] | undefined): string[] | undefined {
|
|
175
|
+
if (!lines || lines.length === 0) return undefined;
|
|
176
|
+
const filtered = lines.filter((line) => typeof line === "string" && line.trim() && line.trim() !== "(running...)");
|
|
177
|
+
if (filtered.length === 0) return undefined;
|
|
178
|
+
return filtered;
|
|
179
|
+
}
|
|
180
|
+
|
|
181
|
+
function sanitizeRecentTools(
|
|
182
|
+
tools: Array<{ tool?: string; args?: string }> | undefined,
|
|
183
|
+
): Array<{ tool: string; args: string }> | undefined {
|
|
184
|
+
if (!tools || tools.length === 0) return undefined;
|
|
185
|
+
const sanitized = tools.flatMap((entry) => {
|
|
186
|
+
if (typeof entry.tool !== "string" || entry.tool.trim().length === 0) return [];
|
|
187
|
+
return [{
|
|
188
|
+
tool: entry.tool,
|
|
189
|
+
args: typeof entry.args === "string" ? entry.args : String(entry.args ?? ""),
|
|
190
|
+
}];
|
|
191
|
+
});
|
|
192
|
+
return sanitized.length > 0 ? sanitized : undefined;
|
|
193
|
+
}
|
|
194
|
+
|
|
195
|
+
function resolveProgressModel(
|
|
196
|
+
update: PromptTemplateBridgeResult,
|
|
197
|
+
entry: { index?: number; agent?: string },
|
|
198
|
+
): string | undefined {
|
|
199
|
+
const results = update.details?.results;
|
|
200
|
+
if (!results || results.length === 0) return undefined;
|
|
201
|
+
if (typeof entry.index === "number" && entry.index >= 0) {
|
|
202
|
+
const byIndex = results[entry.index];
|
|
203
|
+
if (typeof byIndex?.model === "string") return byIndex.model;
|
|
204
|
+
}
|
|
205
|
+
if (entry.agent) {
|
|
206
|
+
const byAgent = results.find((result) => result.agent === entry.agent && typeof result.model === "string");
|
|
207
|
+
if (byAgent?.model) return byAgent.model;
|
|
208
|
+
}
|
|
209
|
+
const firstWithModel = results.find((result) => typeof result.model === "string");
|
|
210
|
+
return firstWithModel?.model;
|
|
211
|
+
}
|
|
212
|
+
|
|
213
|
+
function toolCallNameFromSummary(summary: { text?: string; expandedText?: string }): string | undefined {
|
|
214
|
+
const text = typeof summary.expandedText === "string" && summary.expandedText.trim().length > 0
|
|
215
|
+
? summary.expandedText.trim()
|
|
216
|
+
: typeof summary.text === "string"
|
|
217
|
+
? summary.text.trim()
|
|
218
|
+
: "";
|
|
219
|
+
if (!text) return undefined;
|
|
220
|
+
if (text.startsWith("$ ")) return "bash";
|
|
221
|
+
return text.match(/^[A-Za-z_][\w.-]*/)?.[0];
|
|
222
|
+
}
|
|
223
|
+
|
|
224
|
+
function buildDelegationMessages(
|
|
225
|
+
result: { messages?: unknown[]; finalOutput?: string; toolCalls?: Array<{ text?: string; expandedText?: string }> },
|
|
226
|
+
fallbackText?: string,
|
|
227
|
+
): unknown[] {
|
|
228
|
+
if (Array.isArray(result.messages) && result.messages.length > 0) return result.messages;
|
|
229
|
+
const toolCallParts = (result.toolCalls ?? []).flatMap((summary) => {
|
|
230
|
+
const name = toolCallNameFromSummary(summary);
|
|
231
|
+
return name ? [{ type: "toolCall", name, arguments: { summary: summary.expandedText ?? summary.text ?? "" } }] : [];
|
|
232
|
+
});
|
|
233
|
+
const text = typeof result.finalOutput === "string" && result.finalOutput.trim().length > 0
|
|
234
|
+
? result.finalOutput.trim()
|
|
235
|
+
: fallbackText;
|
|
236
|
+
const content = [
|
|
237
|
+
...toolCallParts,
|
|
238
|
+
...(text ? [{ type: "text", text }] : []),
|
|
239
|
+
];
|
|
240
|
+
if (content.length === 0) return [];
|
|
241
|
+
return [{ role: "assistant", content }];
|
|
242
|
+
}
|
|
243
|
+
|
|
244
|
+
export function toDelegationUpdate(requestId: string, update: PromptTemplateBridgeResult): PromptTemplateDelegationUpdate | undefined {
|
|
245
|
+
const progress = update.details?.progress?.[0];
|
|
246
|
+
const taskProgress = update.details?.progress?.map((entry) => {
|
|
247
|
+
const lastOutput = entry.recentOutput?.[entry.recentOutput.length - 1];
|
|
248
|
+
const safeLastOutput =
|
|
249
|
+
typeof lastOutput === "string" && lastOutput.trim() && lastOutput !== "(running...)"
|
|
250
|
+
? lastOutput
|
|
251
|
+
: undefined;
|
|
252
|
+
return {
|
|
253
|
+
index: entry.index,
|
|
254
|
+
agent: entry.agent ?? "delegate",
|
|
255
|
+
status: entry.status,
|
|
256
|
+
currentTool: entry.currentTool,
|
|
257
|
+
currentToolArgs: entry.currentToolArgs,
|
|
258
|
+
recentOutput: safeLastOutput,
|
|
259
|
+
recentOutputLines: filterRecentOutput(entry.recentOutput),
|
|
260
|
+
recentTools: sanitizeRecentTools(entry.recentTools),
|
|
261
|
+
model: resolveProgressModel(update, entry),
|
|
262
|
+
toolCount: entry.toolCount,
|
|
263
|
+
durationMs: entry.durationMs,
|
|
264
|
+
tokens: entry.tokens,
|
|
265
|
+
};
|
|
266
|
+
});
|
|
267
|
+
if (!progress && (!taskProgress || taskProgress.length === 0)) return undefined;
|
|
268
|
+
const lastOutput = progress?.recentOutput?.[progress.recentOutput.length - 1];
|
|
269
|
+
const safeLastOutput =
|
|
270
|
+
typeof lastOutput === "string" && lastOutput.trim() && lastOutput !== "(running...)"
|
|
271
|
+
? lastOutput
|
|
272
|
+
: undefined;
|
|
273
|
+
return {
|
|
274
|
+
requestId,
|
|
275
|
+
...(update.details?.runId ? { runId: update.details.runId } : {}),
|
|
276
|
+
currentTool: progress?.currentTool,
|
|
277
|
+
currentToolArgs: progress?.currentToolArgs,
|
|
278
|
+
recentOutput: safeLastOutput,
|
|
279
|
+
recentOutputLines: filterRecentOutput(progress?.recentOutput),
|
|
280
|
+
recentTools: sanitizeRecentTools(progress?.recentTools),
|
|
281
|
+
model: progress ? resolveProgressModel(update, progress) : undefined,
|
|
282
|
+
toolCount: progress?.toolCount,
|
|
283
|
+
durationMs: progress?.durationMs,
|
|
284
|
+
tokens: progress?.tokens,
|
|
285
|
+
taskProgress,
|
|
286
|
+
};
|
|
287
|
+
}
|
|
288
|
+
|
|
289
|
+
export function toSubagentDelegationExecutionParams(request: SubagentDelegationRequest): DelegatedSubagentExecutionParams {
|
|
290
|
+
return {
|
|
291
|
+
agent: request.agent,
|
|
292
|
+
task: request.task,
|
|
293
|
+
context: request.context,
|
|
294
|
+
cwd: request.cwd,
|
|
295
|
+
model: request.model,
|
|
296
|
+
timeoutMs: request.timeoutMs,
|
|
297
|
+
turnBudget: request.turnBudget,
|
|
298
|
+
enforceHardTurnLimit: true,
|
|
299
|
+
toolBudget: request.toolBudget,
|
|
300
|
+
skill: request.skill,
|
|
301
|
+
output: false,
|
|
302
|
+
...(request.result.kind === "structured" ? { outputSchema: request.result.schema } : {}),
|
|
303
|
+
acceptance: false,
|
|
304
|
+
artifacts: request.artifacts,
|
|
305
|
+
delegatedThinkingOverride: request.thinking,
|
|
306
|
+
delegatedAllowZeroToolBudget: true,
|
|
307
|
+
async: false,
|
|
308
|
+
foregroundOnly: true,
|
|
309
|
+
clarify: false,
|
|
310
|
+
};
|
|
311
|
+
}
|
|
312
|
+
|
|
313
|
+
export function toSubagentDelegationUpdate(
|
|
314
|
+
request: SubagentDelegationRequest,
|
|
315
|
+
result: PromptTemplateBridgeResult,
|
|
316
|
+
): SubagentDelegationUpdate | undefined {
|
|
317
|
+
const legacy = toDelegationUpdate(request.requestId, result);
|
|
318
|
+
if (!legacy) return undefined;
|
|
319
|
+
return {
|
|
320
|
+
requestId: request.requestId,
|
|
321
|
+
ownerRunId: request.ownerRunId,
|
|
322
|
+
nodeId: request.nodeId,
|
|
323
|
+
...(legacy.runId ? { runId: legacy.runId } : {}),
|
|
324
|
+
...(legacy.currentTool ? { currentTool: legacy.currentTool } : {}),
|
|
325
|
+
...(legacy.currentToolArgs ? { currentToolArgs: legacy.currentToolArgs } : {}),
|
|
326
|
+
...(legacy.recentOutput ? { recentOutput: legacy.recentOutput } : {}),
|
|
327
|
+
...(legacy.recentOutputLines ? { recentOutputLines: legacy.recentOutputLines } : {}),
|
|
328
|
+
...(legacy.recentTools ? { recentTools: legacy.recentTools } : {}),
|
|
329
|
+
...(legacy.model ? { model: legacy.model } : {}),
|
|
330
|
+
...(typeof legacy.toolCount === "number" ? { toolCount: legacy.toolCount } : {}),
|
|
331
|
+
...(typeof legacy.durationMs === "number" ? { durationMs: legacy.durationMs } : {}),
|
|
332
|
+
...(typeof legacy.tokens === "number" ? { tokens: legacy.tokens } : {}),
|
|
333
|
+
};
|
|
334
|
+
}
|
|
335
|
+
|
|
336
|
+
function resolveSubagentDelegationStatus(
|
|
337
|
+
result: PromptTemplateBridgeResult,
|
|
338
|
+
aborted: boolean,
|
|
339
|
+
): SubagentDelegationStatus {
|
|
340
|
+
if (aborted) return "cancelled";
|
|
341
|
+
const child = result.details?.results?.[0];
|
|
342
|
+
if (!child) return "failed";
|
|
343
|
+
if (result.details?.timedOut || child.timedOut) return "timed_out";
|
|
344
|
+
if (child?.structuredOutputFailed) return "structured_output_failed";
|
|
345
|
+
if (child?.turnBudgetExceeded) return "turn_budget_exhausted";
|
|
346
|
+
if (child?.toolBudgetBlocked) return "tool_budget_exhausted";
|
|
347
|
+
if (child?.acceptance?.status === "rejected" && child.acceptance.explicit) return "acceptance_failed";
|
|
348
|
+
if (result.details?.stopped || child?.stopped || child?.interrupted) return "interrupted";
|
|
349
|
+
if (result.isError || child?.error || (typeof child?.exitCode === "number" && child.exitCode !== 0)) return "failed";
|
|
350
|
+
return "completed";
|
|
351
|
+
}
|
|
352
|
+
|
|
353
|
+
const MAX_RESULT_BYTES = 1024 * 1024;
|
|
354
|
+
|
|
355
|
+
export function toSubagentDelegationResponse(
|
|
356
|
+
request: SubagentDelegationRequest,
|
|
357
|
+
result: PromptTemplateBridgeResult,
|
|
358
|
+
aborted: boolean,
|
|
359
|
+
): SubagentDelegationResponse {
|
|
360
|
+
const child = result.details?.results?.[0];
|
|
361
|
+
const progress = child?.progressSummary ?? result.details?.progress?.[0];
|
|
362
|
+
let status = resolveSubagentDelegationStatus(result, aborted);
|
|
363
|
+
let error = child?.error ?? (status === "failed" ? firstTextContent(result.content) : undefined);
|
|
364
|
+
let projectedResult: SubagentDelegationValue | undefined;
|
|
365
|
+
if (status === "completed") {
|
|
366
|
+
if (request.result.kind === "text") {
|
|
367
|
+
if (typeof child?.finalOutput !== "string") {
|
|
368
|
+
status = "failed";
|
|
369
|
+
error = "Delegated subagent did not capture a text result.";
|
|
370
|
+
} else if (Buffer.byteLength(child.finalOutput, "utf8") > MAX_RESULT_BYTES) {
|
|
371
|
+
status = "failed";
|
|
372
|
+
error = "Delegated text result exceeds 1 MiB when UTF-8 encoded.";
|
|
373
|
+
} else {
|
|
374
|
+
projectedResult = { kind: "text", text: child.finalOutput };
|
|
375
|
+
}
|
|
376
|
+
} else if (child?.structuredOutput === undefined) {
|
|
377
|
+
status = "failed";
|
|
378
|
+
error = "Delegated subagent did not capture the requested structured result.";
|
|
379
|
+
} else {
|
|
380
|
+
const inspected = cloneJsonWithinByteLimit(child.structuredOutput, MAX_RESULT_BYTES);
|
|
381
|
+
if (inspected.ok === false) {
|
|
382
|
+
status = "failed";
|
|
383
|
+
error = inspected.reason === "too_large"
|
|
384
|
+
? "Delegated structured result exceeds 1 MiB when encoded."
|
|
385
|
+
: "Delegated structured result is not plain JSON data.";
|
|
386
|
+
} else {
|
|
387
|
+
projectedResult = { kind: "structured", value: inspected.value };
|
|
388
|
+
}
|
|
389
|
+
}
|
|
390
|
+
}
|
|
391
|
+
const usage = child?.usage;
|
|
392
|
+
const childLaunchContractDigest = (child as { launchContractDigest?: string } | undefined)?.launchContractDigest;
|
|
393
|
+
return {
|
|
394
|
+
requestId: request.requestId,
|
|
395
|
+
ownerRunId: request.ownerRunId,
|
|
396
|
+
nodeId: request.nodeId,
|
|
397
|
+
status,
|
|
398
|
+
...(error ? { error } : {}),
|
|
399
|
+
...(result.details?.runId ? { runId: result.details.runId } : {}),
|
|
400
|
+
...(child?.agent ? { agent: child.agent } : {}),
|
|
401
|
+
...(child?.model ? { model: child.model } : {}),
|
|
402
|
+
...(child?.thinking ? { thinking: child.thinking } : {}),
|
|
403
|
+
...(typeof child?.exitCode === "number" ? { exitCode: child.exitCode } : {}),
|
|
404
|
+
...(childLaunchContractDigest ? { launchContractDigest: childLaunchContractDigest } : {}),
|
|
405
|
+
...(projectedResult ? { result: projectedResult } : {}),
|
|
406
|
+
...(usage ? {
|
|
407
|
+
usage: {
|
|
408
|
+
input: usage.input,
|
|
409
|
+
output: usage.output,
|
|
410
|
+
cacheRead: usage.cacheRead,
|
|
411
|
+
cacheWrite: usage.cacheWrite,
|
|
412
|
+
cost: usage.cost,
|
|
413
|
+
turns: usage.turns,
|
|
414
|
+
toolCalls: progress?.toolCount ?? 0,
|
|
415
|
+
durationMs: progress?.durationMs ?? 0,
|
|
416
|
+
},
|
|
417
|
+
} : {}),
|
|
418
|
+
};
|
|
419
|
+
}
|
|
420
|
+
|
|
421
|
+
export function toPromptTemplateResponse(
|
|
422
|
+
request: PromptTemplateDelegationRequest,
|
|
423
|
+
result: PromptTemplateBridgeResult,
|
|
424
|
+
): PromptTemplateDelegationResponse {
|
|
425
|
+
const contentText = firstTextContent(result.content);
|
|
426
|
+
const messages = buildDelegationMessages(result.details?.results?.[0] ?? {}, contentText);
|
|
427
|
+
return {
|
|
428
|
+
...request,
|
|
429
|
+
messages,
|
|
430
|
+
...(contentText ? { contentText } : {}),
|
|
431
|
+
isError: result.isError === true,
|
|
432
|
+
errorText: result.isError ? contentText : undefined,
|
|
433
|
+
};
|
|
434
|
+
}
|
|
@@ -0,0 +1,108 @@
|
|
|
1
|
+
const MAX_JSON_DEPTH = 64;
|
|
2
|
+
const MAX_JSON_ENTRIES = 100_000;
|
|
3
|
+
|
|
4
|
+
export type BoundedJsonClone =
|
|
5
|
+
| { ok: true; value: unknown; encodedBytes: number }
|
|
6
|
+
| { ok: false; reason: "invalid" | "too_large" };
|
|
7
|
+
|
|
8
|
+
/** Clone plain JSON data without invoking getters or toJSON hooks. */
|
|
9
|
+
export function cloneJsonWithinByteLimit(input: unknown, maxBytes: number): BoundedJsonClone {
|
|
10
|
+
let minimumBytes = 0;
|
|
11
|
+
let entries = 0;
|
|
12
|
+
const active = new WeakSet<object>();
|
|
13
|
+
|
|
14
|
+
const addMinimumBytes = (bytes: number): void => {
|
|
15
|
+
minimumBytes += bytes;
|
|
16
|
+
if (minimumBytes > maxBytes) throw new RangeError("too_large");
|
|
17
|
+
};
|
|
18
|
+
|
|
19
|
+
const visit = (value: unknown, depth: number): unknown => {
|
|
20
|
+
if (depth > MAX_JSON_DEPTH) throw new TypeError("invalid");
|
|
21
|
+
if (value === null) {
|
|
22
|
+
addMinimumBytes(4);
|
|
23
|
+
return null;
|
|
24
|
+
}
|
|
25
|
+
if (typeof value === "boolean") {
|
|
26
|
+
addMinimumBytes(value ? 4 : 5);
|
|
27
|
+
return value;
|
|
28
|
+
}
|
|
29
|
+
if (typeof value === "number") {
|
|
30
|
+
if (!Number.isFinite(value)) throw new TypeError("invalid");
|
|
31
|
+
const encoded = JSON.stringify(Object.is(value, -0) ? 0 : value);
|
|
32
|
+
addMinimumBytes(Buffer.byteLength(encoded, "utf8"));
|
|
33
|
+
return Object.is(value, -0) ? 0 : value;
|
|
34
|
+
}
|
|
35
|
+
if (typeof value === "string") {
|
|
36
|
+
// Quoting and escaping can only increase the encoded size.
|
|
37
|
+
addMinimumBytes(Buffer.byteLength(value, "utf8") + 2);
|
|
38
|
+
return value;
|
|
39
|
+
}
|
|
40
|
+
if (typeof value !== "object") throw new TypeError("invalid");
|
|
41
|
+
|
|
42
|
+
const object = value as object;
|
|
43
|
+
if (active.has(object)) throw new TypeError("invalid");
|
|
44
|
+
active.add(object);
|
|
45
|
+
try {
|
|
46
|
+
const prototype = Object.getPrototypeOf(object);
|
|
47
|
+
const keys = Reflect.ownKeys(object);
|
|
48
|
+
if (Array.isArray(object)) {
|
|
49
|
+
if (prototype !== Array.prototype) throw new TypeError("invalid");
|
|
50
|
+
const lengthDescriptor = Object.getOwnPropertyDescriptor(object, "length");
|
|
51
|
+
if (!lengthDescriptor || !("value" in lengthDescriptor) || !Number.isSafeInteger(lengthDescriptor.value) || lengthDescriptor.value < 0) {
|
|
52
|
+
throw new TypeError("invalid");
|
|
53
|
+
}
|
|
54
|
+
const length = lengthDescriptor.value as number;
|
|
55
|
+
addMinimumBytes(2 + Math.max(0, length - 1));
|
|
56
|
+
const output: unknown[] = [];
|
|
57
|
+
for (const key of keys) {
|
|
58
|
+
if (typeof key === "symbol") throw new TypeError("invalid");
|
|
59
|
+
if (key === "length") continue;
|
|
60
|
+
if (!/^(?:0|[1-9][0-9]*)$/.test(key) || Number(key) >= length) throw new TypeError("invalid");
|
|
61
|
+
}
|
|
62
|
+
for (let index = 0; index < length; index++) {
|
|
63
|
+
const descriptor = Object.getOwnPropertyDescriptor(object, String(index));
|
|
64
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new TypeError("invalid");
|
|
65
|
+
entries++;
|
|
66
|
+
if (entries > MAX_JSON_ENTRIES) throw new TypeError("invalid");
|
|
67
|
+
output.push(visit(descriptor.value, depth + 1));
|
|
68
|
+
}
|
|
69
|
+
return output;
|
|
70
|
+
}
|
|
71
|
+
|
|
72
|
+
if (prototype !== Object.prototype && prototype !== null) throw new TypeError("invalid");
|
|
73
|
+
addMinimumBytes(2 + Math.max(0, keys.length - 1));
|
|
74
|
+
const output: Record<string, unknown> = {};
|
|
75
|
+
for (const key of keys) {
|
|
76
|
+
if (typeof key === "symbol") throw new TypeError("invalid");
|
|
77
|
+
const descriptor = Object.getOwnPropertyDescriptor(object, key);
|
|
78
|
+
if (!descriptor || !("value" in descriptor) || !descriptor.enumerable) throw new TypeError("invalid");
|
|
79
|
+
entries++;
|
|
80
|
+
if (entries > MAX_JSON_ENTRIES) throw new TypeError("invalid");
|
|
81
|
+
addMinimumBytes(Buffer.byteLength(JSON.stringify(key), "utf8") + 1);
|
|
82
|
+
Object.defineProperty(output, key, {
|
|
83
|
+
value: visit(descriptor.value, depth + 1),
|
|
84
|
+
enumerable: true,
|
|
85
|
+
configurable: true,
|
|
86
|
+
writable: true,
|
|
87
|
+
});
|
|
88
|
+
}
|
|
89
|
+
return output;
|
|
90
|
+
} finally {
|
|
91
|
+
active.delete(object);
|
|
92
|
+
}
|
|
93
|
+
};
|
|
94
|
+
|
|
95
|
+
try {
|
|
96
|
+
const value = visit(input, 0);
|
|
97
|
+
const encoded = JSON.stringify(value);
|
|
98
|
+
if (encoded === undefined) return { ok: false, reason: "invalid" };
|
|
99
|
+
const encodedBytes = Buffer.byteLength(encoded, "utf8");
|
|
100
|
+
if (encodedBytes > maxBytes) return { ok: false, reason: "too_large" };
|
|
101
|
+
return { ok: true, value, encodedBytes };
|
|
102
|
+
} catch (error) {
|
|
103
|
+
return {
|
|
104
|
+
ok: false,
|
|
105
|
+
reason: error instanceof RangeError && error.message === "too_large" ? "too_large" : "invalid",
|
|
106
|
+
};
|
|
107
|
+
}
|
|
108
|
+
}
|