@botbotgo/agent-harness 0.0.475 → 0.0.476

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.
Files changed (227) hide show
  1. package/README.md +3 -1234
  2. package/README.zh.md +3 -1191
  3. package/dist/acp.js +1 -1
  4. package/dist/api.js +1 -404
  5. package/dist/benchmark/checkpoint-resume-cost-benchmark.js +1 -55
  6. package/dist/benchmark/deepagent-local-model-benchmark.js +2 -35
  7. package/dist/benchmark/upstream-runtime-ab-benchmark.js +1 -179
  8. package/dist/cli/chat-interactive.js +25 -244
  9. package/dist/cli/chat-rendering.js +6 -100
  10. package/dist/cli/chat-stream.js +23 -512
  11. package/dist/cli/chat-ui.js +21 -199
  12. package/dist/cli/chat-workspace.js +2 -210
  13. package/dist/cli/main.js +21 -428
  14. package/dist/cli/managed-service-commands.js +9 -63
  15. package/dist/cli/managed-service.js +2 -137
  16. package/dist/cli/options-init-chat.js +1 -108
  17. package/dist/cli/options-runtime.js +1 -158
  18. package/dist/cli/options-serve.js +1 -282
  19. package/dist/cli/options.js +2 -19
  20. package/dist/cli/process-guards.js +1 -139
  21. package/dist/cli/request-tree.js +7 -296
  22. package/dist/cli/runtime-commands.js +12 -258
  23. package/dist/cli/runtime-output.js +16 -155
  24. package/dist/cli/server-commands.js +16 -270
  25. package/dist/cli/workspace.js +1 -67
  26. package/dist/cli.js +1 -7
  27. package/dist/client/acp.js +1 -1
  28. package/dist/client/in-process.js +1 -67
  29. package/dist/client/index.js +1 -2
  30. package/dist/client/types.js +0 -1
  31. package/dist/client.js +1 -1
  32. package/dist/contracts/core.js +1 -1
  33. package/dist/contracts/runtime-evaluation.js +0 -1
  34. package/dist/contracts/runtime-memory.js +0 -1
  35. package/dist/contracts/runtime-observability.js +0 -1
  36. package/dist/contracts/runtime-requests.js +0 -1
  37. package/dist/contracts/runtime-scheduling.js +0 -1
  38. package/dist/contracts/runtime.js +1 -27
  39. package/dist/contracts/types.js +1 -3
  40. package/dist/contracts/workspace.js +0 -1
  41. package/dist/flow/build-flow-graph.js +1 -50
  42. package/dist/flow/export-mermaid.js +2 -464
  43. package/dist/flow/export-sequence-mermaid.js +2 -325
  44. package/dist/flow/flow-graph-normalization.js +1 -214
  45. package/dist/flow/flow-graph-runtime.js +1 -107
  46. package/dist/flow/flow-graph-upstream.js +1 -494
  47. package/dist/flow/index.js +1 -3
  48. package/dist/flow/types.js +0 -1
  49. package/dist/index.js +1 -5
  50. package/dist/init-project.js +1 -1
  51. package/dist/knowledge/config.js +1 -32
  52. package/dist/knowledge/contracts.js +0 -1
  53. package/dist/knowledge/index.js +1 -2
  54. package/dist/knowledge/module.js +12 -909
  55. package/dist/knowledge/procedural/config.js +1 -125
  56. package/dist/knowledge/procedural/index.js +1 -2
  57. package/dist/knowledge/procedural/manager.js +9 -345
  58. package/dist/mcp.js +1 -2
  59. package/dist/package-version.d.ts +1 -1
  60. package/dist/package-version.js +1 -2
  61. package/dist/persistence/file-store.js +3 -758
  62. package/dist/persistence/sqlite-request-context-store.js +5 -54
  63. package/dist/persistence/sqlite-request-queue-store.js +10 -108
  64. package/dist/persistence/sqlite-runtime.js +1 -86
  65. package/dist/persistence/sqlite-store.js +62 -810
  66. package/dist/persistence/types.js +0 -1
  67. package/dist/projections/presentation.js +37 -206
  68. package/dist/projections/request-events.js +2 -502
  69. package/dist/projections/upstream-events.js +1 -201
  70. package/dist/protocol/a2a/http-discovery.js +1 -178
  71. package/dist/protocol/a2a/http-rpc.js +6 -622
  72. package/dist/protocol/a2a/http.js +1 -138
  73. package/dist/protocol/a2a/task-state.js +3 -317
  74. package/dist/protocol/acp/client.js +8 -294
  75. package/dist/protocol/acp/harness-client.js +1 -218
  76. package/dist/protocol/acp/http.js +5 -130
  77. package/dist/protocol/acp/server.js +1 -310
  78. package/dist/protocol/acp/stdio.js +2 -69
  79. package/dist/protocol/ag-ui/http.js +3 -378
  80. package/dist/protocol/mcp/server.js +1 -428
  81. package/dist/resource/backend/workspace-scoped-backend.js +1 -319
  82. package/dist/resource/isolation.js +1 -237
  83. package/dist/resource/mcp/tool-support.js +3 -296
  84. package/dist/resource/mcp-tool-support.js +1 -2
  85. package/dist/resource/providers/resource-provider.js +1 -215
  86. package/dist/resource/resource-impl.js +1 -3
  87. package/dist/resource/resource-types.js +0 -1
  88. package/dist/resource/resource.js +1 -1
  89. package/dist/resource/sources.js +1 -247
  90. package/dist/resource/tools/function-tool-resolver.js +2 -272
  91. package/dist/runtime/adapter/compat/deepagent-compat.js +1 -29
  92. package/dist/runtime/adapter/compat/openai-compatible.js +1 -55
  93. package/dist/runtime/adapter/direct-builtin-utility.js +2 -90
  94. package/dist/runtime/adapter/flow/execution-context.js +1 -71
  95. package/dist/runtime/adapter/flow/invocation-flow.js +8 -425
  96. package/dist/runtime/adapter/flow/invoke-runtime.js +1 -20
  97. package/dist/runtime/adapter/flow/stream-runtime.js +11 -1395
  98. package/dist/runtime/adapter/invocation-result.js +2 -473
  99. package/dist/runtime/adapter/local-tool-invocation.js +6 -638
  100. package/dist/runtime/adapter/middleware/context-hygiene.js +1 -83
  101. package/dist/runtime/adapter/middleware-assembly.js +5 -477
  102. package/dist/runtime/adapter/model/invocation-request.js +3 -183
  103. package/dist/runtime/adapter/model/message-assembly.js +1 -28
  104. package/dist/runtime/adapter/model/model-providers.js +23 -1115
  105. package/dist/runtime/adapter/model/prompted-json-tool-call-capture.js +1 -40
  106. package/dist/runtime/adapter/model/prompted-json-tool-policy.js +1 -22
  107. package/dist/runtime/adapter/resilience.js +1 -104
  108. package/dist/runtime/adapter/runtime-adapter-support.js +3 -141
  109. package/dist/runtime/adapter/runtime-shell.js +5 -166
  110. package/dist/runtime/adapter/stream-event-projection.js +2 -622
  111. package/dist/runtime/adapter/stream-text-consumption.js +1 -18
  112. package/dist/runtime/adapter/terminal-status.js +2 -67
  113. package/dist/runtime/adapter/tool/builtin-middleware-tools.js +6 -627
  114. package/dist/runtime/adapter/tool/declared-middleware.js +1 -154
  115. package/dist/runtime/adapter/tool/interrupt-policy.js +1 -34
  116. package/dist/runtime/adapter/tool/provider-tool.js +1 -25
  117. package/dist/runtime/adapter/tool/resolved-tool.js +1 -225
  118. package/dist/runtime/adapter/tool/tool-arguments.js +3 -486
  119. package/dist/runtime/adapter/tool/tool-hitl.js +1 -346
  120. package/dist/runtime/adapter/tool/tool-name-mapping.js +1 -128
  121. package/dist/runtime/adapter/tool/tool-output-artifacts.js +2 -88
  122. package/dist/runtime/adapter/tool/tool-replay.js +1 -37
  123. package/dist/runtime/adapter/tool-resolution.js +1 -86
  124. package/dist/runtime/adapter/upstream-configurable-keys.js +1 -2
  125. package/dist/runtime/agent-runtime-adapter.js +60 -2338
  126. package/dist/runtime/agent-runtime-assembly.js +7 -249
  127. package/dist/runtime/env/runtime-env.js +1 -62
  128. package/dist/runtime/harness/background-runtime.js +1 -8
  129. package/dist/runtime/harness/bindings.js +1 -58
  130. package/dist/runtime/harness/events/event-bus.js +1 -16
  131. package/dist/runtime/harness/events/event-sink.js +1 -61
  132. package/dist/runtime/harness/events/events.js +1 -80
  133. package/dist/runtime/harness/events/listener-runtime.js +1 -13
  134. package/dist/runtime/harness/events/runtime-event-operations.js +1 -9
  135. package/dist/runtime/harness/events/streaming.js +1 -100
  136. package/dist/runtime/harness/events/timeline.js +1 -52
  137. package/dist/runtime/harness/public-shapes.js +1 -186
  138. package/dist/runtime/harness/run/artifact-paths.js +1 -15
  139. package/dist/runtime/harness/run/governance.js +1 -295
  140. package/dist/runtime/harness/run/helpers.js +1 -71
  141. package/dist/runtime/harness/run/inspection.js +1 -409
  142. package/dist/runtime/harness/run/operator-overview.js +1 -80
  143. package/dist/runtime/harness/run/queue-diagnostics.js +1 -15
  144. package/dist/runtime/harness/run/recovery.js +1 -162
  145. package/dist/runtime/harness/run/resources.js +1 -60
  146. package/dist/runtime/harness/run/resume.js +1 -56
  147. package/dist/runtime/harness/run/routing.js +1 -48
  148. package/dist/runtime/harness/run/run-lifecycle.js +1 -66
  149. package/dist/runtime/harness/run/run-operations.js +1 -217
  150. package/dist/runtime/harness/run/run-queue.js +1 -43
  151. package/dist/runtime/harness/run/run-slot-acquisition.js +1 -157
  152. package/dist/runtime/harness/run/session-records.js +1 -97
  153. package/dist/runtime/harness/run/start-run.js +1 -120
  154. package/dist/runtime/harness/run/startup-runtime.js +1 -69
  155. package/dist/runtime/harness/run/stream-run.js +8 -1418
  156. package/dist/runtime/harness/run/surface-semantics.js +1 -79
  157. package/dist/runtime/harness/runtime-defaults.js +1 -39
  158. package/dist/runtime/harness/system/boundary-analysis.js +1 -234
  159. package/dist/runtime/harness/system/health-monitor.js +1 -258
  160. package/dist/runtime/harness/system/inventory.js +1 -129
  161. package/dist/runtime/harness/system/mem0-ingestion-sync.js +5 -345
  162. package/dist/runtime/harness/system/policy-engine.js +1 -175
  163. package/dist/runtime/harness/system/runtime-memory-candidates.js +4 -110
  164. package/dist/runtime/harness/system/runtime-memory-consolidation.js +1 -51
  165. package/dist/runtime/harness/system/runtime-memory-manager.js +10 -693
  166. package/dist/runtime/harness/system/runtime-memory-policy.js +1 -155
  167. package/dist/runtime/harness/system/runtime-memory-records.js +11 -577
  168. package/dist/runtime/harness/system/runtime-memory-sync.js +5 -206
  169. package/dist/runtime/harness/system/session-memory-sync.js +3 -113
  170. package/dist/runtime/harness/system/skill-requirements.js +1 -112
  171. package/dist/runtime/harness/system/store.js +9 -365
  172. package/dist/runtime/harness/tool-gateway/index.js +1 -2
  173. package/dist/runtime/harness/tool-gateway/policy.js +1 -45
  174. package/dist/runtime/harness/tool-gateway/validation.js +1 -176
  175. package/dist/runtime/harness/tool-schema.js +1 -3
  176. package/dist/runtime/harness.js +3 -1490
  177. package/dist/runtime/index.js +1 -3
  178. package/dist/runtime/layout/runtime-layout.js +1 -31
  179. package/dist/runtime/maintenance/checkpoint-maintenance.js +2 -178
  180. package/dist/runtime/maintenance/file-checkpoint-saver.js +1 -106
  181. package/dist/runtime/maintenance/runtime-record-maintenance.js +2 -169
  182. package/dist/runtime/maintenance/sqlite-checkpoint-saver.js +4 -289
  183. package/dist/runtime/parsing/output-content.js +10 -550
  184. package/dist/runtime/parsing/output-parsing.js +1 -4
  185. package/dist/runtime/parsing/output-recovery.js +3 -213
  186. package/dist/runtime/parsing/output-tool-args.js +7 -663
  187. package/dist/runtime/parsing/stream-event-parsing.js +3 -362
  188. package/dist/runtime/prompts/runtime-prompts.js +4 -73
  189. package/dist/runtime/scheduling/system-schedule-manager.js +11 -532
  190. package/dist/runtime/skills/skill-metadata.js +1 -197
  191. package/dist/runtime/startup-tracing.js +2 -37
  192. package/dist/runtime/support/compiled-binding.js +1 -290
  193. package/dist/runtime/support/embedding-models.js +1 -118
  194. package/dist/runtime/support/harness-support.js +5 -137
  195. package/dist/runtime/support/llamaindex.js +1 -108
  196. package/dist/runtime/support/runtime-adapter-options.js +1 -29
  197. package/dist/runtime/support/runtime-factories.js +1 -51
  198. package/dist/runtime/support/vector-stores.js +9 -270
  199. package/dist/scaffold/init-project.js +54 -233
  200. package/dist/tooling/extensions.js +1 -311
  201. package/dist/tooling/module-loader.js +1 -55
  202. package/dist/tools.js +1 -176
  203. package/dist/utils/agent-display.js +1 -18
  204. package/dist/utils/bundled-text.js +4 -39
  205. package/dist/utils/compiled-binding.js +1 -33
  206. package/dist/utils/fs.js +2 -45
  207. package/dist/utils/id.js +1 -9
  208. package/dist/utils/message-content.js +1 -30
  209. package/dist/utils/object.js +1 -6
  210. package/dist/workspace/agent-binding-compiler.js +3 -613
  211. package/dist/workspace/compile.js +1 -472
  212. package/dist/workspace/framework-contract-validation.js +2 -322
  213. package/dist/workspace/index.js +1 -1
  214. package/dist/workspace/object-loader-paths.js +1 -71
  215. package/dist/workspace/object-loader-readers.js +1 -187
  216. package/dist/workspace/object-loader.js +1 -754
  217. package/dist/workspace/resource-compilers.js +1 -374
  218. package/dist/workspace/support/agent-capabilities.js +1 -37
  219. package/dist/workspace/support/agent-execution-config.js +1 -44
  220. package/dist/workspace/support/discovery.js +1 -147
  221. package/dist/workspace/support/source-collectors.js +1 -30
  222. package/dist/workspace/support/source-protocols.js +2 -192
  223. package/dist/workspace/support/workspace-ref-utils.js +1 -362
  224. package/dist/workspace/tool-hydration.js +1 -280
  225. package/dist/workspace/validate.js +1 -99
  226. package/dist/workspace/yaml-object-reader.js +1 -285
  227. package/package.json +7 -3
@@ -1,2338 +1,60 @@
1
- import path from "node:path";
2
- import { createHash } from "node:crypto";
3
- import { createAsyncSubAgentMiddleware, createDeepAgent, createFilesystemMiddleware, createMemoryMiddleware, createPatchToolCallsMiddleware, createSkillsMiddleware, createSummarizationMiddleware, createSubAgentMiddleware, FilesystemBackend, StateBackend, } from "deepagents";
4
- import { createAgent, humanInTheLoopMiddleware, todoListMiddleware } from "langchain";
5
- import { sanitizeVisibleText, tryParseJson, wrapResolvedModel, } from "./parsing/output-parsing.js";
6
- import { salvageJsonToolCalls } from "./parsing/output-tool-args.js";
7
- import { extractMessageText } from "../utils/message-content.js";
8
- import { AGENT_INTERRUPT_SENTINEL_PREFIX, buildDeepAgentCreateParams, buildDeepAgentSystemPromptWithCapabilityCatalog, buildLangChainCreateParams, DEFAULT_DEEPAGENT_RECURSION_LIMIT, materializeModelExposedBuiltinMiddlewareTools, resolveLangChainInvocationConfig, resolveRunnableCheckpointer, resolveRunnableInterruptOn, shouldAttachDeepAgentBackend, shouldAttachDeepAgentCheckpointer, shouldAttachDeepAgentStore, } from "./agent-runtime-assembly.js";
9
- import { resolveDeepAgentSkillSourcePaths, resolveDeepAgentSkillSourceRootPaths, } from "./adapter/compat/deepagent-compat.js";
10
- import { buildToolNameMapping, } from "./adapter/tool/tool-name-mapping.js";
11
- import { PROMPTED_JSON_TOOL_POLICY_KEY } from "./adapter/model/prompted-json-tool-policy.js";
12
- import { executeRequestInvocation } from "./adapter/flow/invocation-flow.js";
13
- import { streamRuntimeExecution } from "./adapter/flow/stream-runtime.js";
14
- import { resolveDeterministicFinalOutput } from "./adapter/invocation-result.js";
15
- import { applyToolRecoveryInstruction as applyToolRecoveryInstructionHelper, applyStrictToolJsonInstruction as applyStrictToolJsonInstructionHelper, callRuntimeWithToolParseRecovery as callRuntimeWithToolParseRecoveryHelper, createModelFallbackRunnable as createModelFallbackRunnableHelper, invokeWithProviderRetry as invokeWithProviderRetryHelper, iterateWithTimeout as iterateWithTimeoutHelper, materializeModelStream as materializeModelStreamHelper, RuntimeOperationTimeoutError, withRuntimeTimeout, } from "./adapter/runtime-shell.js";
16
- import { extractSubagentRequestText, invokeBuiltinTaskTool as invokeBuiltinTaskToolHelper, materializeAutomaticSummarizationMiddleware as materializeAutomaticSummarizationMiddlewareHelper, resolveBuiltinMiddlewareBackend as resolveBuiltinMiddlewareBackendHelper, resolveBuiltinMiddlewareTools as resolveBuiltinMiddlewareToolsHelper, resolveLangChainRuntimeExtensionMiddleware as resolveLangChainRuntimeExtensionMiddlewareHelper, resolveMiddleware as resolveMiddlewareHelper, resolveSubagents as resolveSubagentsHelper, wrapRequestResultAsSubagentResponse, } from "./adapter/middleware-assembly.js";
17
- import { isEmptyFinalAiMessageError, resolveBindingTimeout, resolveStreamIdleTimeout, } from "./adapter/resilience.js";
18
- import { createResolvedModel } from "./adapter/model/model-providers.js";
19
- import { appendProviderToolCallAliasTools, resolveAdapterTools } from "./adapter/tool-resolution.js";
20
- import { resolveRuntimeStreamExecutionContext, } from "./adapter/flow/execution-context.js";
21
- import { isRetryableProviderError } from "./adapter/resilience.js";
22
- import { UPSTREAM_REQUEST_CONFIG_KEY, UPSTREAM_SESSION_CONFIG_KEY } from "./adapter/upstream-configurable-keys.js";
23
- export { materializeDeepAgentSkillSourcePaths, resolveDeepAgentSkillSourcePaths, resolveDeepAgentSkillSourceRootPaths, relativizeDeepAgentSkillSourcePaths, } from "./adapter/compat/deepagent-compat.js";
24
- export { buildAuthOmittingFetch, normalizeOpenAICompatibleInit } from "./adapter/compat/openai-compatible.js";
25
- export { buildToolNameMapping, createModelFacingToolNameCandidates, createModelFacingToolNameLookupCandidates, resolveModelFacingToolName, sanitizeToolNameForModel, } from "./adapter/tool/tool-name-mapping.js";
26
- export { computeRemainingTimeoutMs, isRetryableProviderError, resolveBindingTimeout, resolveProviderRetryPolicy, resolveStreamIdleTimeout, resolveTimeoutMs, } from "./adapter/resilience.js";
27
- import { getBindingAdapterKind, getBindingBuiltinToolsConfig, getBindingDeepAgentSubagents, getBindingExecutionParams, getBindingExecutionKind, getBindingFilesystemConfig, getBindingMemorySources, getBindingPrimaryModel, getBindingSkills, getBindingSubagents, getBindingToolCount, getBindingPrimaryTools, getBindingSystemPrompt, isDeepAgentBinding, isLangChainBinding, } from "./support/compiled-binding.js";
28
- function buildDelegatedPlanEvidenceBlocker(agentId) {
29
- return JSON.stringify({
30
- status: "blocked",
31
- routing: [`delegated agent ${agentId}`],
32
- plan: ["delegate to specialist", "require visible TODO planning evidence", "return blocker when planning evidence is absent"],
33
- execution: [`task delegated to ${agentId}`, `delegated agent ${agentId} ended before producing required TODO plan evidence`],
34
- todoTrace: [`${agentId}: TODO evidence missing; delegated agent ended before producing required planning evidence.`],
35
- stepResults: ["delegated planning evidence was not observed"],
36
- summary: [`Delegated agent ${agentId} ended before producing the required TODO plan evidence.`],
37
- findings: ["The delegated run did not expose a valid planning trace, so the framework cannot treat the task as complete."],
38
- blockers: ["missing delegated TODO planning evidence"],
39
- nextActions: ["Retry with the same request or inspect the delegated agent configuration and model/tool-call behavior."],
40
- report: `routing delegated to ${agentId}; todoTrace ${agentId}: TODO evidence missing; stepResults blocked; summary missing planning evidence; findings require retry; blockers missing TODO planning evidence; nextActions inspect delegated model/tool behavior; report task delegated to ${agentId}.`,
41
- });
42
- }
43
- function normalizePlanToolName(toolName) {
44
- return typeof toolName === "string" ? toolName.trim().toLowerCase().replace(/[\s-]+/gu, "_") : "";
45
- }
46
- function isPlanToolName(toolName) {
47
- const normalized = normalizePlanToolName(toolName);
48
- return normalized === "write_todos"
49
- || normalized === "read_todos"
50
- || normalized === "tool_call_write_todos"
51
- || normalized === "tool_call_read_todos"
52
- || normalized === "call_write_todos"
53
- || normalized === "call_read_todos";
54
- }
55
- function readConfiguredToolName(value) {
56
- if (typeof value !== "object" || value === null) {
57
- return "";
58
- }
59
- const typed = value;
60
- return typeof typed.name === "string" ? typed.name.trim() : "";
61
- }
62
- function shouldUseConfigurableDeepAgentAssembly(binding) {
63
- return getBindingExecutionKind(binding) === "deepagent";
64
- }
65
- function canUseUpstreamCreateDeepAgentAssembly(binding) {
66
- const builtinTools = getBindingBuiltinToolsConfig(binding);
67
- return builtinTools?.todos !== false && builtinTools?.filesystem !== false;
68
- }
69
- function readModelText(value) {
70
- if (typeof value === "string") {
71
- return value.trim();
72
- }
73
- if (typeof value !== "object" || value === null) {
74
- return "";
75
- }
76
- const content = value.content;
77
- if (typeof content === "string") {
78
- return content.trim();
79
- }
80
- if (Array.isArray(content)) {
81
- return content
82
- .map((part) => {
83
- if (typeof part === "string")
84
- return part;
85
- if (typeof part === "object" && part !== null && typeof part.text === "string") {
86
- return part.text;
87
- }
88
- return "";
89
- })
90
- .join("")
91
- .trim();
92
- }
93
- return "";
94
- }
95
- function parseFirstJsonObject(value) {
96
- let depth = 0;
97
- let start = -1;
98
- let inString = false;
99
- let escaping = false;
100
- for (let index = 0; index < value.length; index += 1) {
101
- const char = value[index];
102
- if (inString) {
103
- if (escaping) {
104
- escaping = false;
105
- }
106
- else if (char === "\\") {
107
- escaping = true;
108
- }
109
- else if (char === "\"") {
110
- inString = false;
111
- }
112
- continue;
113
- }
114
- if (char === "\"") {
115
- inString = true;
116
- continue;
117
- }
118
- if (char === "{") {
119
- if (depth === 0) {
120
- start = index;
121
- }
122
- depth += 1;
123
- continue;
124
- }
125
- if (char === "}" && depth > 0) {
126
- depth -= 1;
127
- if (depth === 0 && start >= 0) {
128
- return tryParseJson(value.slice(start, index + 1));
129
- }
130
- }
131
- }
132
- return null;
133
- }
134
- function parseCompactRouterSelection(value, subagentNames) {
135
- const trimmed = value.trim();
136
- const resolveExactName = (candidate) => Array.from(subagentNames).find((name) => name.toLowerCase() === candidate.trim().toLowerCase());
137
- const exactTrimmedName = resolveExactName(trimmed);
138
- if (exactTrimmedName) {
139
- return { subagentType: exactTrimmedName };
140
- }
141
- const parsed = parseFirstJsonObject(trimmed);
142
- const toolCall = salvageJsonToolCalls(trimmed).at(0);
143
- const payload = typeof parsed === "object" && parsed !== null && !Array.isArray(parsed)
144
- ? parsed
145
- : toolCall
146
- ? { name: toolCall.name, arguments: toolCall.args }
147
- : null;
148
- if (!payload) {
149
- return null;
150
- }
151
- const args = typeof payload.arguments === "object" && payload.arguments !== null && !Array.isArray(payload.arguments)
152
- ? payload.arguments
153
- : typeof payload.args === "object" && payload.args !== null && !Array.isArray(payload.args)
154
- ? payload.args
155
- : payload;
156
- const subagentType = typeof payload.subagent_type === "string"
157
- ? payload.subagent_type.trim()
158
- : typeof args.subagent_type === "string"
159
- ? args.subagent_type.trim()
160
- : "";
161
- const resolvedSubagentType = resolveExactName(subagentType);
162
- if (resolvedSubagentType) {
163
- return { subagentType: resolvedSubagentType };
164
- }
165
- const rawDelegations = Array.isArray(payload.delegations)
166
- ? payload.delegations
167
- : Array.isArray(args.delegations)
168
- ? args.delegations
169
- : undefined;
170
- if (rawDelegations) {
171
- const delegations = rawDelegations
172
- .map((item) => {
173
- if (typeof item !== "object" || item === null || Array.isArray(item)) {
174
- return null;
175
- }
176
- const typed = item;
177
- const rawName = typeof typed.subagent_type === "string"
178
- ? typed.subagent_type.trim()
179
- : typeof typed.subagent === "string"
180
- ? typed.subagent.trim()
181
- : "";
182
- const resolvedName = Array.from(subagentNames).find((name) => name.toLowerCase() === rawName.toLowerCase());
183
- if (!resolvedName) {
184
- return null;
185
- }
186
- const description = typeof typed.description === "string" && typed.description.trim()
187
- ? typed.description.trim()
188
- : typeof typed.task === "string" && typed.task.trim()
189
- ? typed.task.trim()
190
- : typeof typed.instruction === "string" && typed.instruction.trim()
191
- ? typed.instruction.trim()
192
- : "";
193
- return { subagentType: resolvedName, description };
194
- })
195
- .filter((item) => item !== null);
196
- const deduped = [];
197
- for (const delegation of delegations) {
198
- if (deduped.some((item) => item.subagentType === delegation.subagentType)) {
199
- continue;
200
- }
201
- deduped.push(delegation);
202
- }
203
- if (deduped.length > 0) {
204
- return { delegations: deduped };
205
- }
206
- }
207
- const routingMap = typeof payload.routing === "object" && payload.routing !== null && !Array.isArray(payload.routing)
208
- ? payload.routing
209
- : typeof args.routing === "object" && args.routing !== null && !Array.isArray(args.routing)
210
- ? args.routing
211
- : undefined;
212
- if (routingMap) {
213
- const nestedSubagents = Array.isArray(routingMap.subagents)
214
- ? routingMap.subagents
215
- .map((item) => {
216
- if (typeof item !== "string") {
217
- return null;
218
- }
219
- const resolvedName = resolveExactName(item);
220
- return resolvedName ? { subagentType: resolvedName, description: "" } : null;
221
- })
222
- .filter((item) => item !== null)
223
- : [];
224
- const delegations = Object.entries(routingMap)
225
- .map(([rawName, rawDescription]) => {
226
- const resolvedName = resolveExactName(rawName);
227
- if (!resolvedName) {
228
- return null;
229
- }
230
- const description = typeof rawDescription === "string" && rawDescription.trim()
231
- ? rawDescription.trim()
232
- : "";
233
- return { subagentType: resolvedName, description };
234
- })
235
- .filter((item) => item !== null);
236
- for (const delegation of nestedSubagents) {
237
- if (!delegations.some((item) => item.subagentType === delegation.subagentType)) {
238
- delegations.push(delegation);
239
- }
240
- }
241
- if (delegations.length > 0) {
242
- return { delegations };
243
- }
244
- }
245
- const status = typeof payload.status === "string" ? payload.status.trim().toLowerCase() : "";
246
- if (status === "refused") {
247
- const reason = typeof payload.reason === "string" && payload.reason.trim()
248
- ? payload.reason.trim()
249
- : "No configured subagent can handle the request.";
250
- return { refusedReason: reason };
251
- }
252
- return null;
253
- }
254
- function buildCompactRouterPolicy(routingPolicy) {
255
- if (!routingPolicy) {
256
- return "";
257
- }
258
- const lines = routingPolicy
259
- .split(/\r?\n/u)
260
- .map((line) => line.trim())
261
- .filter((line) => line.length > 0);
262
- const outputContractIndex = lines.findIndex((line) => /^output:?$/iu.test(line));
263
- return (outputContractIndex >= 0 ? lines.slice(0, outputContractIndex) : lines)
264
- .slice(0, 80)
265
- .join("\n");
266
- }
267
- function looksLikeStructuredMultiItemRequest(requestText) {
268
- const lines = requestText
269
- .split(/\r?\n/u)
270
- .map((line) => line.trim())
271
- .filter(Boolean);
272
- const numberedItems = lines.filter((line) => /^\d+[\.)、]\s+/u.test(line));
273
- if (numberedItems.length >= 2) {
274
- return true;
275
- }
276
- const bulletItems = lines.filter((line) => /^[-*]\s+/u.test(line));
277
- return bulletItems.length >= 2;
278
- }
279
- function buildDelegatedOwnedTaskInstruction(input) {
280
- return [
281
- `Delegated owner: ${input.subagentType}.`,
282
- "Execute only this owner's bounded portion of the larger request.",
283
- "Do not take over other specialist-owned work; return blockers for missing access instead of inventing success.",
284
- "Owned subtask:",
285
- input.taskText.trim() || input.originalRequest,
286
- "If the owner policy or tool contract requires evidence, call write_todos first and then execute the appropriate non-planning evidence tool before any final answer.",
287
- "Close every TODO as completed or failed before final output.",
288
- ].filter(Boolean).join("\n");
289
- }
290
- function isDelegationOnlyDeepAgentBinding(binding) {
291
- return isDeepAgentBinding(binding)
292
- && getBindingSubagents(binding).length > 0
293
- && getBindingPrimaryTools(binding).length === 0
294
- && getBindingSkills(binding).length === 0;
295
- }
296
- function hasDelegatedPlanEvidence(result) {
297
- if (result?.metadata?.externalPlanEvidence === true) {
298
- return true;
299
- }
300
- const toolResults = result?.metadata?.executedToolResults;
301
- return Array.isArray(toolResults)
302
- && toolResults.some((item) => isPlanToolName(item.toolName));
303
- }
304
- function hasIncompleteDelegatedTodos(value) {
305
- if (Array.isArray(value)) {
306
- return value.some((item) => hasIncompleteDelegatedTodos(item));
307
- }
308
- if (typeof value !== "object" || value === null) {
309
- return false;
310
- }
311
- const record = value;
312
- const status = typeof record.status === "string" ? record.status.trim().toLowerCase() : "";
313
- if (status === "pending" || status === "in_progress") {
314
- return true;
315
- }
316
- return hasIncompleteDelegatedTodos(record.todos)
317
- || hasIncompleteDelegatedTodos(record.update)
318
- || hasIncompleteDelegatedTodos(record.stateSnapshot)
319
- || hasIncompleteDelegatedTodos(record.metadata);
320
- }
321
- function hasFailedDelegatedTodos(value) {
322
- if (Array.isArray(value)) {
323
- return value.some((item) => hasFailedDelegatedTodos(item));
324
- }
325
- if (typeof value !== "object" || value === null) {
326
- return false;
327
- }
328
- const record = value;
329
- const status = typeof record.status === "string" ? record.status.trim().toLowerCase() : "";
330
- if (status === "failed") {
331
- return true;
332
- }
333
- return hasFailedDelegatedTodos(record.todos)
334
- || hasFailedDelegatedTodos(record.update)
335
- || hasFailedDelegatedTodos(record.stateSnapshot)
336
- || hasFailedDelegatedTodos(record.metadata);
337
- }
338
- function hasIncompleteDelegatedPlanState(result) {
339
- const toolResults = result?.metadata?.executedToolResults;
340
- return Array.isArray(toolResults)
341
- && toolResults.some((item) => isPlanToolName(item.toolName) && hasIncompleteDelegatedTodos(item.output));
342
- }
343
- function hasFailedDelegatedPlanState(result) {
344
- const toolResults = result?.metadata?.executedToolResults;
345
- return Array.isArray(toolResults)
346
- && toolResults.some((item) => isPlanToolName(item.toolName) && hasFailedDelegatedTodos(item.output));
347
- }
348
- function hasDelegatedNonPlanToolEvidence(result) {
349
- const toolResults = result?.metadata?.executedToolResults;
350
- return Array.isArray(toolResults)
351
- && toolResults.some((item) => typeof item.toolName === "string" && !isPlanToolName(item.toolName) && item.isError !== true);
352
- }
353
- function hasNonPlanToolEvidenceItems(items) {
354
- return items.some((item) => typeof item.toolName === "string" && !isPlanToolName(item.toolName) && item.isError !== true);
355
- }
356
- function buildDelegatedExternalPlanEvidenceSummary(items) {
357
- const evidence = items
358
- .filter((item) => typeof item.toolName === "string" && !isPlanToolName(item.toolName) && item.isError !== true)
359
- .map((item) => {
360
- const output = typeof item.output === "string" ? item.output : JSON.stringify(item.output ?? "");
361
- return `## ${String(item.toolName)}\n${output}`;
362
- });
363
- return [
364
- "Status: completed",
365
- "Summary:",
366
- "- Completed delegated recovery after collecting non-planning tool evidence.",
367
- "",
368
- "Evidence:",
369
- evidence.length > 0 ? evidence.join("\n\n") : "(no non-planning tool evidence captured)",
370
- ].join("\n");
371
- }
372
- function needsDelegatedPlanRecovery(binding, result) {
373
- return binding?.harnessRuntime.executionContract?.requiresPlan === true
374
- && (!hasDelegatedPlanEvidence(result)
375
- || hasIncompleteDelegatedPlanState(result)
376
- || (hasFailedDelegatedPlanState(result) && !hasDelegatedNonPlanToolEvidence(result)));
377
- }
378
- function readUpstreamToolEvidence(event) {
379
- if (typeof event !== "object" || event === null) {
380
- return null;
381
- }
382
- const typed = event;
383
- const eventName = typeof typed.event === "string" ? typed.event : "";
384
- const runType = typeof typed.run_type === "string" ? typed.run_type : "";
385
- const toolName = typeof typed.name === "string" ? typed.name : "";
386
- if (!toolName) {
387
- return null;
388
- }
389
- const isToolStart = eventName === "on_tool_start" || (eventName === "on_chain_start" && runType === "tool");
390
- if (isToolStart && isPlanToolName(toolName)) {
391
- return { toolName, output: typed.data?.input };
392
- }
393
- const isToolEnd = eventName === "on_tool_end" || (eventName === "on_chain_end" && runType === "tool");
394
- if (isToolEnd) {
395
- return { toolName, output: typed.data?.output };
396
- }
397
- const isToolError = eventName === "on_tool_error";
398
- if (isToolError) {
399
- return { toolName, output: typed.data?.error ?? typed.data?.output, isError: true };
400
- }
401
- return null;
402
- }
403
- function appendUniqueToolEvidence(executedToolResults, evidence) {
404
- const exists = executedToolResults.some((item) => item.toolName === evidence.toolName
405
- && item.isError === evidence.isError
406
- && JSON.stringify(item.output) === JSON.stringify(evidence.output));
407
- if (!exists) {
408
- executedToolResults.push(evidence);
409
- }
410
- }
411
- function mergeDelegatedResultToolEvidence(result, previous) {
412
- const merged = [];
413
- for (const source of [previous, result]) {
414
- const toolResults = Array.isArray(source.metadata?.executedToolResults)
415
- ? source.metadata.executedToolResults
416
- : [];
417
- for (const toolResult of toolResults) {
418
- if (typeof toolResult === "object"
419
- && toolResult !== null
420
- && typeof toolResult.toolName === "string") {
421
- appendUniqueToolEvidence(merged, toolResult);
422
- }
423
- }
424
- }
425
- return {
426
- ...result,
427
- metadata: {
428
- ...(result.metadata ?? {}),
429
- executedToolResults: merged,
430
- },
431
- };
432
- }
433
- const DELEGATED_PLAN_EVIDENCE_RETRY_INSTRUCTION = [
434
- "The delegated task requires visible TODO planning evidence.",
435
- "Before any other tool call or final answer, call write_todos with concrete task steps and statuses.",
436
- "Then continue the task to completion, update TODO statuses after evidence steps, and close every TODO as completed or failed before the final answer.",
437
- ].join("\n");
438
- const DELEGATED_PLAN_EVIDENCE_FINAL_RETRY_INSTRUCTION = [
439
- "The delegated task has already attempted TODO planning but still has no successful non-planning tool evidence.",
440
- "Do not call write_todos or read_todos next.",
441
- "The next runtime event must be one available non-planning evidence tool call.",
442
- "After that tool returns, update or close the TODO board and provide the final answer required by the agent response format.",
443
- ].join("\n");
444
- function buildDelegatedPlanEvidenceRecoveryOptions(_binding, baseOptions, _requestText = "") {
445
- return {
446
- ...baseOptions,
447
- suppressInitialRequiredPlanInstruction: true,
448
- externalPlanEvidence: true,
449
- state: {
450
- ...(typeof baseOptions.state === "object" && baseOptions.state !== null ? baseOptions.state : {}),
451
- [PROMPTED_JSON_TOOL_POLICY_KEY]: "nonPlanningEvidence",
452
- },
453
- };
454
- }
455
- function looksLikeRawCommandTranscript(value) {
456
- const normalized = value.trim();
457
- return /^(?:stdout|stderr)\s*:/iu.test(normalized)
458
- || /(?:^|\n)\s*(?:stdout|stderr)\s*:/iu.test(normalized)
459
- || /(?:^|\n)\s*exitCode\s*:\s*-?\d+\s*$/iu.test(normalized);
460
- }
461
- function resolveDelegatedResultOutput(result) {
462
- const executedToolResults = Array.isArray(result.metadata?.executedToolResults)
463
- ? result.metadata.executedToolResults
464
- : [];
465
- const deterministicOutput = resolveDeterministicFinalOutput({
466
- visibleOutput: typeof result.output === "string" ? result.output : "",
467
- executedToolResults,
468
- });
469
- return deterministicOutput || result.output;
470
- }
471
- function selectDelegatedToolResultsForVisibleProgress(result) {
472
- const executedToolResults = Array.isArray(result?.metadata?.executedToolResults)
473
- ? result.metadata.executedToolResults
474
- : [];
475
- const hasSuccessfulExecutionEvidence = executedToolResults.some((toolResult) => (toolResult.isError !== true
476
- && !isPlanToolName(toolResult.toolName)));
477
- return hasSuccessfulExecutionEvidence
478
- ? executedToolResults.filter((toolResult) => (toolResult.isError !== true
479
- && !isPlanToolName(toolResult.toolName)))
480
- : executedToolResults;
481
- }
482
- export class AgentRuntimeAdapter {
483
- options;
484
- modelCache = new Map();
485
- runnableCache = new Map();
486
- toolNameMappingCache = new WeakMap();
487
- constructor(options = {}) {
488
- this.options = options;
489
- }
490
- getModelCacheKey(model) {
491
- return JSON.stringify({
492
- id: model.id,
493
- runtimeValue: model.runtimeValue,
494
- init: model.init,
495
- clientRef: model.clientRef,
496
- });
497
- }
498
- async invokeWithProviderRetry(binding, operation) {
499
- return invokeWithProviderRetryHelper(binding, operation, {
500
- onRetry: async () => {
501
- this.invalidateBindingRuntimeCaches(binding);
502
- },
503
- });
504
- }
505
- async withTimeout(producer, timeoutMs, operation, stage = operation.includes("stream") ? "stream" : "invoke") {
506
- return withRuntimeTimeout(producer, timeoutMs, operation, stage);
507
- }
508
- async *iterateWithTimeout(iterable, timeoutMs, operation, deadlineAt, deadlineTimeoutMs) {
509
- yield* iterateWithTimeoutHelper(iterable, timeoutMs, operation, deadlineAt, deadlineTimeoutMs);
510
- }
511
- async materializeModelStream(streamFactory, input, config) {
512
- return materializeModelStreamHelper(streamFactory, input, config);
513
- }
514
- createModelFallbackRunnable(model) {
515
- return createModelFallbackRunnableHelper(model);
516
- }
517
- applyStrictToolJsonInstruction(binding) {
518
- return applyStrictToolJsonInstructionHelper(binding);
519
- }
520
- async resolveModel(model) {
521
- const cacheKey = this.getModelCacheKey(model);
522
- const cached = this.modelCache.get(cacheKey);
523
- if (cached) {
524
- return cached;
525
- }
526
- const pending = (async () => {
527
- return wrapResolvedModel(await createResolvedModel(model, this.options.modelResolver));
528
- })();
529
- this.modelCache.set(cacheKey, pending);
530
- try {
531
- return await pending;
532
- }
533
- catch (error) {
534
- this.modelCache.delete(cacheKey);
535
- throw error;
536
- }
537
- }
538
- invalidateBindingRuntimeCaches(binding) {
539
- const prefix = `${binding.agent.sourcePath}::`;
540
- for (const key of Array.from(this.runnableCache.keys())) {
541
- if (key.startsWith(prefix)) {
542
- this.runnableCache.delete(key);
543
- }
544
- }
545
- this.modelCache.clear();
546
- }
547
- resolveTools(tools, binding) {
548
- return resolveAdapterTools({
549
- tools,
550
- binding,
551
- resolveToolValues: this.options.toolResolver,
552
- });
553
- }
554
- getToolNameMapping(binding) {
555
- const cached = this.toolNameMappingCache.get(binding);
556
- if (cached) {
557
- return cached;
558
- }
559
- const resolved = buildToolNameMapping(getBindingPrimaryTools(binding));
560
- this.toolNameMappingCache.set(binding, resolved);
561
- return resolved;
562
- }
563
- resolveFilesystemBackend(binding, options = {}) {
564
- const filesystemConfig = getBindingFilesystemConfig(binding);
565
- const sessionStorage = typeof filesystemConfig?.sessionStorage === "object" && filesystemConfig.sessionStorage
566
- ? filesystemConfig.sessionStorage
567
- : undefined;
568
- const configuredRootDir = typeof filesystemConfig?.rootDir === "string" && filesystemConfig.rootDir.trim().length > 0
569
- ? filesystemConfig.rootDir
570
- : undefined;
571
- const workspaceRoot = binding.harnessRuntime.workspaceRoot;
572
- const baseRootDir = configuredRootDir
573
- ? (path.isAbsolute(configuredRootDir) ? configuredRootDir : path.resolve(workspaceRoot ?? process.cwd(), configuredRootDir))
574
- : workspaceRoot ?? process.cwd();
575
- const rootDir = this.resolveFilesystemRootDir(baseRootDir, binding, sessionStorage, options.sessionId ?? options.legacySessionId);
576
- return new FilesystemBackend({
577
- rootDir,
578
- virtualMode: filesystemConfig?.virtualMode === true,
579
- maxFileSizeMb: typeof filesystemConfig?.maxFileSizeMb === "number" && Number.isFinite(filesystemConfig.maxFileSizeMb)
580
- ? filesystemConfig.maxFileSizeMb
581
- : 10,
582
- });
583
- }
584
- resolveFilesystemRootDir(baseRootDir, binding, sessionStorage, sessionId) {
585
- const enabled = sessionStorage?.enabled === true;
586
- if (!enabled || !sessionId) {
587
- return baseRootDir;
588
- }
589
- const workspaceRoot = binding.harnessRuntime.workspaceRoot ?? process.cwd();
590
- const runtimeRoot = binding.harnessRuntime.runtimeRoot;
591
- const configuredRootDir = typeof sessionStorage.rootDir === "string" && sessionStorage.rootDir.trim().length > 0
592
- ? sessionStorage.rootDir.trim()
593
- : "{runtimeRoot}/sessions/{sessionId}/filesystem";
594
- const rendered = configuredRootDir
595
- .replaceAll("{legacySessionId}", sessionId)
596
- .replaceAll("{sessionId}", sessionId)
597
- .replaceAll("{agentId}", binding.agent.id)
598
- .replaceAll("{runtimeRoot}", runtimeRoot)
599
- .replaceAll("{workspaceRoot}", workspaceRoot)
600
- .replaceAll("{baseRootDir}", baseRootDir);
601
- return path.isAbsolute(rendered) ? rendered : path.resolve(workspaceRoot, rendered);
602
- }
603
- resolveBuiltinMiddlewareBackend(binding, options = {}) {
604
- const resolved = resolveBuiltinMiddlewareBackendHelper({
605
- binding,
606
- runtimeAdapterOptions: this.options,
607
- resolveFilesystemBackend: (currentBinding) => this.resolveFilesystemBackend(currentBinding),
608
- options,
609
- });
610
- if (!this.options.scheduleManager || typeof resolved !== "object" || !resolved) {
611
- return resolved;
612
- }
613
- const decorated = Object.create(resolved);
614
- decorated.manageSchedule = (input) => this.options.scheduleManager.manageSchedule(input);
615
- return decorated;
616
- }
617
- buildFunctionToolRuntimeContext(binding, options = {}) {
618
- if (!this.options.functionToolContextResolver) {
619
- return undefined;
620
- }
621
- const publicRequestId = typeof options.requestId === "string" && options.requestId.includes(":")
622
- ? options.requestId.split(":")[0]
623
- : options.requestId;
624
- const backend = this.resolveBuiltinMiddlewareBackend(binding, options);
625
- return {
626
- ...this.options.functionToolContextResolver({
627
- binding,
628
- sessionId: options.sessionId,
629
- requestId: publicRequestId,
630
- }),
631
- backend,
632
- invocation: {
633
- ...(options.context ? { context: options.context } : {}),
634
- ...(options.sessionId ? { sessionId: options.sessionId } : {}),
635
- ...(publicRequestId ? { requestId: publicRequestId } : {}),
636
- },
637
- };
638
- }
639
- createDeclaredMiddlewareResolverOptions(binding, options = {}) {
640
- return {
641
- resolveModel: (model) => this.resolveModel(model),
642
- resolveBackend: (resolvedBinding) => {
643
- const targetBinding = resolvedBinding ?? binding;
644
- return targetBinding ? this.options.backendResolver?.(targetBinding) : undefined;
645
- },
646
- resolveFilesystemBackend: (resolvedBinding) => {
647
- const targetBinding = resolvedBinding ?? binding;
648
- return targetBinding ? this.resolveFilesystemBackend(targetBinding, { sessionId: options.sessionId ?? options.legacySessionId }) : undefined;
649
- },
650
- resolveCustom: this.options.declaredMiddlewareResolver,
651
- binding,
652
- };
653
- }
654
- createAssemblyResolvers(binding, options = {}) {
655
- return {
656
- resolveModel: (model) => this.resolveModel(model),
657
- resolveTools: (tools, currentBinding) => this.resolveTools(tools, currentBinding),
658
- resolveFilesystemBackend: (currentBinding) => this.resolveFilesystemBackend(currentBinding, { sessionId: options.sessionId ?? options.legacySessionId }),
659
- createDeclaredMiddlewareResolverOptions: (currentBinding) => this.createDeclaredMiddlewareResolverOptions(currentBinding, options),
660
- resolveBuiltinMiddlewareBackend: (currentBinding, currentOptions = {}) => this.resolveBuiltinMiddlewareBackend(currentBinding, currentOptions),
661
- resolveSubagents: (subagents, currentBinding) => this.resolveSubagents(subagents, currentBinding),
662
- invokeBuiltinTaskTool: (currentBinding, toolInput, currentOptions = {}) => this.invokeBuiltinTaskTool(currentBinding, toolInput, currentOptions),
663
- binding,
664
- options,
665
- };
666
- }
667
- async invokeBuiltinTaskTool(binding, input, options = {}) {
668
- const assembly = this.createAssemblyResolvers(binding, options);
669
- return invokeBuiltinTaskToolHelper({
670
- binding,
671
- toolInput: input,
672
- options,
673
- resolveBuiltinMiddlewareBackend: assembly.resolveBuiltinMiddlewareBackend,
674
- resolveSubagents: assembly.resolveSubagents,
675
- resolveModel: assembly.resolveModel,
676
- resolveTools: assembly.resolveTools,
677
- });
678
- }
679
- async resolveBuiltinMiddlewareTools(binding, options = {}) {
680
- const assembly = this.createAssemblyResolvers(binding, options);
681
- return resolveBuiltinMiddlewareToolsHelper({
682
- binding,
683
- options,
684
- resolveBuiltinMiddlewareBackend: assembly.resolveBuiltinMiddlewareBackend,
685
- invokeBuiltinTaskTool: assembly.invokeBuiltinTaskTool,
686
- });
687
- }
688
- materializeProviderAliasBuiltinTools(builtinTools, modelExposed) {
689
- if (modelExposed === false) {
690
- return [];
691
- }
692
- const allowedToolNames = Array.isArray(modelExposed) ? new Set(modelExposed) : undefined;
693
- const aliasableTools = ["write_todos", "read_todos", "task"]
694
- .filter((name) => !allowedToolNames || allowedToolNames.has(name))
695
- .map((name) => builtinTools.get(name))
696
- .filter((tool) => tool !== undefined);
697
- return appendProviderToolCallAliasTools(aliasableTools).slice(aliasableTools.length);
698
- }
699
- shouldExposeBuiltinToolsToModel(binding, primaryTools) {
700
- const modelExposed = getBindingBuiltinToolsConfig(binding)?.modelExposed;
701
- if (binding.harnessRuntime.executionContract?.requiresPlan === true) {
702
- return true;
703
- }
704
- if (modelExposed === false) {
705
- return false;
706
- }
707
- if (Array.isArray(modelExposed)) {
708
- return modelExposed.length > 0;
709
- }
710
- return (primaryTools.length > 0
711
- || getBindingSubagents(binding).length > 0
712
- || getBindingDeepAgentSubagents(binding).length > 0);
713
- }
714
- resolveEffectiveModelExposedBuiltins(binding) {
715
- const configured = getBindingBuiltinToolsConfig(binding)?.modelExposed;
716
- const requiredNames = new Set();
717
- if (binding.harnessRuntime.executionContract?.requiresPlan === true) {
718
- requiredNames.add("write_todos");
719
- requiredNames.add("read_todos");
720
- }
721
- if (configured === false) {
722
- return requiredNames.size > 0 ? [...requiredNames] : false;
723
- }
724
- if (Array.isArray(configured)) {
725
- return [...new Set([...configured, ...requiredNames])];
726
- }
727
- return configured;
728
- }
729
- async materializeAutomaticSummarizationMiddleware(binding) {
730
- const assembly = this.createAssemblyResolvers(binding);
731
- return materializeAutomaticSummarizationMiddlewareHelper({
732
- binding,
733
- createDeclaredMiddlewareResolverOptions: assembly.createDeclaredMiddlewareResolverOptions,
734
- });
735
- }
736
- async resolveLangChainRuntimeExtensionMiddleware(binding, options = {}) {
737
- const assembly = this.createAssemblyResolvers(binding, options);
738
- return resolveLangChainRuntimeExtensionMiddlewareHelper({
739
- binding,
740
- materializeAutomaticSummarizationMiddleware: (currentBinding) => this.materializeAutomaticSummarizationMiddleware(currentBinding),
741
- resolveFilesystemBackend: assembly.resolveFilesystemBackend,
742
- resolveModel: assembly.resolveModel,
743
- resolveTools: assembly.resolveTools,
744
- resolveSubagents: assembly.resolveSubagents,
745
- });
746
- }
747
- async resolveMiddleware(binding, interruptOn, options = {}) {
748
- const assembly = this.createAssemblyResolvers(binding, options);
749
- return resolveMiddlewareHelper({
750
- binding,
751
- interruptOn,
752
- runtimeAdapterOptions: this.options,
753
- createDeclaredMiddlewareResolverOptions: assembly.createDeclaredMiddlewareResolverOptions,
754
- resolveLangChainRuntimeExtensionMiddleware: (currentBinding) => this.resolveLangChainRuntimeExtensionMiddleware(currentBinding, options),
755
- });
756
- }
757
- async resolveSubagents(subagents, binding) {
758
- const assembly = this.createAssemblyResolvers(binding);
759
- return resolveSubagentsHelper({
760
- subagents,
761
- binding,
762
- resolveModel: assembly.resolveModel,
763
- resolveTools: assembly.resolveTools,
764
- createDeclaredMiddlewareResolverOptions: assembly.createDeclaredMiddlewareResolverOptions,
765
- resolveBackend: (currentBinding) => {
766
- const targetBinding = currentBinding ?? binding;
767
- return targetBinding ? this.options.backendResolver?.(targetBinding) : undefined;
768
- },
769
- });
770
- }
771
- async resolveDeepAgentSubagents(subagents, binding, options = {}) {
772
- const syncSubagents = subagents.filter((subagent) => !("graphId" in subagent));
773
- const asyncSubagents = subagents.filter((subagent) => "graphId" in subagent);
774
- const resolvedSyncSubagents = await this.resolveSubagents(syncSubagents, binding);
775
- const wrappedSyncSubagents = await Promise.all(resolvedSyncSubagents.map(async (resolvedSubagent, index) => {
776
- const compiledSubagent = syncSubagents[index];
777
- const targetAgentId = compiledSubagent?.agentId;
778
- const targetBinding = targetAgentId ? this.options.bindingResolver?.(targetAgentId) : undefined;
779
- if (!targetBinding) {
780
- return resolvedSubagent;
781
- }
782
- const wrapper = {
783
- name: resolvedSubagent.name,
784
- description: resolvedSubagent.description,
785
- systemPrompt: resolvedSubagent.systemPrompt,
786
- runnable: {
787
- invoke: async (state, config) => {
788
- const requestText = extractSubagentRequestText(state);
789
- const configurable = typeof config?.configurable === "object" && config.configurable
790
- ? config.configurable
791
- : {};
792
- const sessionId = typeof configurable[UPSTREAM_SESSION_CONFIG_KEY] === "string"
793
- ? configurable[UPSTREAM_SESSION_CONFIG_KEY]
794
- : options.sessionId ?? `${binding?.agent.id ?? "agent"}:${resolvedSubagent.name}`;
795
- const requestId = typeof configurable[UPSTREAM_REQUEST_CONFIG_KEY] === "string"
796
- ? configurable[UPSTREAM_REQUEST_CONFIG_KEY]
797
- : sessionId;
798
- const childSessionId = `${sessionId}:delegated:${resolvedSubagent.name}`;
799
- const childRequestId = `${requestId}:delegated:${resolvedSubagent.name}:${Date.now().toString(36)}`;
800
- try {
801
- const result = await this.invoke(targetBinding, requestText, childSessionId, childRequestId, undefined, [], {
802
- ...(typeof config?.context === "object" && config.context ? { context: config.context } : {}),
803
- });
804
- return wrapRequestResultAsSubagentResponse({
805
- output: result.output,
806
- structuredResponse: result.structuredResponse,
807
- });
808
- }
809
- catch (error) {
810
- const message = error instanceof Error && error.message.trim().length > 0
811
- ? error.message.trim()
812
- : "delegated execution failed";
813
- throw new Error(message);
814
- }
815
- },
816
- },
817
- };
818
- return wrapper;
819
- }));
820
- return [...wrappedSyncSubagents, ...asyncSubagents];
821
- }
822
- async createLangChainRunnable(binding, options = {}) {
823
- const executionKind = getBindingExecutionKind(binding);
824
- const primaryModel = getBindingPrimaryModel(binding);
825
- const primaryTools = getBindingPrimaryTools(binding);
826
- if (executionKind !== "langchain-v1" || !primaryModel) {
827
- throw new Error(`Agent ${binding.agent.id} has no langchain params`);
828
- }
829
- const interruptOn = resolveRunnableInterruptOn(binding);
830
- const resolvedModel = await this.resolveModel(primaryModel);
831
- const resolvedTools = this.resolveTools(primaryTools, binding);
832
- const builtinExecutableTools = await this.resolveBuiltinMiddlewareTools(binding, {
833
- sessionId: options.sessionId ?? options.legacySessionId,
834
- toolRuntimeContext: this.buildFunctionToolRuntimeContext(binding, {
835
- sessionId: options.sessionId ?? options.legacySessionId,
836
- }),
837
- });
838
- const modelExposedBuiltins = this.resolveEffectiveModelExposedBuiltins(binding);
839
- const shouldExposeBuiltinTools = this.shouldExposeBuiltinToolsToModel(binding, primaryTools);
840
- const builtinMiddlewareTools = shouldExposeBuiltinTools
841
- ? materializeModelExposedBuiltinMiddlewareTools({
842
- builtinTools: builtinExecutableTools,
843
- explicitToolNames: primaryTools.map((tool) => tool.name),
844
- modelExposed: modelExposedBuiltins,
845
- })
846
- : [];
847
- const providerAliasBuiltinTools = shouldExposeBuiltinTools
848
- ? this.materializeProviderAliasBuiltinTools(builtinExecutableTools, modelExposedBuiltins)
849
- : [];
850
- const resolvedMiddleware = await this.resolveMiddleware(binding, interruptOn, { sessionId: options.sessionId ?? options.legacySessionId });
851
- const resolvedCheckpointer = resolveRunnableCheckpointer(this.options, binding);
852
- const resolvedStore = this.options.storeResolver?.(binding);
853
- const model = resolvedModel;
854
- if (resolvedTools.length + builtinMiddlewareTools.length > 0 && typeof model.bindTools !== "function") {
855
- throw new Error(`Agent ${binding.agent.id} configures ${resolvedTools.length + builtinMiddlewareTools.length} tool(s), but resolved model ${primaryModel.id} does not support tool binding.`);
856
- }
857
- const modelTools = [
858
- ...appendProviderToolCallAliasTools([...resolvedTools, ...builtinMiddlewareTools]),
859
- ...providerAliasBuiltinTools,
860
- ];
861
- return createAgent(buildLangChainCreateParams({
862
- binding,
863
- resolvedModel: model,
864
- resolvedTools: modelTools,
865
- resolvedMiddleware,
866
- resolvedCheckpointer,
867
- resolvedStore,
868
- passthroughOverride: options.passthroughOverride,
869
- systemPromptOverride: options.systemPromptOverride,
870
- }));
871
- }
872
- async createRunnable(binding, options = {}) {
873
- if (getBindingAdapterKind(binding) === "langgraph") {
874
- throw new Error(`Agent ${binding.agent.id} uses removed backend langgraph; use langchain-v1 or deepagent`);
875
- }
876
- if (isLangChainBinding(binding)) {
877
- return this.createLangChainRunnable(binding, { sessionId: options.sessionId ?? options.legacySessionId });
878
- }
879
- return this.createDeepAgentRunnable(binding, { sessionId: options.sessionId ?? options.legacySessionId });
880
- }
881
- async createDeepAgentRunnable(binding, options = {}) {
882
- const executionKind = getBindingExecutionKind(binding);
883
- const primaryModel = getBindingPrimaryModel(binding);
884
- const primaryTools = getBindingPrimaryTools(binding);
885
- if (executionKind !== "deepagent" || !primaryModel) {
886
- throw new Error(`Agent ${binding.agent.id} has no runnable params`);
887
- }
888
- const resolvedModel = await this.resolveModel(primaryModel);
889
- const resolvedTools = this.resolveTools(primaryTools, binding);
890
- const builtinExecutableTools = await this.resolveBuiltinMiddlewareTools(binding, {
891
- sessionId: options.sessionId ?? options.legacySessionId,
892
- toolRuntimeContext: this.buildFunctionToolRuntimeContext(binding, {
893
- sessionId: options.sessionId ?? options.legacySessionId,
894
- }),
895
- });
896
- const modelExposedBuiltins = this.resolveEffectiveModelExposedBuiltins(binding);
897
- const shouldExposeBuiltinTools = this.shouldExposeBuiltinToolsToModel(binding, primaryTools);
898
- const builtinMiddlewareTools = shouldExposeBuiltinTools
899
- ? materializeModelExposedBuiltinMiddlewareTools({
900
- builtinTools: builtinExecutableTools,
901
- explicitToolNames: primaryTools.map((tool) => tool.name),
902
- modelExposed: modelExposedBuiltins,
903
- })
904
- : [];
905
- const providerAliasBuiltinTools = shouldExposeBuiltinTools
906
- ? this.materializeProviderAliasBuiltinTools(builtinExecutableTools, modelExposedBuiltins)
907
- : [];
908
- const modelTools = [
909
- ...appendProviderToolCallAliasTools([...resolvedTools, ...builtinMiddlewareTools]),
910
- ...providerAliasBuiltinTools,
911
- ];
912
- const resolvedMiddleware = await this.resolveMiddleware(binding);
913
- const resolvedSubagents = await this.resolveDeepAgentSubagents(getBindingDeepAgentSubagents(binding), binding, { sessionId: options.sessionId ?? options.legacySessionId });
914
- const resolvedInterruptOn = resolveRunnableInterruptOn(binding);
915
- const resolvedCheckpointer = shouldAttachDeepAgentCheckpointer(binding, resolvedInterruptOn)
916
- ? resolveRunnableCheckpointer(this.options, binding)
917
- : undefined;
918
- const resolvedStore = shouldAttachDeepAgentStore(binding) ? this.options.storeResolver?.(binding) : undefined;
919
- const resolvedSkills = resolveDeepAgentSkillSourcePaths({
920
- workspaceRoot: binding.harnessRuntime.workspaceRoot,
921
- runtimeRoot: binding.harnessRuntime.runtimeRoot,
922
- ownerId: binding.agent.id,
923
- skillPaths: getBindingSkills(binding),
924
- }) ?? [];
925
- const resolvedBackend = shouldAttachDeepAgentBackend(binding)
926
- ? (this.options.backendResolver?.(binding) ?? (resolvedSkills.length > 0 ? this.resolveFilesystemBackend(binding, {
927
- sessionId: options.sessionId ?? options.legacySessionId,
928
- }) : undefined))
929
- : undefined;
930
- if (shouldUseConfigurableDeepAgentAssembly(binding)) {
931
- const assemblyInput = {
932
- resolvedModel,
933
- resolvedTools: modelTools,
934
- resolvedMiddleware,
935
- resolvedSubagents,
936
- resolvedInterruptOn,
937
- resolvedCheckpointer,
938
- resolvedStore,
939
- resolvedBackend,
940
- resolvedSkills,
941
- };
942
- return canUseUpstreamCreateDeepAgentAssembly(binding)
943
- ? this.createUpstreamDeepAgentRunnable(binding, assemblyInput)
944
- : this.createConfigurableDeepAgentRunnable(binding, assemblyInput);
945
- }
946
- throw new Error(`Agent ${binding.agent.id} has no supported deepagent assembly path`);
947
- }
948
- createUpstreamDeepAgentRunnable(binding, input) {
949
- const executionParams = getBindingExecutionParams(binding);
950
- const responseFormat = getBindingExecutionKind(binding) === "deepagent"
951
- ? (executionParams && "responseFormat" in executionParams ? executionParams.responseFormat : undefined)
952
- : undefined;
953
- const contextSchema = getBindingExecutionKind(binding) === "deepagent"
954
- ? (executionParams && "contextSchema" in executionParams ? executionParams.contextSchema : undefined)
955
- : undefined;
956
- return createDeepAgent({
957
- model: input.resolvedModel,
958
- systemPrompt: buildDeepAgentSystemPromptWithCapabilityCatalog({
959
- systemPrompt: getBindingSystemPrompt(binding),
960
- subagents: input.resolvedSubagents,
961
- skills: input.resolvedSkills,
962
- tools: getBindingPrimaryTools(binding),
963
- }),
964
- tools: input.resolvedTools,
965
- middleware: input.resolvedMiddleware,
966
- subagents: input.resolvedSubagents,
967
- ...(responseFormat !== undefined ? { responseFormat: responseFormat } : {}),
968
- ...(contextSchema !== undefined ? { contextSchema: contextSchema } : {}),
969
- ...(input.resolvedCheckpointer !== undefined ? { checkpointer: input.resolvedCheckpointer } : {}),
970
- ...(input.resolvedStore !== undefined ? { store: input.resolvedStore } : {}),
971
- ...(input.resolvedBackend !== undefined ? { backend: input.resolvedBackend } : {}),
972
- ...(input.resolvedInterruptOn !== undefined ? { interruptOn: input.resolvedInterruptOn } : {}),
973
- name: binding.agent.id,
974
- memory: getBindingMemorySources(binding),
975
- skills: input.resolvedSkills,
976
- });
977
- }
978
- createConfigurableDeepAgentRunnable(binding, input) {
979
- const builtinTools = getBindingBuiltinToolsConfig(binding) ?? {};
980
- const backend = (input.resolvedBackend ?? new StateBackend({}));
981
- const inlineSubagents = input.resolvedSubagents.filter((subagent) => !("graphId" in subagent));
982
- const asyncSubagents = input.resolvedSubagents.filter((subagent) => "graphId" in subagent);
983
- const subagents = inlineSubagents;
984
- const subagentDefaultMiddleware = [
985
- ...(builtinTools.todos === false ? [] : [todoListMiddleware()]),
986
- ...(builtinTools.filesystem === false ? [] : [createFilesystemMiddleware({ backend })]),
987
- createSummarizationMiddleware({
988
- model: input.resolvedModel,
989
- backend,
990
- }),
991
- createPatchToolCallsMiddleware(),
992
- ];
993
- const generalPurposeMiddleware = [
994
- ...subagentDefaultMiddleware,
995
- ...(input.resolvedSkills.length > 0 ? [createSkillsMiddleware({
996
- backend,
997
- sources: resolveDeepAgentSkillSourceRootPaths({
998
- workspaceRoot: binding.harnessRuntime.workspaceRoot,
999
- runtimeRoot: binding.harnessRuntime.runtimeRoot,
1000
- ownerId: binding.agent.id,
1001
- skillPaths: input.resolvedSkills,
1002
- }) ?? input.resolvedSkills,
1003
- })] : []),
1004
- ];
1005
- const hasGeneralPurposeOverride = subagents.some((subagent) => subagent.name === "general-purpose");
1006
- const middleware = [
1007
- ...(builtinTools.todos === false ? [] : [todoListMiddleware()]),
1008
- ...(input.resolvedSkills.length > 0 ? [createSkillsMiddleware({
1009
- backend,
1010
- sources: resolveDeepAgentSkillSourceRootPaths({
1011
- workspaceRoot: binding.harnessRuntime.workspaceRoot,
1012
- runtimeRoot: binding.harnessRuntime.runtimeRoot,
1013
- ownerId: binding.agent.id,
1014
- skillPaths: input.resolvedSkills,
1015
- }) ?? input.resolvedSkills,
1016
- })] : []),
1017
- ...(builtinTools.filesystem === false ? [] : [createFilesystemMiddleware({ backend })]),
1018
- createSubAgentMiddleware({
1019
- defaultModel: input.resolvedModel,
1020
- defaultTools: input.resolvedTools,
1021
- defaultMiddleware: subagentDefaultMiddleware,
1022
- generalPurposeMiddleware: generalPurposeMiddleware,
1023
- defaultInterruptOn: input.resolvedInterruptOn,
1024
- subagents: subagents,
1025
- generalPurposeAgent: !hasGeneralPurposeOverride,
1026
- }),
1027
- createSummarizationMiddleware({
1028
- model: input.resolvedModel,
1029
- backend,
1030
- }),
1031
- createPatchToolCallsMiddleware(),
1032
- ...(asyncSubagents.length > 0 ? [createAsyncSubAgentMiddleware({ asyncSubAgents: asyncSubagents })] : []),
1033
- ...input.resolvedMiddleware,
1034
- ...(getBindingMemorySources(binding).length > 0 ? [createMemoryMiddleware({ backend, sources: getBindingMemorySources(binding) })] : []),
1035
- ...(input.resolvedInterruptOn ? [humanInTheLoopMiddleware({ interruptOn: input.resolvedInterruptOn })] : []),
1036
- ];
1037
- const executionParams = getBindingExecutionParams(binding);
1038
- const responseFormat = getBindingExecutionKind(binding) === "deepagent"
1039
- ? (executionParams && "responseFormat" in executionParams ? executionParams.responseFormat : undefined)
1040
- : undefined;
1041
- return createAgent({
1042
- model: input.resolvedModel,
1043
- systemPrompt: buildDeepAgentSystemPromptWithCapabilityCatalog({
1044
- systemPrompt: getBindingSystemPrompt(binding),
1045
- subagents: input.resolvedSubagents,
1046
- skills: input.resolvedSkills,
1047
- tools: getBindingPrimaryTools(binding),
1048
- }),
1049
- tools: input.resolvedTools,
1050
- middleware: middleware,
1051
- name: binding.agent.id,
1052
- ...(input.resolvedCheckpointer !== undefined ? { checkpointer: input.resolvedCheckpointer } : {}),
1053
- ...(input.resolvedStore !== undefined ? { store: input.resolvedStore } : {}),
1054
- ...(responseFormat !== undefined ? { responseFormat: responseFormat } : {}),
1055
- });
1056
- }
1057
- buildRunnableCacheKey(binding, sessionId) {
1058
- const filesystemConfig = getBindingFilesystemConfig(binding);
1059
- const sessionStorage = typeof filesystemConfig?.sessionStorage === "object" && filesystemConfig.sessionStorage
1060
- ? filesystemConfig.sessionStorage
1061
- : undefined;
1062
- const sessionScoped = sessionStorage?.enabled === true;
1063
- const executionParams = getBindingExecutionParams(binding);
1064
- const primaryModel = getBindingPrimaryModel(binding);
1065
- const runnableFingerprint = createHash("sha256").update(JSON.stringify({
1066
- executionKind: getBindingExecutionKind(binding),
1067
- systemPrompt: getBindingSystemPrompt(binding) ?? "",
1068
- responseFormat: executionParams && "responseFormat" in executionParams ? executionParams.responseFormat : undefined,
1069
- model: primaryModel
1070
- ? {
1071
- id: primaryModel.id,
1072
- provider: primaryModel.provider,
1073
- model: primaryModel.model,
1074
- }
1075
- : undefined,
1076
- tools: getBindingPrimaryTools(binding).map((tool) => tool.name).filter(Boolean).sort(),
1077
- })).digest("hex").slice(0, 16);
1078
- return `${binding.agent.sourcePath}::${sessionScoped ? (sessionId ?? "__default__") : "__binding__"}::${runnableFingerprint}`;
1079
- }
1080
- async create(binding, options = {}) {
1081
- const cacheKey = this.buildRunnableCacheKey(binding, options.sessionId ?? options.legacySessionId);
1082
- const cached = this.runnableCache.get(cacheKey);
1083
- if (cached) {
1084
- return cached;
1085
- }
1086
- const pending = this.createRunnable(binding, options);
1087
- this.runnableCache.set(cacheKey, pending);
1088
- try {
1089
- return await pending;
1090
- }
1091
- catch (error) {
1092
- this.runnableCache.delete(cacheKey);
1093
- throw error;
1094
- }
1095
- }
1096
- async invoke(binding, input, sessionId, requestId, resumePayload, history = [], options = {}) {
1097
- const compactDelegation = await this.tryDelegateWithCompactRouter(binding, input, sessionId, requestId, {
1098
- ...options,
1099
- sessionId,
1100
- requestId,
1101
- });
1102
- if (compactDelegation) {
1103
- const compactReport = this.buildCompactDelegationReport(compactDelegation);
1104
- const output = compactDelegation.delegatedSubagentType === null
1105
- ? String(compactDelegation.toolOutput ?? "")
1106
- : this.formatCompactDelegationReportForDisplay(compactReport);
1107
- const delegatedToolResults = Array.isArray(compactDelegation.delegatedResult?.metadata?.executedToolResults)
1108
- ? compactDelegation.delegatedResult.metadata.executedToolResults
1109
- : [];
1110
- return {
1111
- sessionId,
1112
- requestId,
1113
- agentId: binding.agent.id,
1114
- state: compactDelegation.delegatedResult?.state ?? "completed",
1115
- output: sanitizeVisibleText(output),
1116
- finalMessageText: sanitizeVisibleText(output),
1117
- metadata: {
1118
- executedToolResults: [
1119
- {
1120
- toolName: "task",
1121
- output: compactDelegation.toolOutput,
1122
- },
1123
- ...delegatedToolResults,
1124
- ],
1125
- },
1126
- };
1127
- }
1128
- const callRuntime = async (activeBinding, activeRequest) => {
1129
- return this.invokeWithProviderRetry(activeBinding, async () => {
1130
- const runnable = await this.create(activeBinding, { sessionId });
1131
- return (await this.withTimeout(() => runnable.invoke(activeRequest, resolveLangChainInvocationConfig(activeBinding, {
1132
- sessionId,
1133
- requestId,
1134
- context: options.context,
1135
- toolRuntimeContext: this.buildFunctionToolRuntimeContext(activeBinding, {
1136
- ...options,
1137
- sessionId,
1138
- requestId,
1139
- }),
1140
- })), resolveBindingTimeout(activeBinding), "agent invoke", "invoke"));
1141
- });
1142
- };
1143
- const callRuntimeWithToolParseRecovery = async (activeRequest) => {
1144
- return callRuntimeWithToolParseRecoveryHelper({
1145
- binding,
1146
- request: activeRequest,
1147
- resumePayload,
1148
- callRuntime,
1149
- });
1150
- };
1151
- const toolRuntimeContext = this.buildFunctionToolRuntimeContext(binding, {
1152
- ...options,
1153
- sessionId,
1154
- requestId,
1155
- });
1156
- const invokeRequest = () => executeRequestInvocation({
1157
- binding,
1158
- input,
1159
- sessionId,
1160
- requestId,
1161
- resumePayload,
1162
- history,
1163
- invokeOptions: {
1164
- ...options,
1165
- ...(toolRuntimeContext ? { toolRuntimeContext } : {}),
1166
- },
1167
- resolveTools: (tools, currentBinding) => this.resolveTools(tools, currentBinding),
1168
- getToolNameMapping: (currentBinding) => this.getToolNameMapping(currentBinding),
1169
- resolveBuiltinMiddlewareTools: (currentBinding, currentOptions) => this.resolveBuiltinMiddlewareTools(currentBinding, { ...currentOptions, sessionId, requestId }),
1170
- callRuntimeWithToolParseRecovery,
1171
- });
1172
- try {
1173
- return await invokeRequest();
1174
- }
1175
- catch (error) {
1176
- if (!isEmptyFinalAiMessageError(error)) {
1177
- throw error;
1178
- }
1179
- this.invalidateBindingRuntimeCaches(binding);
1180
- return invokeRequest();
1181
- }
1182
- }
1183
- async tryDelegateWithCompactRouter(binding, input, sessionId, requestId, options = {}) {
1184
- if (!isDelegationOnlyDeepAgentBinding(binding)) {
1185
- return null;
1186
- }
1187
- if (!this.options.bindingResolver) {
1188
- return null;
1189
- }
1190
- const primaryModel = getBindingPrimaryModel(binding);
1191
- if (!primaryModel) {
1192
- return null;
1193
- }
1194
- const requestText = extractMessageText(input).trim();
1195
- if (!requestText) {
1196
- return null;
1197
- }
1198
- const subagents = getBindingSubagents(binding);
1199
- const subagentNames = new Set(subagents.map((subagent) => subagent.name));
1200
- const structuredMultiItemRequest = looksLikeStructuredMultiItemRequest(requestText);
1201
- let selection = null;
1202
- const subagentCatalog = subagents
1203
- .map((subagent) => `- ${subagent.name}: ${subagent.description}`)
1204
- .join("\n");
1205
- const routingPolicy = getBindingSystemPrompt(binding);
1206
- const compactRoutingPolicy = buildCompactRouterPolicy(routingPolicy);
1207
- const prompt = [
1208
- primaryModel.init?.think === false ? "/no_think" : "",
1209
- "You are selecting a subagent for a delegation-only agent.",
1210
- "Choose exactly one listed subagent when it can responsibly handle the request.",
1211
- "Use the agent routing policy as authoritative routing configuration when it maps the request meaning to a listed subagent.",
1212
- "When the routing policy says a request class is owned by one listed subagent, keep that request with the configured owner even if the task mentions supporting evidence from other domains.",
1213
- "Do not refuse while any listed subagent can own the request after applying the routing policy.",
1214
- "Refuse only when the request is outside every listed subagent's configured responsibility.",
1215
- compactRoutingPolicy ? "Agent routing policy:" : "",
1216
- compactRoutingPolicy,
1217
- "Return only JSON with this shape:",
1218
- "{\"subagent_type\":\"<listed subagent name>\"}",
1219
- "If no listed subagent can handle the request, return only:",
1220
- "{\"status\":\"refused\",\"reason\":\"No configured subagent can handle the request.\"}",
1221
- "Available subagents:",
1222
- subagentCatalog,
1223
- "User request:",
1224
- requestText,
1225
- ].filter(Boolean).join("\n\n");
1226
- let model = null;
1227
- const invokeRouter = async (activePrompt, operationName) => {
1228
- if (!model || typeof model.invoke !== "function") {
1229
- return null;
1230
- }
1231
- return this.invokeWithProviderRetry(binding, () => this.withTimeout(() => model.invoke(activePrompt, resolveLangChainInvocationConfig(binding, {
1232
- sessionId,
1233
- requestId,
1234
- context: options.context,
1235
- toolRuntimeContext: this.buildFunctionToolRuntimeContext(binding, {
1236
- ...options,
1237
- sessionId,
1238
- requestId,
1239
- }),
1240
- })), resolveBindingTimeout(binding), operationName, "invoke"));
1241
- };
1242
- if (!selection) {
1243
- model = await this.resolveModel(primaryModel);
1244
- if (typeof model.invoke !== "function") {
1245
- return null;
1246
- }
1247
- const routerPrompts = [
1248
- prompt,
1249
- [
1250
- prompt,
1251
- "Your previous router output was invalid.",
1252
- "Return only one JSON object now. Do not include prose, markdown, labels, or tool-call wrappers.",
1253
- ].join("\n\n"),
1254
- [
1255
- primaryModel.init?.think === false ? "/no_think" : "",
1256
- "Select one subagent from this exact list:",
1257
- Array.from(subagentNames).join(", "),
1258
- "Return JSON only:",
1259
- "{\"subagent_type\":\"<one exact listed name>\"}",
1260
- "User request:",
1261
- requestText,
1262
- ].filter(Boolean).join("\n\n"),
1263
- [
1264
- primaryModel.init?.think === false ? "/no_think" : "",
1265
- "JSON only. Pick a listed subagent or refuse.",
1266
- "Listed subagents:",
1267
- Array.from(subagentNames).join(", "),
1268
- "Allowed outputs:",
1269
- "{\"subagent_type\":\"<listed name>\"}",
1270
- "{\"status\":\"refused\",\"reason\":\"No configured subagent can handle the request.\"}",
1271
- "Request:",
1272
- requestText,
1273
- ].filter(Boolean).join("\n\n"),
1274
- ];
1275
- let previousRawText = "";
1276
- for (let index = 0; index < routerPrompts.length; index += 1) {
1277
- const activePrompt = index <= 1 || !previousRawText
1278
- ? routerPrompts[index]
1279
- : [routerPrompts[index], "Previous output:", previousRawText].join("\n\n");
1280
- const raw = await invokeRouter(activePrompt, index === 0 ? "delegation router invoke" : `delegation router retry invoke ${index}`);
1281
- if (raw === null) {
1282
- break;
1283
- }
1284
- previousRawText = readModelText(raw);
1285
- const parsedSelection = parseCompactRouterSelection(previousRawText, subagentNames);
1286
- if (!parsedSelection) {
1287
- continue;
1288
- }
1289
- if (parsedSelection.delegations && parsedSelection.delegations.length > 1) {
1290
- if (selection?.subagentType
1291
- && !parsedSelection.delegations.some((delegation) => delegation.subagentType === selection?.subagentType)) {
1292
- continue;
1293
- }
1294
- selection = parsedSelection;
1295
- break;
1296
- }
1297
- if (!selection || selection.refusedReason || parsedSelection.subagentType) {
1298
- selection = parsedSelection.refusedReason && index < routerPrompts.length - 1
1299
- ? selection
1300
- : parsedSelection;
1301
- }
1302
- }
1303
- }
1304
- if (selection?.delegations && selection.delegations.length > 1) {
1305
- const aggregateToolResults = [];
1306
- const childReports = [];
1307
- for (const planned of selection.delegations) {
1308
- const selectedBinding = this.options.bindingResolver(planned.subagentType);
1309
- if (!selectedBinding) {
1310
- const output = `Configured subagent '${planned.subagentType}' could not be resolved.`;
1311
- childReports.push({
1312
- subagentType: planned.subagentType,
1313
- result: {
1314
- sessionId,
1315
- requestId: `${requestId}:${planned.subagentType}`,
1316
- agentId: planned.subagentType,
1317
- state: "failed",
1318
- output,
1319
- finalMessageText: output,
1320
- metadata: { executedToolResults: [] },
1321
- },
1322
- output,
1323
- });
1324
- continue;
1325
- }
1326
- const delegatedResult = await this.invoke(selectedBinding, buildDelegatedOwnedTaskInstruction({
1327
- subagentType: planned.subagentType,
1328
- taskText: planned.description,
1329
- originalRequest: requestText,
1330
- }), sessionId, `${requestId}:${planned.subagentType}`, undefined, [], {
1331
- context: options.context,
1332
- state: options.state,
1333
- files: options.files,
1334
- memoryContext: options.memoryContext,
1335
- });
1336
- const executedToolResults = Array.isArray(delegatedResult.metadata?.executedToolResults)
1337
- ? delegatedResult.metadata.executedToolResults
1338
- : [];
1339
- aggregateToolResults.push(...executedToolResults);
1340
- childReports.push({
1341
- subagentType: planned.subagentType,
1342
- result: delegatedResult,
1343
- output: typeof delegatedResult.output === "string" ? delegatedResult.output : String(delegatedResult.output ?? ""),
1344
- });
1345
- }
1346
- const failedChildren = childReports.filter((child) => child.result.state === "failed");
1347
- const uniqueToolNames = [...new Set(aggregateToolResults.map((toolResult) => toolResult.toolName))];
1348
- const status = failedChildren.length > 0 ? "failed" : "completed";
1349
- const report = childReports
1350
- .map((child) => `## ${child.subagentType}\n${child.output.trim() || "No visible output returned."}`)
1351
- .join("\n\n");
1352
- const output = JSON.stringify({
1353
- status,
1354
- routing: selection.delegations.map((planned, index) => `${index + 1}) 路由判断: ${planned.subagentType} 负责 ${planned.description.trim() || "该专业域子任务"}。`),
1355
- plan: selection.delegations.map((planned, index) => `${index + 1}) 委托 ${planned.subagentType}: ${planned.description.trim() || "执行其专业域任务"}。`),
1356
- execution: childReports.map((child, index) => `${index + 1}) ${child.subagentType} ${child.result.state === "failed" ? "failed" : "completed"}。`),
1357
- todoTrace: childReports.map((child, index) => `${index + 1}) ${child.subagentType}: ${hasDelegatedPlanEvidence(child.result) ? "TODO evidence observed" : "TODO evidence missing"}。`),
1358
- stepResults: childReports.map((child, index) => `${index + 1}) ${child.subagentType}: delegated result collected; aggregate tools = ${uniqueToolNames.length > 0 ? uniqueToolNames.join(", ") : "none"}。`),
1359
- summary: [
1360
- status === "failed"
1361
- ? `多 specialist 编排完成,但 ${failedChildren.length} 个委托返回 failed。`
1362
- : "多 specialist 编排已完成,所有委托均返回 completed。",
1363
- ],
1364
- findings: childReports.map((child) => `${child.subagentType}: ${child.output.trim().slice(0, 500) || "No finding text returned."}`),
1365
- blockers: failedChildren.length > 0
1366
- ? failedChildren.map((child) => `${child.subagentType}: delegated execution failed.`)
1367
- : ["none"],
1368
- nextActions: failedChildren.length > 0
1369
- ? ["查看 failed specialist 的 blocker 并单独重跑该委托。"]
1370
- : ["可基于各 specialist 结果继续做最终修复或发布决策。"],
1371
- report,
1372
- });
1373
- return {
1374
- toolOutput: output,
1375
- delegatedSubagentType: "multiple",
1376
- delegatedResult: {
1377
- sessionId,
1378
- requestId,
1379
- agentId: binding.agent.id,
1380
- state: status,
1381
- output,
1382
- finalMessageText: output,
1383
- metadata: {
1384
- executedToolResults: aggregateToolResults,
1385
- delegations: childReports.map((child) => ({
1386
- subagentType: child.subagentType,
1387
- state: child.result.state,
1388
- })),
1389
- },
1390
- },
1391
- };
1392
- }
1393
- if (selection?.delegations && selection.delegations.length === 1) {
1394
- selection = { subagentType: selection.delegations[0].subagentType };
1395
- }
1396
- if (selection?.refusedReason) {
1397
- return {
1398
- toolOutput: selection.refusedReason,
1399
- delegatedSubagentType: null,
1400
- delegatedResult: {
1401
- sessionId,
1402
- requestId,
1403
- agentId: binding.agent.id,
1404
- state: "failed",
1405
- output: selection.refusedReason,
1406
- finalMessageText: selection.refusedReason,
1407
- },
1408
- };
1409
- }
1410
- let subagentType = selection?.subagentType ?? "";
1411
- if (!subagentNames.has(subagentType)) {
1412
- return null;
1413
- }
1414
- const selectedBinding = this.options.bindingResolver(subagentType);
1415
- if (!selectedBinding) {
1416
- return null;
1417
- }
1418
- const runDelegatedRequest = async (text, requestSuffix = "", delegatedOptions = {}) => {
1419
- const result = await this.invoke(selectedBinding, text, sessionId, `${requestId}:${subagentType}${requestSuffix}`, undefined, [], {
1420
- context: options.context,
1421
- state: options.state,
1422
- files: options.files,
1423
- memoryContext: options.memoryContext,
1424
- ...delegatedOptions,
1425
- });
1426
- if (delegatedOptions.externalPlanEvidence === true) {
1427
- return {
1428
- ...result,
1429
- metadata: {
1430
- ...(result.metadata ?? {}),
1431
- externalPlanEvidence: true,
1432
- },
1433
- };
1434
- }
1435
- return result;
1436
- };
1437
- let delegatedResult;
1438
- try {
1439
- delegatedResult = await runDelegatedRequest(requestText);
1440
- }
1441
- catch (error) {
1442
- if (selectedBinding.harnessRuntime.executionContract?.requiresPlan === true) {
1443
- try {
1444
- delegatedResult = await runDelegatedRequest([requestText, DELEGATED_PLAN_EVIDENCE_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-retry");
1445
- }
1446
- catch (recoveryError) {
1447
- const output = recoveryError instanceof Error ? recoveryError.message : String(recoveryError);
1448
- return {
1449
- toolOutput: output,
1450
- delegatedSubagentType: subagentType,
1451
- delegatedResult: {
1452
- sessionId,
1453
- requestId,
1454
- agentId: selectedBinding.agent.id,
1455
- state: "failed",
1456
- output,
1457
- finalMessageText: output,
1458
- },
1459
- };
1460
- }
1461
- }
1462
- else {
1463
- const output = error instanceof Error ? error.message : String(error);
1464
- return {
1465
- toolOutput: output,
1466
- delegatedSubagentType: subagentType,
1467
- delegatedResult: {
1468
- sessionId,
1469
- requestId,
1470
- agentId: selectedBinding.agent.id,
1471
- state: "failed",
1472
- output,
1473
- finalMessageText: output,
1474
- },
1475
- };
1476
- }
1477
- }
1478
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
1479
- try {
1480
- delegatedResult = await runDelegatedRequest([requestText, DELEGATED_PLAN_EVIDENCE_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-retry");
1481
- }
1482
- catch (error) {
1483
- const output = error instanceof Error ? error.message : String(error);
1484
- return {
1485
- toolOutput: output,
1486
- delegatedSubagentType: subagentType,
1487
- delegatedResult: {
1488
- ...delegatedResult,
1489
- state: "failed",
1490
- output,
1491
- finalMessageText: output,
1492
- },
1493
- };
1494
- }
1495
- }
1496
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
1497
- const previousDelegatedResult = delegatedResult;
1498
- try {
1499
- delegatedResult = mergeDelegatedResultToolEvidence(await runDelegatedRequest([requestText, DELEGATED_PLAN_EVIDENCE_FINAL_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-final-retry", buildDelegatedPlanEvidenceRecoveryOptions(selectedBinding, options, requestText)), previousDelegatedResult);
1500
- }
1501
- catch (error) {
1502
- const output = error instanceof Error ? error.message : String(error);
1503
- return {
1504
- toolOutput: output,
1505
- delegatedSubagentType: subagentType,
1506
- delegatedResult: {
1507
- ...delegatedResult,
1508
- state: "failed",
1509
- output,
1510
- finalMessageText: output,
1511
- },
1512
- };
1513
- }
1514
- }
1515
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
1516
- const output = buildDelegatedPlanEvidenceBlocker(selectedBinding.agent.id);
1517
- return {
1518
- toolOutput: output,
1519
- delegatedSubagentType: subagentType,
1520
- delegatedResult: {
1521
- ...delegatedResult,
1522
- state: "failed",
1523
- output,
1524
- finalMessageText: output,
1525
- },
1526
- };
1527
- }
1528
- return {
1529
- toolOutput: resolveDelegatedResultOutput(delegatedResult),
1530
- delegatedSubagentType: subagentType,
1531
- delegatedResult,
1532
- };
1533
- }
1534
- buildCompactDelegationReport(compactDelegation) {
1535
- const delegatedSubagentType = compactDelegation.delegatedSubagentType ?? "unknown";
1536
- const delegatedOutput = typeof compactDelegation.toolOutput === "string"
1537
- ? [compactDelegation.toolOutput]
1538
- : [];
1539
- const delegatedPayload = (() => {
1540
- if (delegatedOutput.length === 0) {
1541
- return undefined;
1542
- }
1543
- try {
1544
- const parsed = JSON.parse(delegatedOutput[0]);
1545
- return parsed && typeof parsed === "object" && !Array.isArray(parsed)
1546
- ? parsed
1547
- : undefined;
1548
- }
1549
- catch {
1550
- return undefined;
1551
- }
1552
- })();
1553
- const payloadStringArray = (key) => {
1554
- const value = delegatedPayload?.[key];
1555
- if (!Array.isArray(value)) {
1556
- return undefined;
1557
- }
1558
- const items = value.filter((item) => typeof item === "string" && item.trim().length > 0);
1559
- return items.length > 0 ? items : undefined;
1560
- };
1561
- const payloadReport = typeof delegatedPayload?.report === "string" && delegatedPayload.report.trim().length > 0
1562
- ? delegatedPayload.report
1563
- : undefined;
1564
- const delegatedToolNames = Array.isArray(compactDelegation.delegatedResult?.metadata?.executedToolResults)
1565
- ? compactDelegation.delegatedResult.metadata.executedToolResults
1566
- .filter((toolResult) => toolResult?.toolName)
1567
- .map((toolResult) => toolResult.toolName)
1568
- : [];
1569
- const state = compactDelegation.delegatedResult?.state === "failed" ? "failed" : "completed";
1570
- const uniqueToolNames = [...new Set(delegatedToolNames)];
1571
- const toolEvidence = uniqueToolNames.length > 0 ? uniqueToolNames.join(", ") : "none";
1572
- const hasPlanEvidence = hasDelegatedPlanEvidence(compactDelegation.delegatedResult);
1573
- const fallbackTodoTrace = [
1574
- `1) TODO observed: delegated to ${delegatedSubagentType}.`,
1575
- hasPlanEvidence
1576
- ? `2) ${delegatedSubagentType}: TODO evidence observed; delegated specialist invoked write_todos.`
1577
- : `2) ${delegatedSubagentType}: TODO evidence missing; delegated specialist did not expose write_todos in returned metadata.`,
1578
- state === "failed"
1579
- ? "3) TODO closed: delegated execution failed; blocker reported."
1580
- : "3) TODO closed: delegated execution completed; synthesis returned.",
1581
- ];
1582
- const fallbackStepResults = [
1583
- `1) Delegation step: task invoked ${delegatedSubagentType}.`,
1584
- `2) Evidence step: delegated tool evidence = ${toolEvidence}.`,
1585
- state === "failed"
1586
- ? "3) Synthesis step: returned blocker report because delegated execution failed."
1587
- : "3) Synthesis step: compact delegation report assembled from delegated output.",
1588
- ];
1589
- const fallbackSummary = [
1590
- state === "failed"
1591
- ? `子代理 ${delegatedSubagentType} 委托执行失败。`
1592
- : `已完成子代理 ${delegatedSubagentType} 委托执行。`,
1593
- ];
1594
- const fallbackFindings = payloadReport
1595
- ? ["子代理返回了结构化报告,详见 report。"]
1596
- : delegatedOutput.length > 0
1597
- ? delegatedOutput.slice(0, 3)
1598
- : ["none"];
1599
- const report = payloadReport ?? (delegatedOutput.join("\n") || "委托已完成,未返回附加报告。");
1600
- return {
1601
- status: state,
1602
- routing: [
1603
- `1) 路由判断: 已选择 sub-agent = ${delegatedSubagentType}。`,
1604
- ],
1605
- plan: [
1606
- "1) 选择具备匹配能力的子代理并创建委托任务。",
1607
- "2) 执行子代理的原生工作流并收集委托工具输出。",
1608
- "3) 合成汇总报告并返回给用户。",
1609
- ],
1610
- execution: [
1611
- `1) 调用 task 工具,目标子代理:${delegatedSubagentType}`,
1612
- uniqueToolNames.length > 0
1613
- ? `2) 子代理返回工具证据:${toolEvidence}`
1614
- : "2) 子代理返回文本结果。",
1615
- "3) 产出主编排汇总并返回结构化结果。",
1616
- ],
1617
- todoTrace: payloadStringArray("todoTrace") ?? fallbackTodoTrace,
1618
- stepResults: payloadStringArray("stepResults") ?? fallbackStepResults,
1619
- summary: payloadStringArray("summary") ?? fallbackSummary,
1620
- findings: payloadStringArray("findings") ?? fallbackFindings,
1621
- blockers: state === "failed" ? ["子代理执行未能完成。"] : ["none"],
1622
- nextActions: ["如需更深入,可继续追问该次委托的细节。"],
1623
- report,
1624
- };
1625
- }
1626
- formatCompactDelegationReportForDisplay(report) {
1627
- const reportText = typeof report.report === "string" ? report.report.trim() : "";
1628
- if (reportText && looksLikeRawCommandTranscript(reportText)) {
1629
- return JSON.stringify(report);
1630
- }
1631
- if (reportText) {
1632
- return reportText;
1633
- }
1634
- const summary = Array.isArray(report.summary)
1635
- ? report.summary.find((item) => typeof item === "string" && item.trim().length > 0)
1636
- : undefined;
1637
- return summary?.trim() || "委托已完成,未返回附加报告。";
1638
- }
1639
- async *streamDelegateWithCompactRouter(binding, input, sessionId, requestId, options = {}) {
1640
- if (!isDelegationOnlyDeepAgentBinding(binding) || !this.options.bindingResolver) {
1641
- return null;
1642
- }
1643
- const primaryModel = getBindingPrimaryModel(binding);
1644
- if (!primaryModel) {
1645
- return null;
1646
- }
1647
- const requestText = extractMessageText(input).trim();
1648
- if (!requestText) {
1649
- return null;
1650
- }
1651
- const subagents = getBindingSubagents(binding);
1652
- const subagentNames = new Set(subagents.map((subagent) => subagent.name));
1653
- const structuredMultiItemRequest = looksLikeStructuredMultiItemRequest(requestText);
1654
- let selection = null;
1655
- const subagentCatalog = subagents
1656
- .map((subagent) => `- ${subagent.name}: ${subagent.description}`)
1657
- .join("\n");
1658
- const routingPolicy = getBindingSystemPrompt(binding);
1659
- const compactRoutingPolicy = buildCompactRouterPolicy(routingPolicy);
1660
- const prompt = [
1661
- primaryModel.init?.think === false ? "/no_think" : "",
1662
- "You are planning delegation for a delegation-only agent.",
1663
- "Choose exactly one listed subagent when one specialist can responsibly handle the request.",
1664
- "If the request naturally requires multiple specialist-owned steps, return an ordered delegation plan instead of one subagent.",
1665
- "A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.",
1666
- "Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.",
1667
- "For multi-line or numbered requests, evaluate every requested item semantically before choosing the final owner list.",
1668
- "Use the agent routing policy as authoritative routing configuration when it maps request meaning to listed subagents.",
1669
- "Apply the routing policy and subagent catalog literally; do not assign work to a subagent when the policy says that subagent is not the owner.",
1670
- "When the routing policy or subagent catalog says a request class routes to one owner only, choose that single owner.",
1671
- "Evidence dimensions inside one request, such as tools, files, CI, output format, failure states, routing, or runtime paths, are inputs to the selected owner; they do not create extra owners unless the user asks those specialists to do their own work.",
1672
- "A request made from one specialist perspective is single-owner when that specialist can responsibly handle the whole requested assessment.",
1673
- "Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.",
1674
- "Do not merge one listed subagent's configured responsibility into another listed subagent's task.",
1675
- "A broad request can still be handleable when multiple listed subagents each own part of it; return a delegation plan in that case.",
1676
- "Do not refuse while any listed subagent can own the request or a subtask after applying the routing policy.",
1677
- "Refuse only when the request is outside every listed subagent's configured responsibility.",
1678
- compactRoutingPolicy ? "Agent routing policy:" : "",
1679
- compactRoutingPolicy,
1680
- "For one specialist, return only JSON with this shape:",
1681
- "{\"subagent_type\":\"<listed subagent name>\"}",
1682
- "For multiple specialist steps, return only JSON with this shape:",
1683
- "{\"delegations\":[{\"subagent_type\":\"<listed subagent name>\",\"description\":\"<only that specialist's owned portion>\"}]}",
1684
- "If no listed subagent can handle the request, return only:",
1685
- "{\"status\":\"refused\",\"reason\":\"No configured subagent can handle the request.\"}",
1686
- "Available subagents:",
1687
- subagentCatalog,
1688
- "User request:",
1689
- requestText,
1690
- ].filter(Boolean).join("\n\n");
1691
- let model = null;
1692
- const invokeRouter = async (activePrompt, operationName) => {
1693
- if (!model || typeof model.invoke !== "function") {
1694
- return null;
1695
- }
1696
- return this.invokeWithProviderRetry(binding, () => this.withTimeout(() => model.invoke(activePrompt, resolveLangChainInvocationConfig(binding, {
1697
- sessionId,
1698
- requestId,
1699
- context: options.context,
1700
- toolRuntimeContext: this.buildFunctionToolRuntimeContext(binding, {
1701
- ...options,
1702
- sessionId,
1703
- requestId,
1704
- }),
1705
- })), resolveBindingTimeout(binding), operationName, "invoke"));
1706
- };
1707
- if (!selection) {
1708
- model = await this.resolveModel(primaryModel);
1709
- if (typeof model.invoke !== "function") {
1710
- return null;
1711
- }
1712
- const routerPrompts = [
1713
- prompt,
1714
- [
1715
- prompt,
1716
- "Your previous router output was invalid.",
1717
- "Return only one JSON object now. Do not include prose, markdown, labels, or tool-call wrappers.",
1718
- ].join("\n\n"),
1719
- [
1720
- primaryModel.init?.think === false ? "/no_think" : "",
1721
- "Select one subagent or an ordered delegation plan from this exact list:",
1722
- Array.from(subagentNames).join(", "),
1723
- "Return JSON only. Single-specialist shape:",
1724
- "{\"subagent_type\":\"<one exact listed name>\"}",
1725
- "Multi-specialist shape:",
1726
- "{\"delegations\":[{\"subagent_type\":\"<one exact listed name>\",\"description\":\"<owned subtask>\"}]}",
1727
- "User request:",
1728
- requestText,
1729
- ].filter(Boolean).join("\n\n"),
1730
- [
1731
- primaryModel.init?.think === false ? "/no_think" : "",
1732
- "JSON only. Pick a listed subagent, return delegations, or refuse.",
1733
- "Listed subagents:",
1734
- Array.from(subagentNames).join(", "),
1735
- "Allowed outputs:",
1736
- "{\"subagent_type\":\"<listed name>\"}",
1737
- "{\"delegations\":[{\"subagent_type\":\"<listed name>\",\"description\":\"<owned subtask>\"}]}",
1738
- "{\"status\":\"refused\",\"reason\":\"No configured subagent can handle the request.\"}",
1739
- "Request:",
1740
- requestText,
1741
- ].filter(Boolean).join("\n\n"),
1742
- [
1743
- primaryModel.init?.think === false ? "/no_think" : "",
1744
- "Multi-specialist delegation is supported.",
1745
- "If a request needs multiple listed specialists, that is not a refusal condition.",
1746
- "A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.",
1747
- "Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.",
1748
- "Return a delegations array that assigns each specialist-owned work item to listed subagents.",
1749
- "Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.",
1750
- "Do not merge one listed subagent's configured responsibility into another listed subagent's task.",
1751
- "Do not turn supporting evidence dimensions into separate owners when one listed subagent owns the requested assessment.",
1752
- "Never return final response fields such as routing, todoTrace, stepResults, summary, findings, blockers, nextActions, or report.",
1753
- "Return JSON only with this exact shape:",
1754
- "{\"delegations\":[{\"subagent_type\":\"<one exact listed name>\",\"description\":\"<owned subtask>\"}]}",
1755
- compactRoutingPolicy ? "Agent routing policy:" : "",
1756
- compactRoutingPolicy,
1757
- "Available subagents:",
1758
- subagentCatalog,
1759
- "User request:",
1760
- requestText,
1761
- ].filter(Boolean).join("\n\n"),
1762
- ];
1763
- let previousRawText = "";
1764
- for (let index = 0; index < routerPrompts.length; index += 1) {
1765
- const activePrompt = index <= 1 || !previousRawText
1766
- ? routerPrompts[index]
1767
- : [routerPrompts[index], "Previous output:", previousRawText].join("\n\n");
1768
- const raw = await invokeRouter(activePrompt, index === 0 ? "delegation router invoke" : `delegation router retry invoke ${index}`);
1769
- if (raw === null) {
1770
- break;
1771
- }
1772
- previousRawText = readModelText(raw);
1773
- const parsedSelection = parseCompactRouterSelection(previousRawText, subagentNames);
1774
- if (!parsedSelection) {
1775
- continue;
1776
- }
1777
- if (parsedSelection.delegations && parsedSelection.delegations.length > 1) {
1778
- selection = parsedSelection;
1779
- break;
1780
- }
1781
- if (parsedSelection.subagentType && !structuredMultiItemRequest) {
1782
- selection = parsedSelection;
1783
- break;
1784
- }
1785
- if (!selection || selection.refusedReason || parsedSelection.subagentType) {
1786
- selection = parsedSelection.refusedReason && index < routerPrompts.length - 1
1787
- ? selection
1788
- : parsedSelection;
1789
- }
1790
- }
1791
- }
1792
- if (selection?.delegations || selection?.subagentType) {
1793
- const candidateDelegations = selection.delegations ?? [{
1794
- subagentType: selection.subagentType,
1795
- description: requestText,
1796
- }];
1797
- const candidatePlan = candidateDelegations
1798
- .map((item, index) => `${index + 1}. ${item.subagentType}: ${item.description}`)
1799
- .join("\n");
1800
- const coveragePrompt = [
1801
- primaryModel.init?.think === false ? "/no_think" : "",
1802
- "Verify this delegation plan against the user request and routing policy.",
1803
- "Internally review every sentence or list item in the user request before returning JSON.",
1804
- "Return one corrected JSON object only.",
1805
- "Keep the candidate plan unchanged when it already covers every specialist-owned work item.",
1806
- "Return a single subagent_type when one listed subagent owns the whole request and the candidate plan only split supporting evidence dimensions.",
1807
- "A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.",
1808
- "Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.",
1809
- "If the candidate omits a specialist-owned work item, add that listed subagent in the correct user-requested order.",
1810
- "If the candidate includes a subagent whose described work is not owned by that subagent, remove or replace it.",
1811
- "Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.",
1812
- "Do not merge one listed subagent's configured responsibility into another listed subagent's task.",
1813
- "Do not turn supporting evidence dimensions into separate owners when one listed subagent owns the requested assessment.",
1814
- "Do not add a subagent unless the routing policy or subagent catalog makes ownership clear.",
1815
- "When the routing policy states that a subagent is not the owner for a domain, do not assign that domain to that subagent.",
1816
- "Use only listed subagent names.",
1817
- compactRoutingPolicy ? "Agent routing policy:" : "",
1818
- compactRoutingPolicy,
1819
- "Available subagents:",
1820
- subagentCatalog,
1821
- "Candidate delegation plan:",
1822
- candidatePlan,
1823
- "Allowed JSON shapes:",
1824
- "{\"subagent_type\":\"<listed subagent name>\"}",
1825
- "{\"delegations\":[{\"subagent_type\":\"<listed subagent name>\",\"description\":\"<only that specialist's owned portion>\"}]}",
1826
- "User request:",
1827
- requestText,
1828
- ].filter(Boolean).join("\n\n");
1829
- const rawCoverage = await invokeRouter(coveragePrompt, "delegation router coverage invoke");
1830
- if (rawCoverage !== null) {
1831
- const coverageText = readModelText(rawCoverage);
1832
- const coverageSelection = parseCompactRouterSelection(coverageText, subagentNames);
1833
- if (coverageSelection?.subagentType && !structuredMultiItemRequest) {
1834
- selection = coverageSelection;
1835
- }
1836
- if (coverageSelection?.delegations && coverageSelection.delegations.length === 1 && !structuredMultiItemRequest) {
1837
- selection = { subagentType: coverageSelection.delegations[0].subagentType };
1838
- }
1839
- if (coverageSelection?.delegations && coverageSelection.delegations.length > 1) {
1840
- const candidateNames = new Set(candidateDelegations.map((item) => item.subagentType));
1841
- const coverageNames = new Set(coverageSelection.delegations.map((item) => item.subagentType));
1842
- const preservesCandidateOwners = Array.from(candidateNames).every((name) => coverageNames.has(name));
1843
- if (preservesCandidateOwners) {
1844
- selection = coverageSelection;
1845
- }
1846
- }
1847
- }
1848
- if (candidateDelegations.length > 1 && selection?.delegations && selection.delegations.length > 1) {
1849
- const activePlan = selection.delegations
1850
- .map((item, index) => `${index + 1}. ${item.subagentType}: ${item.description}`)
1851
- .join("\n");
1852
- const arbitrationPrompt = [
1853
- primaryModel.init?.think === false ? "/no_think" : "",
1854
- "Arbitrate whether this delegation plan is over-split.",
1855
- "The runtime supports both one-owner and multi-owner delegation.",
1856
- "Choose one owner when the routing policy or subagent catalog says one listed subagent owns the whole request.",
1857
- "A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.",
1858
- "Treat supporting evidence dimensions as inputs to that owner, not as separate owners.",
1859
- "Keep multi-owner delegation only when the user asked for multiple independently owned specialist work items.",
1860
- "Return exactly one JSON object and no prose.",
1861
- "Single-owner shape:",
1862
- "{\"subagent_type\":\"<listed subagent name>\"}",
1863
- "Multi-owner shape:",
1864
- "{\"delegations\":[{\"subagent_type\":\"<listed subagent name>\",\"description\":\"<only that specialist's owned portion>\"}]}",
1865
- compactRoutingPolicy ? "Agent routing policy:" : "",
1866
- compactRoutingPolicy,
1867
- "Available subagents:",
1868
- subagentCatalog,
1869
- "Candidate plan:",
1870
- activePlan,
1871
- "User request:",
1872
- requestText,
1873
- ].filter(Boolean).join("\n\n");
1874
- const rawArbitration = await invokeRouter(arbitrationPrompt, "delegation router over-split arbitration invoke");
1875
- if (rawArbitration !== null) {
1876
- const arbitrationText = readModelText(rawArbitration);
1877
- const arbitrationSelection = parseCompactRouterSelection(arbitrationText, subagentNames);
1878
- if (arbitrationSelection?.subagentType && !structuredMultiItemRequest) {
1879
- selection = arbitrationSelection;
1880
- }
1881
- else if (arbitrationSelection?.delegations && arbitrationSelection.delegations.length === 1 && !structuredMultiItemRequest) {
1882
- selection = { subagentType: arbitrationSelection.delegations[0].subagentType };
1883
- }
1884
- else if (arbitrationSelection?.delegations && arbitrationSelection.delegations.length > 1) {
1885
- selection = arbitrationSelection;
1886
- }
1887
- }
1888
- }
1889
- }
1890
- if (selection?.delegations?.length === 1) {
1891
- const onlyDelegation = selection.delegations[0];
1892
- selection = { subagentType: onlyDelegation.subagentType };
1893
- }
1894
- if (selection?.delegations && selection.delegations.length > 1) {
1895
- const plannedDelegations = selection.delegations;
1896
- const executableDelegations = plannedDelegations;
1897
- const aggregateToolResults = [];
1898
- const childReports = [];
1899
- yield {
1900
- kind: "commentary",
1901
- content: `Planned delegation tree: ${executableDelegations.map((item) => item.subagentType).join(" -> ")}.`,
1902
- agentId: binding.agent.id,
1903
- };
1904
- const runPlannedDelegation = async function* (subagentType, text, requestIdSuffix = "", delegatedOptions = {}) {
1905
- const selectedBinding = this.options.bindingResolver?.(subagentType);
1906
- if (!selectedBinding) {
1907
- const output = `Configured subagent '${subagentType}' could not be resolved.`;
1908
- return {
1909
- sessionId,
1910
- requestId: `${requestId}:${subagentType}${requestIdSuffix}`,
1911
- agentId: subagentType,
1912
- state: "failed",
1913
- output,
1914
- finalMessageText: output,
1915
- metadata: { executedToolResults: [] },
1916
- };
1917
- }
1918
- const executedToolResults = [];
1919
- let output = "";
1920
- try {
1921
- for await (const chunk of this.stream(selectedBinding, text, sessionId, [], {
1922
- context: options.context,
1923
- state: delegatedOptions.state ?? options.state,
1924
- files: options.files,
1925
- requestId: `${requestId}:${subagentType}${requestIdSuffix}`,
1926
- memoryContext: options.memoryContext,
1927
- profiling: options.profiling,
1928
- suppressInitialRequiredPlanInstruction: delegatedOptions.suppressInitialRequiredPlanInstruction,
1929
- externalPlanEvidence: delegatedOptions.externalPlanEvidence,
1930
- })) {
1931
- if (typeof chunk === "string") {
1932
- output += chunk;
1933
- continue;
1934
- }
1935
- if (chunk.kind === "content") {
1936
- output += chunk.content ?? "";
1937
- continue;
1938
- }
1939
- if (chunk.kind === "tool-result") {
1940
- appendUniqueToolEvidence(executedToolResults, {
1941
- toolName: chunk.toolName,
1942
- output: chunk.output,
1943
- ...(chunk.isError !== undefined ? { isError: chunk.isError } : {}),
1944
- });
1945
- }
1946
- if (chunk.kind === "upstream-event") {
1947
- const streamedEvidence = readUpstreamToolEvidence(chunk.event);
1948
- if (streamedEvidence) {
1949
- appendUniqueToolEvidence(executedToolResults, streamedEvidence);
1950
- }
1951
- }
1952
- yield { ...chunk, agentId: chunk.agentId ?? selectedBinding.agent.id };
1953
- }
1954
- }
1955
- catch (error) {
1956
- output = error instanceof Error ? error.message : String(error);
1957
- return {
1958
- sessionId,
1959
- requestId: `${requestId}:${subagentType}${requestIdSuffix}`,
1960
- agentId: selectedBinding.agent.id,
1961
- state: "failed",
1962
- output,
1963
- finalMessageText: output,
1964
- metadata: {
1965
- executedToolResults,
1966
- ...(delegatedOptions.externalPlanEvidence === true ? { externalPlanEvidence: true } : {}),
1967
- },
1968
- };
1969
- }
1970
- const finalOutput = delegatedOptions.externalPlanEvidence === true && hasNonPlanToolEvidenceItems(executedToolResults)
1971
- ? buildDelegatedExternalPlanEvidenceSummary(executedToolResults)
1972
- : sanitizeVisibleText(output);
1973
- return {
1974
- sessionId,
1975
- requestId: `${requestId}:${subagentType}${requestIdSuffix}`,
1976
- agentId: selectedBinding.agent.id,
1977
- state: "completed",
1978
- output: finalOutput,
1979
- finalMessageText: finalOutput,
1980
- metadata: {
1981
- executedToolResults,
1982
- ...(delegatedOptions.externalPlanEvidence === true ? { externalPlanEvidence: true } : {}),
1983
- },
1984
- };
1985
- }.bind(this);
1986
- for (const [index, planned] of executableDelegations.entries()) {
1987
- const selectedBinding = this.options.bindingResolver?.(planned.subagentType);
1988
- const delegatedText = buildDelegatedOwnedTaskInstruction({
1989
- subagentType: planned.subagentType,
1990
- taskText: planned.description,
1991
- originalRequest: requestText,
1992
- });
1993
- yield {
1994
- kind: "commentary",
1995
- content: `Delegating to ${planned.subagentType}.`,
1996
- agentId: binding.agent.id,
1997
- };
1998
- yield {
1999
- kind: "commentary",
2000
- content: "Starting delegated execution.",
2001
- agentId: selectedBinding?.agent.id ?? planned.subagentType,
2002
- };
2003
- let delegatedResult = yield* runPlannedDelegation(planned.subagentType, delegatedText);
2004
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2005
- const previousDelegatedResult = delegatedResult;
2006
- delegatedResult = mergeDelegatedResultToolEvidence(yield* runPlannedDelegation(planned.subagentType, [delegatedText, DELEGATED_PLAN_EVIDENCE_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-retry"), previousDelegatedResult);
2007
- }
2008
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2009
- const previousDelegatedResult = delegatedResult;
2010
- delegatedResult = mergeDelegatedResultToolEvidence(yield* runPlannedDelegation(planned.subagentType, [delegatedText, DELEGATED_PLAN_EVIDENCE_FINAL_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-final-retry", buildDelegatedPlanEvidenceRecoveryOptions(selectedBinding, options, delegatedText)), previousDelegatedResult);
2011
- }
2012
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2013
- const output = buildDelegatedPlanEvidenceBlocker(selectedBinding?.agent.id ?? planned.subagentType);
2014
- delegatedResult = {
2015
- ...delegatedResult,
2016
- state: "failed",
2017
- output,
2018
- finalMessageText: output,
2019
- };
2020
- }
2021
- const delegatedToolResults = Array.isArray(delegatedResult.metadata?.executedToolResults)
2022
- ? delegatedResult.metadata.executedToolResults
2023
- : [];
2024
- for (const toolResult of delegatedToolResults) {
2025
- if (typeof toolResult.toolName !== "string") {
2026
- continue;
2027
- }
2028
- appendUniqueToolEvidence(aggregateToolResults, {
2029
- toolName: toolResult.toolName,
2030
- output: toolResult.output,
2031
- ...(toolResult.isError !== undefined ? { isError: Boolean(toolResult.isError) } : {}),
2032
- });
2033
- if (isPlanToolName(toolResult.toolName)) {
2034
- continue;
2035
- }
2036
- yield {
2037
- kind: "commentary",
2038
- content: `Running tool ${toolResult.toolName}.`,
2039
- agentId: selectedBinding?.agent.id ?? planned.subagentType,
2040
- };
2041
- yield {
2042
- kind: "commentary",
2043
- content: `Tool ${toolResult.toolName} ${toolResult.isError === true ? "failed" : "completed"}.`,
2044
- agentId: selectedBinding?.agent.id ?? planned.subagentType,
2045
- };
2046
- }
2047
- childReports.push({
2048
- subagentType: planned.subagentType,
2049
- result: delegatedResult,
2050
- output: typeof delegatedResult.output === "string" ? delegatedResult.output : String(delegatedResult.output ?? ""),
2051
- });
2052
- if (index < executableDelegations.length - 1) {
2053
- yield {
2054
- kind: "commentary",
2055
- content: "Continuing ordered delegation plan.",
2056
- agentId: binding.agent.id,
2057
- };
2058
- }
2059
- }
2060
- const failedChildren = childReports.filter((child) => child.result.state === "failed");
2061
- const uniqueToolNames = [...new Set(aggregateToolResults.map((toolResult) => toolResult.toolName))];
2062
- const status = failedChildren.length > 0 ? "failed" : "completed";
2063
- const report = childReports
2064
- .map((child) => `## ${child.subagentType}\n${child.output.trim() || "No visible output returned."}`)
2065
- .join("\n\n");
2066
- const payload = {
2067
- status,
2068
- routing: executableDelegations.map((planned, index) => `${index + 1}) 路由判断: ${planned.subagentType} 负责 ${planned.description.trim() || "该专业域子任务"}。`),
2069
- plan: executableDelegations.map((planned, index) => `${index + 1}) 委托 ${planned.subagentType}: ${planned.description.trim() || "执行其专业域任务"}。`),
2070
- execution: childReports.map((child, index) => `${index + 1}) ${child.subagentType} ${child.result.state === "failed" ? "failed" : "completed"}。`),
2071
- todoTrace: childReports.map((child, index) => `${index + 1}) ${child.subagentType}: ${hasDelegatedPlanEvidence(child.result) ? "TODO evidence observed" : "TODO evidence missing"}。`),
2072
- stepResults: childReports.map((child, index) => `${index + 1}) ${child.subagentType}: delegated result collected; aggregate tools = ${uniqueToolNames.length > 0 ? uniqueToolNames.join(", ") : "none"}。`),
2073
- summary: [
2074
- status === "failed"
2075
- ? `多 specialist 编排完成,但 ${failedChildren.length} 个委托返回 failed。`
2076
- : "多 specialist 编排已完成,所有委托均返回 completed。",
2077
- ],
2078
- findings: childReports.map((child) => `${child.subagentType}: ${child.output.trim().slice(0, 500) || "No finding text returned."}`),
2079
- blockers: failedChildren.length > 0
2080
- ? failedChildren.map((child) => `${child.subagentType}: delegated execution failed.`)
2081
- : ["none"],
2082
- nextActions: failedChildren.length > 0
2083
- ? ["查看 failed specialist 的 blocker 并单独重跑该委托。"]
2084
- : ["可基于各 specialist 结果继续做最终修复或发布决策。"],
2085
- report,
2086
- };
2087
- const output = JSON.stringify(payload);
2088
- return {
2089
- toolOutput: output,
2090
- delegatedSubagentType: "multiple",
2091
- delegatedResult: {
2092
- sessionId,
2093
- requestId,
2094
- agentId: binding.agent.id,
2095
- state: status,
2096
- output,
2097
- finalMessageText: output,
2098
- metadata: {
2099
- executedToolResults: aggregateToolResults,
2100
- delegations: childReports.map((child) => ({
2101
- subagentType: child.subagentType,
2102
- state: child.result.state,
2103
- })),
2104
- },
2105
- },
2106
- };
2107
- }
2108
- if (selection?.refusedReason) {
2109
- return {
2110
- toolOutput: selection.refusedReason,
2111
- delegatedSubagentType: null,
2112
- delegatedResult: {
2113
- sessionId,
2114
- requestId,
2115
- agentId: binding.agent.id,
2116
- state: "failed",
2117
- output: selection.refusedReason,
2118
- finalMessageText: selection.refusedReason,
2119
- },
2120
- };
2121
- }
2122
- let subagentType = selection?.subagentType ?? "";
2123
- if (!subagentNames.has(subagentType)) {
2124
- return null;
2125
- }
2126
- const selectedBinding = this.options.bindingResolver(subagentType);
2127
- if (!selectedBinding) {
2128
- return null;
2129
- }
2130
- yield {
2131
- kind: "commentary",
2132
- content: `Delegating to ${subagentType}.`,
2133
- agentId: binding.agent.id,
2134
- };
2135
- yield {
2136
- kind: "commentary",
2137
- content: "Starting delegated execution.",
2138
- agentId: selectedBinding.agent.id,
2139
- };
2140
- const childRequestId = `${requestId}:${subagentType}`;
2141
- const runDelegatedStreamAttempt = async function* (text, requestIdSuffix = "", delegatedOptions = {}) {
2142
- const executedToolResults = [];
2143
- let output = "";
2144
- try {
2145
- for await (const chunk of this.stream(selectedBinding, text, sessionId, [], {
2146
- context: options.context,
2147
- state: delegatedOptions.state ?? options.state,
2148
- files: options.files,
2149
- requestId: `${childRequestId}${requestIdSuffix}`,
2150
- memoryContext: options.memoryContext,
2151
- profiling: options.profiling,
2152
- toolRuntimeContext: delegatedOptions.toolRuntimeContext ?? options.toolRuntimeContext,
2153
- suppressInitialRequiredPlanInstruction: delegatedOptions.suppressInitialRequiredPlanInstruction,
2154
- externalPlanEvidence: delegatedOptions.externalPlanEvidence,
2155
- })) {
2156
- if (typeof chunk === "string") {
2157
- output += chunk;
2158
- continue;
2159
- }
2160
- if (chunk.kind === "content") {
2161
- output += chunk.content ?? "";
2162
- continue;
2163
- }
2164
- if (chunk.kind === "tool-result") {
2165
- appendUniqueToolEvidence(executedToolResults, {
2166
- toolName: chunk.toolName,
2167
- output: chunk.output,
2168
- ...(chunk.isError !== undefined ? { isError: chunk.isError } : {}),
2169
- });
2170
- }
2171
- if (chunk.kind === "upstream-event") {
2172
- const streamedEvidence = readUpstreamToolEvidence(chunk.event);
2173
- if (streamedEvidence) {
2174
- appendUniqueToolEvidence(executedToolResults, streamedEvidence);
2175
- }
2176
- }
2177
- yield { ...chunk, agentId: chunk.agentId ?? selectedBinding.agent.id };
2178
- }
2179
- }
2180
- catch (error) {
2181
- output = error instanceof Error ? error.message : String(error);
2182
- return {
2183
- sessionId,
2184
- requestId: `${childRequestId}${requestIdSuffix}`,
2185
- agentId: selectedBinding.agent.id,
2186
- state: "failed",
2187
- output,
2188
- finalMessageText: output,
2189
- metadata: {
2190
- executedToolResults,
2191
- ...(delegatedOptions.externalPlanEvidence === true ? { externalPlanEvidence: true } : {}),
2192
- },
2193
- };
2194
- }
2195
- const finalOutput = delegatedOptions.externalPlanEvidence === true && hasNonPlanToolEvidenceItems(executedToolResults)
2196
- ? buildDelegatedExternalPlanEvidenceSummary(executedToolResults)
2197
- : sanitizeVisibleText(output);
2198
- return {
2199
- sessionId,
2200
- requestId: `${childRequestId}${requestIdSuffix}`,
2201
- agentId: selectedBinding.agent.id,
2202
- state: "completed",
2203
- output: finalOutput,
2204
- finalMessageText: finalOutput,
2205
- metadata: {
2206
- executedToolResults,
2207
- ...(delegatedOptions.externalPlanEvidence === true ? { externalPlanEvidence: true } : {}),
2208
- },
2209
- };
2210
- }.bind(this);
2211
- const delegatedText = buildDelegatedOwnedTaskInstruction({
2212
- subagentType,
2213
- taskText: requestText,
2214
- originalRequest: requestText,
2215
- });
2216
- let delegatedResult = yield* runDelegatedStreamAttempt(delegatedText);
2217
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2218
- const previousDelegatedResult = delegatedResult;
2219
- delegatedResult = mergeDelegatedResultToolEvidence(yield* runDelegatedStreamAttempt([delegatedText, DELEGATED_PLAN_EVIDENCE_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-retry"), previousDelegatedResult);
2220
- }
2221
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2222
- const previousDelegatedResult = delegatedResult;
2223
- delegatedResult = mergeDelegatedResultToolEvidence(yield* runDelegatedStreamAttempt([delegatedText, DELEGATED_PLAN_EVIDENCE_FINAL_RETRY_INSTRUCTION].filter(Boolean).join("\n\n"), ":plan-evidence-final-retry", buildDelegatedPlanEvidenceRecoveryOptions(selectedBinding, options, delegatedText)), previousDelegatedResult);
2224
- }
2225
- if (needsDelegatedPlanRecovery(selectedBinding, delegatedResult)) {
2226
- const output = buildDelegatedPlanEvidenceBlocker(selectedBinding.agent.id);
2227
- delegatedResult = {
2228
- ...delegatedResult,
2229
- state: "failed",
2230
- output,
2231
- finalMessageText: output,
2232
- };
2233
- }
2234
- const delegatedToolResults = Array.isArray(delegatedResult.metadata?.executedToolResults)
2235
- ? delegatedResult.metadata.executedToolResults
2236
- : [];
2237
- for (const toolResult of delegatedToolResults) {
2238
- const toolName = typeof toolResult.toolName === "string" ? toolResult.toolName : "";
2239
- if (!toolName || isPlanToolName(toolName)) {
2240
- continue;
2241
- }
2242
- yield {
2243
- kind: "commentary",
2244
- content: `Running tool ${toolName}.`,
2245
- agentId: selectedBinding.agent.id,
2246
- };
2247
- yield {
2248
- kind: "commentary",
2249
- content: `Tool ${toolName} ${toolResult.isError === true ? "failed" : "completed"}.`,
2250
- agentId: selectedBinding.agent.id,
2251
- };
2252
- }
2253
- return {
2254
- toolOutput: resolveDelegatedResultOutput(delegatedResult),
2255
- delegatedSubagentType: subagentType,
2256
- delegatedResult,
2257
- };
2258
- }
2259
- async *stream(binding, input, sessionId, history = [], options = {}) {
2260
- if (isDelegationOnlyDeepAgentBinding(binding)) {
2261
- yield {
2262
- kind: "commentary",
2263
- content: "Selecting a specialist for delegated execution.",
2264
- };
2265
- }
2266
- const compactDelegation = yield* this.streamDelegateWithCompactRouter(binding, input, sessionId, options.requestId ?? sessionId, options);
2267
- if (compactDelegation) {
2268
- const compactReport = this.buildCompactDelegationReport(compactDelegation);
2269
- yield {
2270
- kind: "tool-result",
2271
- toolName: "task",
2272
- output: compactDelegation.toolOutput,
2273
- };
2274
- yield {
2275
- kind: "content",
2276
- content: compactDelegation.delegatedSubagentType === null
2277
- ? String(compactDelegation.toolOutput ?? "")
2278
- : this.formatCompactDelegationReportForDisplay(compactReport),
2279
- };
2280
- return;
2281
- }
2282
- const invokeTimeoutMs = resolveBindingTimeout(binding);
2283
- const streamIdleTimeoutMs = resolveStreamIdleTimeout(binding);
2284
- const streamDeadlineAt = invokeTimeoutMs ? Date.now() + invokeTimeoutMs : undefined;
2285
- const { primaryTools, toolNameMapping, forceInvokeFallback, canUseDirectModelStream, langChainStreamModel, } = await resolveRuntimeStreamExecutionContext({
2286
- binding,
2287
- getToolNameMapping: (currentBinding) => this.getToolNameMapping(currentBinding),
2288
- resolveModel: (model) => this.resolveModel(model),
2289
- resolveTools: (tools, currentBinding) => this.resolveTools(tools, currentBinding),
2290
- });
2291
- const streamToolRuntimeContext = this.buildFunctionToolRuntimeContext(binding, {
2292
- ...options,
2293
- sessionId,
2294
- requestId: options.requestId,
2295
- });
2296
- yield* streamRuntimeExecution({
2297
- binding,
2298
- input,
2299
- sessionId,
2300
- history,
2301
- runtimeOptions: {
2302
- ...options,
2303
- requestId: options.requestId,
2304
- profiling: options.profiling,
2305
- ...(streamToolRuntimeContext ? { toolRuntimeContext: streamToolRuntimeContext } : {}),
2306
- },
2307
- primaryTools,
2308
- toolNameMapping,
2309
- forceInvokeFallback,
2310
- canUseDirectModelStream,
2311
- langChainStreamModel,
2312
- createRunnable: () => this.create(binding, { sessionId }),
2313
- resolveInvocationConfig: (activeBinding, configOptions) => resolveLangChainInvocationConfig(activeBinding, {
2314
- sessionId: configOptions.sessionId,
2315
- requestId: configOptions.requestId,
2316
- ...(configOptions.context ? { context: configOptions.context } : {}),
2317
- ...(configOptions.toolRuntimeContext ? { toolRuntimeContext: configOptions.toolRuntimeContext } : {}),
2318
- }),
2319
- withTimeout: (producer, timeoutMs, operation, stage) => this.withTimeout(producer, timeoutMs, operation, stage),
2320
- iterateWithTimeout: (iterable, timeoutMs, operation, deadlineAt, deadlineTimeoutMs) => this.iterateWithTimeout(iterable, timeoutMs, operation, deadlineAt, deadlineTimeoutMs),
2321
- invokeTimeoutMs,
2322
- streamIdleTimeoutMs,
2323
- streamDeadlineAt,
2324
- invoke: (activeBinding, activeInput, activeSessionId, activeRequestId, resumePayload, activeHistory, invokeOptions) => this.invoke(activeBinding, activeInput, activeSessionId, activeRequestId, resumePayload, activeHistory, invokeOptions),
2325
- applyToolRecoveryInstruction: (activeBinding, instruction) => applyToolRecoveryInstructionHelper(activeBinding, instruction),
2326
- isRetryableProviderError: (activeBinding, error) => isRetryableProviderError(activeBinding, error),
2327
- getSystemPrompt: (activeBinding) => getBindingSystemPrompt(activeBinding),
2328
- isLangChainBinding,
2329
- isDeepAgentBinding,
2330
- countConfiguredTools: getBindingToolCount,
2331
- countConfiguredToolsForAgentId: (agentId) => {
2332
- const resolved = this.options.bindingResolver?.(agentId);
2333
- return resolved ? getBindingToolCount(resolved) : 0;
2334
- },
2335
- });
2336
- }
2337
- }
2338
- export { AgentRuntimeAdapter as RuntimeAdapter, AGENT_INTERRUPT_SENTINEL_PREFIX, AGENT_INTERRUPT_SENTINEL_PREFIX as INTERRUPT_SENTINEL_PREFIX, buildDeepAgentCreateParams, buildLangChainCreateParams, DEFAULT_DEEPAGENT_RECURSION_LIMIT, materializeModelExposedBuiltinMiddlewareTools, resolveLangChainInvocationConfig, resolveRunnableCheckpointer, resolveRunnableInterruptOn, RuntimeOperationTimeoutError, };
1
+ import ee from"node:path";import{createHash as Ye}from"node:crypto";import{createAsyncSubAgentMiddleware as Ve,createDeepAgent as Ge,createFilesystemMiddleware as ke,createMemoryMiddleware as Xe,createPatchToolCallsMiddleware as xe,createSkillsMiddleware as Se,createSummarizationMiddleware as Ae,createSubAgentMiddleware as Qe,FilesystemBackend as Ze,StateBackend as et}from"deepagents";import{createAgent as Me,humanInTheLoopMiddleware as tt,todoListMiddleware as Ee}from"langchain";import{sanitizeVisibleText as te,tryParseJson as nt,wrapResolvedModel as ot}from"./parsing/output-parsing.js";import{salvageJsonToolCalls as st}from"./parsing/output-tool-args.js";import{extractMessageText as Ce}from"../utils/message-content.js";import{AGENT_INTERRUPT_SENTINEL_PREFIX as De,buildDeepAgentCreateParams as rt,buildDeepAgentSystemPromptWithCapabilityCatalog as $e,buildLangChainCreateParams as Ne,DEFAULT_DEEPAGENT_RECURSION_LIMIT as at,materializeModelExposedBuiltinMiddlewareTools as de,resolveLangChainInvocationConfig as X,resolveRunnableCheckpointer as ce,resolveRunnableInterruptOn as ge,shouldAttachDeepAgentBackend as it,shouldAttachDeepAgentCheckpointer as lt,shouldAttachDeepAgentStore as ut}from"./agent-runtime-assembly.js";import{resolveDeepAgentSkillSourcePaths as dt,resolveDeepAgentSkillSourceRootPaths as Pe}from"./adapter/compat/deepagent-compat.js";import{buildToolNameMapping as ct}from"./adapter/tool/tool-name-mapping.js";import{PROMPTED_JSON_TOOL_POLICY_KEY as gt}from"./adapter/model/prompted-json-tool-policy.js";import{executeRequestInvocation as pt}from"./adapter/flow/invocation-flow.js";import{streamRuntimeExecution as mt}from"./adapter/flow/stream-runtime.js";import{resolveDeterministicFinalOutput as ft}from"./adapter/invocation-result.js";import{applyToolRecoveryInstruction as yt,applyStrictToolJsonInstruction as ht,callRuntimeWithToolParseRecovery as vt,createModelFallbackRunnable as Tt,invokeWithProviderRetry as bt,iterateWithTimeout as Rt,materializeModelStream as wt,RuntimeOperationTimeoutError as kt,withRuntimeTimeout as xt}from"./adapter/runtime-shell.js";import{extractSubagentRequestText as St,invokeBuiltinTaskTool as At,materializeAutomaticSummarizationMiddleware as Mt,resolveBuiltinMiddlewareBackend as Et,resolveBuiltinMiddlewareTools as Ct,resolveLangChainRuntimeExtensionMiddleware as Dt,resolveMiddleware as $t,resolveSubagents as Nt,wrapRequestResultAsSubagentResponse as Pt}from"./adapter/middleware-assembly.js";import{isEmptyFinalAiMessageError as Ot,resolveBindingTimeout as ne,resolveStreamIdleTimeout as It}from"./adapter/resilience.js";import{createResolvedModel as Bt}from"./adapter/model/model-providers.js";import{appendProviderToolCallAliasTools as pe,resolveAdapterTools as _t}from"./adapter/tool-resolution.js";import{resolveRuntimeStreamExecutionContext as qt}from"./adapter/flow/execution-context.js";import{isRetryableProviderError as jt}from"./adapter/resilience.js";import{UPSTREAM_REQUEST_CONFIG_KEY as Oe,UPSTREAM_SESSION_CONFIG_KEY as Ie}from"./adapter/upstream-configurable-keys.js";import{materializeDeepAgentSkillSourcePaths as xn,resolveDeepAgentSkillSourcePaths as Sn,resolveDeepAgentSkillSourceRootPaths as An,relativizeDeepAgentSkillSourcePaths as Mn}from"./adapter/compat/deepagent-compat.js";import{buildAuthOmittingFetch as Cn,normalizeOpenAICompatibleInit as Dn}from"./adapter/compat/openai-compatible.js";import{buildToolNameMapping as Nn,createModelFacingToolNameCandidates as Pn,createModelFacingToolNameLookupCandidates as On,resolveModelFacingToolName as In,sanitizeToolNameForModel as Bn}from"./adapter/tool/tool-name-mapping.js";import{computeRemainingTimeoutMs as qn,isRetryableProviderError as jn,resolveBindingTimeout as Fn,resolveProviderRetryPolicy as Ln,resolveStreamIdleTimeout as zn,resolveTimeoutMs as Jn}from"./adapter/resilience.js";import{getBindingAdapterKind as Ft,getBindingBuiltinToolsConfig as oe,getBindingDeepAgentSubagents as Be,getBindingExecutionParams as me,getBindingExecutionKind as W,getBindingFilesystemConfig as _e,getBindingMemorySources as fe,getBindingPrimaryModel as Q,getBindingSkills as qe,getBindingSubagents as se,getBindingToolCount as je,getBindingPrimaryTools as K,getBindingSystemPrompt as H,isDeepAgentBinding as Fe,isLangChainBinding as Le}from"./support/compiled-binding.js";function ye(r){return JSON.stringify({status:"blocked",routing:[`delegated agent ${r}`],plan:["delegate to specialist","require visible TODO planning evidence","return blocker when planning evidence is absent"],execution:[`task delegated to ${r}`,`delegated agent ${r} ended before producing required TODO plan evidence`],todoTrace:[`${r}: TODO evidence missing; delegated agent ended before producing required planning evidence.`],stepResults:["delegated planning evidence was not observed"],summary:[`Delegated agent ${r} ended before producing the required TODO plan evidence.`],findings:["The delegated run did not expose a valid planning trace, so the framework cannot treat the task as complete."],blockers:["missing delegated TODO planning evidence"],nextActions:["Retry with the same request or inspect the delegated agent configuration and model/tool-call behavior."],report:`routing delegated to ${r}; todoTrace ${r}: TODO evidence missing; stepResults blocked; summary missing planning evidence; findings require retry; blockers missing TODO planning evidence; nextActions inspect delegated model/tool behavior; report task delegated to ${r}.`})}function Lt(r){return typeof r=="string"?r.trim().toLowerCase().replace(/[\s-]+/gu,"_"):""}function L(r){const e=Lt(r);return e==="write_todos"||e==="read_todos"||e==="tool_call_write_todos"||e==="tool_call_read_todos"||e==="call_write_todos"||e==="call_read_todos"}function bn(r){if(typeof r!="object"||r===null)return"";const e=r;return typeof e.name=="string"?e.name.trim():""}function zt(r){return W(r)==="deepagent"}function Jt(r){const e=oe(r);return e?.todos!==!1&&e?.filesystem!==!1}function re(r){if(typeof r=="string")return r.trim();if(typeof r!="object"||r===null)return"";const e=r.content;return typeof e=="string"?e.trim():Array.isArray(e)?e.map(t=>typeof t=="string"?t:typeof t=="object"&&t!==null&&typeof t.text=="string"?t.text:"").join("").trim():""}function Ut(r){let e=0,t=-1,n=!1,o=!1;for(let s=0;s<r.length;s+=1){const g=r[s];if(n){o?o=!1:g==="\\"?o=!0:g==='"'&&(n=!1);continue}if(g==='"'){n=!0;continue}if(g==="{"){e===0&&(t=s),e+=1;continue}if(g==="}"&&e>0&&(e-=1,e===0&&t>=0))return nt(r.slice(t,s+1))}return null}function ae(r,e){const t=r.trim(),n=h=>Array.from(e).find(R=>R.toLowerCase()===h.trim().toLowerCase()),o=n(t);if(o)return{subagentType:o};const s=Ut(t),g=st(t).at(0),a=typeof s=="object"&&s!==null&&!Array.isArray(s)?s:g?{name:g.name,arguments:g.args}:null;if(!a)return null;const c=typeof a.arguments=="object"&&a.arguments!==null&&!Array.isArray(a.arguments)?a.arguments:typeof a.args=="object"&&a.args!==null&&!Array.isArray(a.args)?a.args:a,b=typeof a.subagent_type=="string"?a.subagent_type.trim():typeof c.subagent_type=="string"?c.subagent_type.trim():"",$=n(b);if($)return{subagentType:$};const i=Array.isArray(a.delegations)?a.delegations:Array.isArray(c.delegations)?c.delegations:void 0;if(i){const h=i.map(u=>{if(typeof u!="object"||u===null||Array.isArray(u))return null;const l=u,w=typeof l.subagent_type=="string"?l.subagent_type.trim():typeof l.subagent=="string"?l.subagent.trim():"",m=Array.from(e).find(E=>E.toLowerCase()===w.toLowerCase());if(!m)return null;const O=typeof l.description=="string"&&l.description.trim()?l.description.trim():typeof l.task=="string"&&l.task.trim()?l.task.trim():typeof l.instruction=="string"&&l.instruction.trim()?l.instruction.trim():"";return{subagentType:m,description:O}}).filter(u=>u!==null),R=[];for(const u of h)R.some(l=>l.subagentType===u.subagentType)||R.push(u);if(R.length>0)return{delegations:R}}const A=typeof a.routing=="object"&&a.routing!==null&&!Array.isArray(a.routing)?a.routing:typeof c.routing=="object"&&c.routing!==null&&!Array.isArray(c.routing)?c.routing:void 0;if(A){const h=Array.isArray(A.subagents)?A.subagents.map(u=>{if(typeof u!="string")return null;const l=n(u);return l?{subagentType:l,description:""}:null}).filter(u=>u!==null):[],R=Object.entries(A).map(([u,l])=>{const w=n(u);if(!w)return null;const m=typeof l=="string"&&l.trim()?l.trim():"";return{subagentType:w,description:m}}).filter(u=>u!==null);for(const u of h)R.some(l=>l.subagentType===u.subagentType)||R.push(u);if(R.length>0)return{delegations:R}}return(typeof a.status=="string"?a.status.trim().toLowerCase():"")==="refused"?{refusedReason:typeof a.reason=="string"&&a.reason.trim()?a.reason.trim():"No configured subagent can handle the request."}:null}function ze(r){if(!r)return"";const e=r.split(/\r?\n/u).map(n=>n.trim()).filter(n=>n.length>0),t=e.findIndex(n=>/^output:?$/iu.test(n));return(t>=0?e.slice(0,t):e).slice(0,80).join(`
2
+ `)}function Je(r){const e=r.split(/\r?\n/u).map(o=>o.trim()).filter(Boolean);return e.filter(o=>/^\d+[\.)、]\s+/u.test(o)).length>=2?!0:e.filter(o=>/^[-*]\s+/u.test(o)).length>=2}function he(r){return[`Delegated owner: ${r.subagentType}.`,"Execute only this owner's bounded portion of the larger request.","Do not take over other specialist-owned work; return blockers for missing access instead of inventing success.","Owned subtask:",r.taskText.trim()||r.originalRequest,"If the owner policy or tool contract requires evidence, call write_todos first and then execute the appropriate non-planning evidence tool before any final answer.","Close every TODO as completed or failed before final output."].filter(Boolean).join(`
3
+ `)}function ve(r){return Fe(r)&&se(r).length>0&&K(r).length===0&&qe(r).length===0}function ie(r){if(r?.metadata?.externalPlanEvidence===!0)return!0;const e=r?.metadata?.executedToolResults;return Array.isArray(e)&&e.some(t=>L(t.toolName))}function Y(r){if(Array.isArray(r))return r.some(n=>Y(n));if(typeof r!="object"||r===null)return!1;const e=r,t=typeof e.status=="string"?e.status.trim().toLowerCase():"";return t==="pending"||t==="in_progress"?!0:Y(e.todos)||Y(e.update)||Y(e.stateSnapshot)||Y(e.metadata)}function V(r){if(Array.isArray(r))return r.some(n=>V(n));if(typeof r!="object"||r===null)return!1;const e=r;return(typeof e.status=="string"?e.status.trim().toLowerCase():"")==="failed"?!0:V(e.todos)||V(e.update)||V(e.stateSnapshot)||V(e.metadata)}function Wt(r){const e=r?.metadata?.executedToolResults;return Array.isArray(e)&&e.some(t=>L(t.toolName)&&Y(t.output))}function Kt(r){const e=r?.metadata?.executedToolResults;return Array.isArray(e)&&e.some(t=>L(t.toolName)&&V(t.output))}function Ht(r){const e=r?.metadata?.executedToolResults;return Array.isArray(e)&&e.some(t=>typeof t.toolName=="string"&&!L(t.toolName)&&t.isError!==!0)}function Ue(r){return r.some(e=>typeof e.toolName=="string"&&!L(e.toolName)&&e.isError!==!0)}function We(r){const e=r.filter(t=>typeof t.toolName=="string"&&!L(t.toolName)&&t.isError!==!0).map(t=>{const n=typeof t.output=="string"?t.output:JSON.stringify(t.output??"");return`## ${String(t.toolName)}
4
+ ${n}`});return["Status: completed","Summary:","- Completed delegated recovery after collecting non-planning tool evidence.","","Evidence:",e.length>0?e.join(`
5
+
6
+ `):"(no non-planning tool evidence captured)"].join(`
7
+ `)}function z(r,e){return r?.harnessRuntime.executionContract?.requiresPlan===!0&&(!ie(e)||Wt(e)||Kt(e)&&!Ht(e))}function Ke(r){if(typeof r!="object"||r===null)return null;const e=r,t=typeof e.event=="string"?e.event:"",n=typeof e.run_type=="string"?e.run_type:"",o=typeof e.name=="string"?e.name:"";return o?(t==="on_tool_start"||t==="on_chain_start"&&n==="tool")&&L(o)?{toolName:o,output:e.data?.input}:t==="on_tool_end"||t==="on_chain_end"&&n==="tool"?{toolName:o,output:e.data?.output}:t==="on_tool_error"?{toolName:o,output:e.data?.error??e.data?.output,isError:!0}:null:null}function G(r,e){r.some(n=>n.toolName===e.toolName&&n.isError===e.isError&&JSON.stringify(n.output)===JSON.stringify(e.output))||r.push(e)}function Z(r,e){const t=[];for(const n of[e,r]){const o=Array.isArray(n.metadata?.executedToolResults)?n.metadata.executedToolResults:[];for(const s of o)typeof s=="object"&&s!==null&&typeof s.toolName=="string"&&G(t,s)}return{...r,metadata:{...r.metadata??{},executedToolResults:t}}}const le=["The delegated task requires visible TODO planning evidence.","Before any other tool call or final answer, call write_todos with concrete task steps and statuses.","Then continue the task to completion, update TODO statuses after evidence steps, and close every TODO as completed or failed before the final answer."].join(`
8
+ `),Te=["The delegated task has already attempted TODO planning but still has no successful non-planning tool evidence.","Do not call write_todos or read_todos next.","The next runtime event must be one available non-planning evidence tool call.","After that tool returns, update or close the TODO board and provide the final answer required by the agent response format."].join(`
9
+ `);function be(r,e,t=""){return{...e,suppressInitialRequiredPlanInstruction:!0,externalPlanEvidence:!0,state:{...typeof e.state=="object"&&e.state!==null?e.state:{},[gt]:"nonPlanningEvidence"}}}function Yt(r){const e=r.trim();return/^(?:stdout|stderr)\s*:/iu.test(e)||/(?:^|\n)\s*(?:stdout|stderr)\s*:/iu.test(e)||/(?:^|\n)\s*exitCode\s*:\s*-?\d+\s*$/iu.test(e)}function He(r){const e=Array.isArray(r.metadata?.executedToolResults)?r.metadata.executedToolResults:[];return ft({visibleOutput:typeof r.output=="string"?r.output:"",executedToolResults:e})||r.output}function Rn(r){const e=Array.isArray(r?.metadata?.executedToolResults)?r.metadata.executedToolResults:[];return e.some(n=>n.isError!==!0&&!L(n.toolName))?e.filter(n=>n.isError!==!0&&!L(n.toolName)):e}class Vt{options;modelCache=new Map;runnableCache=new Map;toolNameMappingCache=new WeakMap;constructor(e={}){this.options=e}getModelCacheKey(e){return JSON.stringify({id:e.id,runtimeValue:e.runtimeValue,init:e.init,clientRef:e.clientRef})}async invokeWithProviderRetry(e,t){return bt(e,t,{onRetry:async()=>{this.invalidateBindingRuntimeCaches(e)}})}async withTimeout(e,t,n,o=n.includes("stream")?"stream":"invoke"){return xt(e,t,n,o)}async*iterateWithTimeout(e,t,n,o,s){yield*Rt(e,t,n,o,s)}async materializeModelStream(e,t,n){return wt(e,t,n)}createModelFallbackRunnable(e){return Tt(e)}applyStrictToolJsonInstruction(e){return ht(e)}async resolveModel(e){const t=this.getModelCacheKey(e),n=this.modelCache.get(t);if(n)return n;const o=(async()=>ot(await Bt(e,this.options.modelResolver)))();this.modelCache.set(t,o);try{return await o}catch(s){throw this.modelCache.delete(t),s}}invalidateBindingRuntimeCaches(e){const t=`${e.agent.sourcePath}::`;for(const n of Array.from(this.runnableCache.keys()))n.startsWith(t)&&this.runnableCache.delete(n);this.modelCache.clear()}resolveTools(e,t){return _t({tools:e,binding:t,resolveToolValues:this.options.toolResolver})}getToolNameMapping(e){const t=this.toolNameMappingCache.get(e);if(t)return t;const n=ct(K(e));return this.toolNameMappingCache.set(e,n),n}resolveFilesystemBackend(e,t={}){const n=_e(e),o=typeof n?.sessionStorage=="object"&&n.sessionStorage?n.sessionStorage:void 0,s=typeof n?.rootDir=="string"&&n.rootDir.trim().length>0?n.rootDir:void 0,g=e.harnessRuntime.workspaceRoot,a=s?ee.isAbsolute(s)?s:ee.resolve(g??process.cwd(),s):g??process.cwd(),c=this.resolveFilesystemRootDir(a,e,o,t.sessionId??t.legacySessionId);return new Ze({rootDir:c,virtualMode:n?.virtualMode===!0,maxFileSizeMb:typeof n?.maxFileSizeMb=="number"&&Number.isFinite(n.maxFileSizeMb)?n.maxFileSizeMb:10})}resolveFilesystemRootDir(e,t,n,o){if(!(n?.enabled===!0)||!o)return e;const g=t.harnessRuntime.workspaceRoot??process.cwd(),a=t.harnessRuntime.runtimeRoot,b=(typeof n.rootDir=="string"&&n.rootDir.trim().length>0?n.rootDir.trim():"{runtimeRoot}/sessions/{sessionId}/filesystem").replaceAll("{legacySessionId}",o).replaceAll("{sessionId}",o).replaceAll("{agentId}",t.agent.id).replaceAll("{runtimeRoot}",a).replaceAll("{workspaceRoot}",g).replaceAll("{baseRootDir}",e);return ee.isAbsolute(b)?b:ee.resolve(g,b)}resolveBuiltinMiddlewareBackend(e,t={}){const n=Et({binding:e,runtimeAdapterOptions:this.options,resolveFilesystemBackend:s=>this.resolveFilesystemBackend(s),options:t});if(!this.options.scheduleManager||typeof n!="object"||!n)return n;const o=Object.create(n);return o.manageSchedule=s=>this.options.scheduleManager.manageSchedule(s),o}buildFunctionToolRuntimeContext(e,t={}){if(!this.options.functionToolContextResolver)return;const n=typeof t.requestId=="string"&&t.requestId.includes(":")?t.requestId.split(":")[0]:t.requestId,o=this.resolveBuiltinMiddlewareBackend(e,t);return{...this.options.functionToolContextResolver({binding:e,sessionId:t.sessionId,requestId:n}),backend:o,invocation:{...t.context?{context:t.context}:{},...t.sessionId?{sessionId:t.sessionId}:{},...n?{requestId:n}:{}}}}createDeclaredMiddlewareResolverOptions(e,t={}){return{resolveModel:n=>this.resolveModel(n),resolveBackend:n=>{const o=n??e;return o?this.options.backendResolver?.(o):void 0},resolveFilesystemBackend:n=>{const o=n??e;return o?this.resolveFilesystemBackend(o,{sessionId:t.sessionId??t.legacySessionId}):void 0},resolveCustom:this.options.declaredMiddlewareResolver,binding:e}}createAssemblyResolvers(e,t={}){return{resolveModel:n=>this.resolveModel(n),resolveTools:(n,o)=>this.resolveTools(n,o),resolveFilesystemBackend:n=>this.resolveFilesystemBackend(n,{sessionId:t.sessionId??t.legacySessionId}),createDeclaredMiddlewareResolverOptions:n=>this.createDeclaredMiddlewareResolverOptions(n,t),resolveBuiltinMiddlewareBackend:(n,o={})=>this.resolveBuiltinMiddlewareBackend(n,o),resolveSubagents:(n,o)=>this.resolveSubagents(n,o),invokeBuiltinTaskTool:(n,o,s={})=>this.invokeBuiltinTaskTool(n,o,s),binding:e,options:t}}async invokeBuiltinTaskTool(e,t,n={}){const o=this.createAssemblyResolvers(e,n);return At({binding:e,toolInput:t,options:n,resolveBuiltinMiddlewareBackend:o.resolveBuiltinMiddlewareBackend,resolveSubagents:o.resolveSubagents,resolveModel:o.resolveModel,resolveTools:o.resolveTools})}async resolveBuiltinMiddlewareTools(e,t={}){const n=this.createAssemblyResolvers(e,t);return Ct({binding:e,options:t,resolveBuiltinMiddlewareBackend:n.resolveBuiltinMiddlewareBackend,invokeBuiltinTaskTool:n.invokeBuiltinTaskTool})}materializeProviderAliasBuiltinTools(e,t){if(t===!1)return[];const n=Array.isArray(t)?new Set(t):void 0,o=["write_todos","read_todos","task"].filter(s=>!n||n.has(s)).map(s=>e.get(s)).filter(s=>s!==void 0);return pe(o).slice(o.length)}shouldExposeBuiltinToolsToModel(e,t){const n=oe(e)?.modelExposed;return e.harnessRuntime.executionContract?.requiresPlan===!0?!0:n===!1?!1:Array.isArray(n)?n.length>0:t.length>0||se(e).length>0||Be(e).length>0}resolveEffectiveModelExposedBuiltins(e){const t=oe(e)?.modelExposed,n=new Set;return e.harnessRuntime.executionContract?.requiresPlan===!0&&(n.add("write_todos"),n.add("read_todos")),t===!1?n.size>0?[...n]:!1:Array.isArray(t)?[...new Set([...t,...n])]:t}async materializeAutomaticSummarizationMiddleware(e){const t=this.createAssemblyResolvers(e);return Mt({binding:e,createDeclaredMiddlewareResolverOptions:t.createDeclaredMiddlewareResolverOptions})}async resolveLangChainRuntimeExtensionMiddleware(e,t={}){const n=this.createAssemblyResolvers(e,t);return Dt({binding:e,materializeAutomaticSummarizationMiddleware:o=>this.materializeAutomaticSummarizationMiddleware(o),resolveFilesystemBackend:n.resolveFilesystemBackend,resolveModel:n.resolveModel,resolveTools:n.resolveTools,resolveSubagents:n.resolveSubagents})}async resolveMiddleware(e,t,n={}){const o=this.createAssemblyResolvers(e,n);return $t({binding:e,interruptOn:t,runtimeAdapterOptions:this.options,createDeclaredMiddlewareResolverOptions:o.createDeclaredMiddlewareResolverOptions,resolveLangChainRuntimeExtensionMiddleware:s=>this.resolveLangChainRuntimeExtensionMiddleware(s,n)})}async resolveSubagents(e,t){const n=this.createAssemblyResolvers(t);return Nt({subagents:e,binding:t,resolveModel:n.resolveModel,resolveTools:n.resolveTools,createDeclaredMiddlewareResolverOptions:n.createDeclaredMiddlewareResolverOptions,resolveBackend:o=>{const s=o??t;return s?this.options.backendResolver?.(s):void 0}})}async resolveDeepAgentSubagents(e,t,n={}){const o=e.filter(c=>!("graphId"in c)),s=e.filter(c=>"graphId"in c),g=await this.resolveSubagents(o,t);return[...await Promise.all(g.map(async(c,b)=>{const i=o[b]?.agentId,A=i?this.options.bindingResolver?.(i):void 0;return A?{name:c.name,description:c.description,systemPrompt:c.systemPrompt,runnable:{invoke:async(h,R)=>{const u=St(h),l=typeof R?.configurable=="object"&&R.configurable?R.configurable:{},w=typeof l[Ie]=="string"?l[Ie]:n.sessionId??`${t?.agent.id??"agent"}:${c.name}`,m=typeof l[Oe]=="string"?l[Oe]:w,O=`${w}:delegated:${c.name}`,E=`${m}:delegated:${c.name}:${Date.now().toString(36)}`;try{const f=await this.invoke(A,u,O,E,void 0,[],{...typeof R?.context=="object"&&R.context?{context:R.context}:{}});return Pt({output:f.output,structuredResponse:f.structuredResponse})}catch(f){const p=f instanceof Error&&f.message.trim().length>0?f.message.trim():"delegated execution failed";throw new Error(p)}}}}:c})),...s]}async createLangChainRunnable(e,t={}){const n=W(e),o=Q(e),s=K(e);if(n!=="langchain-v1"||!o)throw new Error(`Agent ${e.agent.id} has no langchain params`);const g=ge(e),a=await this.resolveModel(o),c=this.resolveTools(s,e),b=await this.resolveBuiltinMiddlewareTools(e,{sessionId:t.sessionId??t.legacySessionId,toolRuntimeContext:this.buildFunctionToolRuntimeContext(e,{sessionId:t.sessionId??t.legacySessionId})}),$=this.resolveEffectiveModelExposedBuiltins(e),i=this.shouldExposeBuiltinToolsToModel(e,s),A=i?de({builtinTools:b,explicitToolNames:s.map(m=>m.name),modelExposed:$}):[],k=i?this.materializeProviderAliasBuiltinTools(b,$):[],h=await this.resolveMiddleware(e,g,{sessionId:t.sessionId??t.legacySessionId}),R=ce(this.options,e),u=this.options.storeResolver?.(e),l=a;if(c.length+A.length>0&&typeof l.bindTools!="function")throw new Error(`Agent ${e.agent.id} configures ${c.length+A.length} tool(s), but resolved model ${o.id} does not support tool binding.`);const w=[...pe([...c,...A]),...k];return Me(Ne({binding:e,resolvedModel:l,resolvedTools:w,resolvedMiddleware:h,resolvedCheckpointer:R,resolvedStore:u,passthroughOverride:t.passthroughOverride,systemPromptOverride:t.systemPromptOverride}))}async createRunnable(e,t={}){if(Ft(e)==="langgraph")throw new Error(`Agent ${e.agent.id} uses removed backend langgraph; use langchain-v1 or deepagent`);return Le(e)?this.createLangChainRunnable(e,{sessionId:t.sessionId??t.legacySessionId}):this.createDeepAgentRunnable(e,{sessionId:t.sessionId??t.legacySessionId})}async createDeepAgentRunnable(e,t={}){const n=W(e),o=Q(e),s=K(e);if(n!=="deepagent"||!o)throw new Error(`Agent ${e.agent.id} has no runnable params`);const g=await this.resolveModel(o),a=this.resolveTools(s,e),c=await this.resolveBuiltinMiddlewareTools(e,{sessionId:t.sessionId??t.legacySessionId,toolRuntimeContext:this.buildFunctionToolRuntimeContext(e,{sessionId:t.sessionId??t.legacySessionId})}),b=this.resolveEffectiveModelExposedBuiltins(e),$=this.shouldExposeBuiltinToolsToModel(e,s),i=$?de({builtinTools:c,explicitToolNames:s.map(E=>E.name),modelExposed:b}):[],A=$?this.materializeProviderAliasBuiltinTools(c,b):[],k=[...pe([...a,...i]),...A],h=await this.resolveMiddleware(e),R=await this.resolveDeepAgentSubagents(Be(e),e,{sessionId:t.sessionId??t.legacySessionId}),u=ge(e),l=lt(e,u)?ce(this.options,e):void 0,w=ut(e)?this.options.storeResolver?.(e):void 0,m=dt({workspaceRoot:e.harnessRuntime.workspaceRoot,runtimeRoot:e.harnessRuntime.runtimeRoot,ownerId:e.agent.id,skillPaths:qe(e)})??[],O=it(e)?this.options.backendResolver?.(e)??(m.length>0?this.resolveFilesystemBackend(e,{sessionId:t.sessionId??t.legacySessionId}):void 0):void 0;if(zt(e)){const E={resolvedModel:g,resolvedTools:k,resolvedMiddleware:h,resolvedSubagents:R,resolvedInterruptOn:u,resolvedCheckpointer:l,resolvedStore:w,resolvedBackend:O,resolvedSkills:m};return Jt(e)?this.createUpstreamDeepAgentRunnable(e,E):this.createConfigurableDeepAgentRunnable(e,E)}throw new Error(`Agent ${e.agent.id} has no supported deepagent assembly path`)}createUpstreamDeepAgentRunnable(e,t){const n=me(e),o=W(e)==="deepagent"&&n&&"responseFormat"in n?n.responseFormat:void 0,s=W(e)==="deepagent"&&n&&"contextSchema"in n?n.contextSchema:void 0;return Ge({model:t.resolvedModel,systemPrompt:$e({systemPrompt:H(e),subagents:t.resolvedSubagents,skills:t.resolvedSkills,tools:K(e)}),tools:t.resolvedTools,middleware:t.resolvedMiddleware,subagents:t.resolvedSubagents,...o!==void 0?{responseFormat:o}:{},...s!==void 0?{contextSchema:s}:{},...t.resolvedCheckpointer!==void 0?{checkpointer:t.resolvedCheckpointer}:{},...t.resolvedStore!==void 0?{store:t.resolvedStore}:{},...t.resolvedBackend!==void 0?{backend:t.resolvedBackend}:{},...t.resolvedInterruptOn!==void 0?{interruptOn:t.resolvedInterruptOn}:{},name:e.agent.id,memory:fe(e),skills:t.resolvedSkills})}createConfigurableDeepAgentRunnable(e,t){const n=oe(e)??{},o=t.resolvedBackend??new et({}),s=t.resolvedSubagents.filter(h=>!("graphId"in h)),g=t.resolvedSubagents.filter(h=>"graphId"in h),a=s,c=[...n.todos===!1?[]:[Ee()],...n.filesystem===!1?[]:[ke({backend:o})],Ae({model:t.resolvedModel,backend:o}),xe()],b=[...c,...t.resolvedSkills.length>0?[Se({backend:o,sources:Pe({workspaceRoot:e.harnessRuntime.workspaceRoot,runtimeRoot:e.harnessRuntime.runtimeRoot,ownerId:e.agent.id,skillPaths:t.resolvedSkills})??t.resolvedSkills})]:[]],$=a.some(h=>h.name==="general-purpose"),i=[...n.todos===!1?[]:[Ee()],...t.resolvedSkills.length>0?[Se({backend:o,sources:Pe({workspaceRoot:e.harnessRuntime.workspaceRoot,runtimeRoot:e.harnessRuntime.runtimeRoot,ownerId:e.agent.id,skillPaths:t.resolvedSkills})??t.resolvedSkills})]:[],...n.filesystem===!1?[]:[ke({backend:o})],Qe({defaultModel:t.resolvedModel,defaultTools:t.resolvedTools,defaultMiddleware:c,generalPurposeMiddleware:b,defaultInterruptOn:t.resolvedInterruptOn,subagents:a,generalPurposeAgent:!$}),Ae({model:t.resolvedModel,backend:o}),xe(),...g.length>0?[Ve({asyncSubAgents:g})]:[],...t.resolvedMiddleware,...fe(e).length>0?[Xe({backend:o,sources:fe(e)})]:[],...t.resolvedInterruptOn?[tt({interruptOn:t.resolvedInterruptOn})]:[]],A=me(e),k=W(e)==="deepagent"&&A&&"responseFormat"in A?A.responseFormat:void 0;return Me({model:t.resolvedModel,systemPrompt:$e({systemPrompt:H(e),subagents:t.resolvedSubagents,skills:t.resolvedSkills,tools:K(e)}),tools:t.resolvedTools,middleware:i,name:e.agent.id,...t.resolvedCheckpointer!==void 0?{checkpointer:t.resolvedCheckpointer}:{},...t.resolvedStore!==void 0?{store:t.resolvedStore}:{},...k!==void 0?{responseFormat:k}:{}})}buildRunnableCacheKey(e,t){const n=_e(e),s=(typeof n?.sessionStorage=="object"&&n.sessionStorage?n.sessionStorage:void 0)?.enabled===!0,g=me(e),a=Q(e),c=Ye("sha256").update(JSON.stringify({executionKind:W(e),systemPrompt:H(e)??"",responseFormat:g&&"responseFormat"in g?g.responseFormat:void 0,model:a?{id:a.id,provider:a.provider,model:a.model}:void 0,tools:K(e).map(b=>b.name).filter(Boolean).sort()})).digest("hex").slice(0,16);return`${e.agent.sourcePath}::${s?t??"__default__":"__binding__"}::${c}`}async create(e,t={}){const n=this.buildRunnableCacheKey(e,t.sessionId??t.legacySessionId),o=this.runnableCache.get(n);if(o)return o;const s=this.createRunnable(e,t);this.runnableCache.set(n,s);try{return await s}catch(g){throw this.runnableCache.delete(n),g}}async invoke(e,t,n,o,s,g=[],a={}){const c=await this.tryDelegateWithCompactRouter(e,t,n,o,{...a,sessionId:n,requestId:o});if(c){const k=this.buildCompactDelegationReport(c),h=c.delegatedSubagentType===null?String(c.toolOutput??""):this.formatCompactDelegationReportForDisplay(k),R=Array.isArray(c.delegatedResult?.metadata?.executedToolResults)?c.delegatedResult.metadata.executedToolResults:[];return{sessionId:n,requestId:o,agentId:e.agent.id,state:c.delegatedResult?.state??"completed",output:te(h),finalMessageText:te(h),metadata:{executedToolResults:[{toolName:"task",output:c.toolOutput},...R]}}}const b=async(k,h)=>this.invokeWithProviderRetry(k,async()=>{const R=await this.create(k,{sessionId:n});return await this.withTimeout(()=>R.invoke(h,X(k,{sessionId:n,requestId:o,context:a.context,toolRuntimeContext:this.buildFunctionToolRuntimeContext(k,{...a,sessionId:n,requestId:o})})),ne(k),"agent invoke","invoke")}),$=async k=>vt({binding:e,request:k,resumePayload:s,callRuntime:b}),i=this.buildFunctionToolRuntimeContext(e,{...a,sessionId:n,requestId:o}),A=()=>pt({binding:e,input:t,sessionId:n,requestId:o,resumePayload:s,history:g,invokeOptions:{...a,...i?{toolRuntimeContext:i}:{}},resolveTools:(k,h)=>this.resolveTools(k,h),getToolNameMapping:k=>this.getToolNameMapping(k),resolveBuiltinMiddlewareTools:(k,h)=>this.resolveBuiltinMiddlewareTools(k,{...h,sessionId:n,requestId:o}),callRuntimeWithToolParseRecovery:$});try{return await A()}catch(k){if(!Ot(k))throw k;return this.invalidateBindingRuntimeCaches(e),A()}}async tryDelegateWithCompactRouter(e,t,n,o,s={}){if(!ve(e)||!this.options.bindingResolver)return null;const g=Q(e);if(!g)return null;const a=Ce(t).trim();if(!a)return null;const c=se(e),b=new Set(c.map(f=>f.name)),$=Je(a);let i=null;const A=c.map(f=>`- ${f.name}: ${f.description}`).join(`
10
+ `),k=H(e),h=ze(k),R=[g.init?.think===!1?"/no_think":"","You are selecting a subagent for a delegation-only agent.","Choose exactly one listed subagent when it can responsibly handle the request.","Use the agent routing policy as authoritative routing configuration when it maps the request meaning to a listed subagent.","When the routing policy says a request class is owned by one listed subagent, keep that request with the configured owner even if the task mentions supporting evidence from other domains.","Do not refuse while any listed subagent can own the request after applying the routing policy.","Refuse only when the request is outside every listed subagent's configured responsibility.",h?"Agent routing policy:":"",h,"Return only JSON with this shape:",'{"subagent_type":"<listed subagent name>"}',"If no listed subagent can handle the request, return only:",'{"status":"refused","reason":"No configured subagent can handle the request."}',"Available subagents:",A,"User request:",a].filter(Boolean).join(`
11
+
12
+ `);let u=null;const l=async(f,p)=>!u||typeof u.invoke!="function"?null:this.invokeWithProviderRetry(e,()=>this.withTimeout(()=>u.invoke(f,X(e,{sessionId:n,requestId:o,context:s.context,toolRuntimeContext:this.buildFunctionToolRuntimeContext(e,{...s,sessionId:n,requestId:o})})),ne(e),p,"invoke"));if(!i){if(u=await this.resolveModel(g),typeof u.invoke!="function")return null;const f=[R,[R,"Your previous router output was invalid.","Return only one JSON object now. Do not include prose, markdown, labels, or tool-call wrappers."].join(`
13
+
14
+ `),[g.init?.think===!1?"/no_think":"","Select one subagent from this exact list:",Array.from(b).join(", "),"Return JSON only:",'{"subagent_type":"<one exact listed name>"}',"User request:",a].filter(Boolean).join(`
15
+
16
+ `),[g.init?.think===!1?"/no_think":"","JSON only. Pick a listed subagent or refuse.","Listed subagents:",Array.from(b).join(", "),"Allowed outputs:",'{"subagent_type":"<listed name>"}','{"status":"refused","reason":"No configured subagent can handle the request."}',"Request:",a].filter(Boolean).join(`
17
+
18
+ `)];let p="";for(let C=0;C<f.length;C+=1){const T=C<=1||!p?f[C]:[f[C],"Previous output:",p].join(`
19
+
20
+ `),M=await l(T,C===0?"delegation router invoke":`delegation router retry invoke ${C}`);if(M===null)break;p=re(M);const x=ae(p,b);if(x){if(x.delegations&&x.delegations.length>1){if(i?.subagentType&&!x.delegations.some(D=>D.subagentType===i?.subagentType))continue;i=x;break}(!i||i.refusedReason||x.subagentType)&&(i=x.refusedReason&&C<f.length-1?i:x)}}}if(i?.delegations&&i.delegations.length>1){const f=[],p=[];for(const d of i.delegations){const y=this.options.bindingResolver(d.subagentType);if(!y){const _=`Configured subagent '${d.subagentType}' could not be resolved.`;p.push({subagentType:d.subagentType,result:{sessionId:n,requestId:`${o}:${d.subagentType}`,agentId:d.subagentType,state:"failed",output:_,finalMessageText:_,metadata:{executedToolResults:[]}},output:_});continue}const S=await this.invoke(y,he({subagentType:d.subagentType,taskText:d.description,originalRequest:a}),n,`${o}:${d.subagentType}`,void 0,[],{context:s.context,state:s.state,files:s.files,memoryContext:s.memoryContext}),q=Array.isArray(S.metadata?.executedToolResults)?S.metadata.executedToolResults:[];f.push(...q),p.push({subagentType:d.subagentType,result:S,output:typeof S.output=="string"?S.output:String(S.output??"")})}const C=p.filter(d=>d.result.state==="failed"),T=[...new Set(f.map(d=>d.toolName))],M=C.length>0?"failed":"completed",x=p.map(d=>`## ${d.subagentType}
21
+ ${d.output.trim()||"No visible output returned."}`).join(`
22
+
23
+ `),D=JSON.stringify({status:M,routing:i.delegations.map((d,y)=>`${y+1}) \u8DEF\u7531\u5224\u65AD: ${d.subagentType} \u8D1F\u8D23 ${d.description.trim()||"\u8BE5\u4E13\u4E1A\u57DF\u5B50\u4EFB\u52A1"}\u3002`),plan:i.delegations.map((d,y)=>`${y+1}) \u59D4\u6258 ${d.subagentType}: ${d.description.trim()||"\u6267\u884C\u5176\u4E13\u4E1A\u57DF\u4EFB\u52A1"}\u3002`),execution:p.map((d,y)=>`${y+1}) ${d.subagentType} ${d.result.state==="failed"?"failed":"completed"}\u3002`),todoTrace:p.map((d,y)=>`${y+1}) ${d.subagentType}: ${ie(d.result)?"TODO evidence observed":"TODO evidence missing"}\u3002`),stepResults:p.map((d,y)=>`${y+1}) ${d.subagentType}: delegated result collected; aggregate tools = ${T.length>0?T.join(", "):"none"}\u3002`),summary:[M==="failed"?`\u591A specialist \u7F16\u6392\u5B8C\u6210\uFF0C\u4F46 ${C.length} \u4E2A\u59D4\u6258\u8FD4\u56DE failed\u3002`:"\u591A specialist \u7F16\u6392\u5DF2\u5B8C\u6210\uFF0C\u6240\u6709\u59D4\u6258\u5747\u8FD4\u56DE completed\u3002"],findings:p.map(d=>`${d.subagentType}: ${d.output.trim().slice(0,500)||"No finding text returned."}`),blockers:C.length>0?C.map(d=>`${d.subagentType}: delegated execution failed.`):["none"],nextActions:C.length>0?["\u67E5\u770B failed specialist \u7684 blocker \u5E76\u5355\u72EC\u91CD\u8DD1\u8BE5\u59D4\u6258\u3002"]:["\u53EF\u57FA\u4E8E\u5404 specialist \u7ED3\u679C\u7EE7\u7EED\u505A\u6700\u7EC8\u4FEE\u590D\u6216\u53D1\u5E03\u51B3\u7B56\u3002"],report:x});return{toolOutput:D,delegatedSubagentType:"multiple",delegatedResult:{sessionId:n,requestId:o,agentId:e.agent.id,state:M,output:D,finalMessageText:D,metadata:{executedToolResults:f,delegations:p.map(d=>({subagentType:d.subagentType,state:d.result.state}))}}}}if(i?.delegations&&i.delegations.length===1&&(i={subagentType:i.delegations[0].subagentType}),i?.refusedReason)return{toolOutput:i.refusedReason,delegatedSubagentType:null,delegatedResult:{sessionId:n,requestId:o,agentId:e.agent.id,state:"failed",output:i.refusedReason,finalMessageText:i.refusedReason}};let w=i?.subagentType??"";if(!b.has(w))return null;const m=this.options.bindingResolver(w);if(!m)return null;const O=async(f,p="",C={})=>{const T=await this.invoke(m,f,n,`${o}:${w}${p}`,void 0,[],{context:s.context,state:s.state,files:s.files,memoryContext:s.memoryContext,...C});return C.externalPlanEvidence===!0?{...T,metadata:{...T.metadata??{},externalPlanEvidence:!0}}:T};let E;try{E=await O(a)}catch(f){if(m.harnessRuntime.executionContract?.requiresPlan===!0)try{E=await O([a,le].filter(Boolean).join(`
24
+
25
+ `),":plan-evidence-retry")}catch(p){const C=p instanceof Error?p.message:String(p);return{toolOutput:C,delegatedSubagentType:w,delegatedResult:{sessionId:n,requestId:o,agentId:m.agent.id,state:"failed",output:C,finalMessageText:C}}}else{const p=f instanceof Error?f.message:String(f);return{toolOutput:p,delegatedSubagentType:w,delegatedResult:{sessionId:n,requestId:o,agentId:m.agent.id,state:"failed",output:p,finalMessageText:p}}}}if(z(m,E))try{E=await O([a,le].filter(Boolean).join(`
26
+
27
+ `),":plan-evidence-retry")}catch(f){const p=f instanceof Error?f.message:String(f);return{toolOutput:p,delegatedSubagentType:w,delegatedResult:{...E,state:"failed",output:p,finalMessageText:p}}}if(z(m,E)){const f=E;try{E=Z(await O([a,Te].filter(Boolean).join(`
28
+
29
+ `),":plan-evidence-final-retry",be(m,s,a)),f)}catch(p){const C=p instanceof Error?p.message:String(p);return{toolOutput:C,delegatedSubagentType:w,delegatedResult:{...E,state:"failed",output:C,finalMessageText:C}}}}if(z(m,E)){const f=ye(m.agent.id);return{toolOutput:f,delegatedSubagentType:w,delegatedResult:{...E,state:"failed",output:f,finalMessageText:f}}}return{toolOutput:He(E),delegatedSubagentType:w,delegatedResult:E}}buildCompactDelegationReport(e){const t=e.delegatedSubagentType??"unknown",n=typeof e.toolOutput=="string"?[e.toolOutput]:[],o=(()=>{if(n.length!==0)try{const l=JSON.parse(n[0]);return l&&typeof l=="object"&&!Array.isArray(l)?l:void 0}catch{return}})(),s=l=>{const w=o?.[l];if(!Array.isArray(w))return;const m=w.filter(O=>typeof O=="string"&&O.trim().length>0);return m.length>0?m:void 0},g=typeof o?.report=="string"&&o.report.trim().length>0?o.report:void 0,a=Array.isArray(e.delegatedResult?.metadata?.executedToolResults)?e.delegatedResult.metadata.executedToolResults.filter(l=>l?.toolName).map(l=>l.toolName):[],c=e.delegatedResult?.state==="failed"?"failed":"completed",b=[...new Set(a)],$=b.length>0?b.join(", "):"none",i=ie(e.delegatedResult),A=[`1) TODO observed: delegated to ${t}.`,i?`2) ${t}: TODO evidence observed; delegated specialist invoked write_todos.`:`2) ${t}: TODO evidence missing; delegated specialist did not expose write_todos in returned metadata.`,c==="failed"?"3) TODO closed: delegated execution failed; blocker reported.":"3) TODO closed: delegated execution completed; synthesis returned."],k=[`1) Delegation step: task invoked ${t}.`,`2) Evidence step: delegated tool evidence = ${$}.`,c==="failed"?"3) Synthesis step: returned blocker report because delegated execution failed.":"3) Synthesis step: compact delegation report assembled from delegated output."],h=[c==="failed"?`\u5B50\u4EE3\u7406 ${t} \u59D4\u6258\u6267\u884C\u5931\u8D25\u3002`:`\u5DF2\u5B8C\u6210\u5B50\u4EE3\u7406 ${t} \u59D4\u6258\u6267\u884C\u3002`],R=g?["\u5B50\u4EE3\u7406\u8FD4\u56DE\u4E86\u7ED3\u6784\u5316\u62A5\u544A\uFF0C\u8BE6\u89C1 report\u3002"]:n.length>0?n.slice(0,3):["none"],u=g??(n.join(`
30
+ `)||"\u59D4\u6258\u5DF2\u5B8C\u6210\uFF0C\u672A\u8FD4\u56DE\u9644\u52A0\u62A5\u544A\u3002");return{status:c,routing:[`1) \u8DEF\u7531\u5224\u65AD: \u5DF2\u9009\u62E9 sub-agent = ${t}\u3002`],plan:["1) \u9009\u62E9\u5177\u5907\u5339\u914D\u80FD\u529B\u7684\u5B50\u4EE3\u7406\u5E76\u521B\u5EFA\u59D4\u6258\u4EFB\u52A1\u3002","2) \u6267\u884C\u5B50\u4EE3\u7406\u7684\u539F\u751F\u5DE5\u4F5C\u6D41\u5E76\u6536\u96C6\u59D4\u6258\u5DE5\u5177\u8F93\u51FA\u3002","3) \u5408\u6210\u6C47\u603B\u62A5\u544A\u5E76\u8FD4\u56DE\u7ED9\u7528\u6237\u3002"],execution:[`1) \u8C03\u7528 task \u5DE5\u5177\uFF0C\u76EE\u6807\u5B50\u4EE3\u7406\uFF1A${t}`,b.length>0?`2) \u5B50\u4EE3\u7406\u8FD4\u56DE\u5DE5\u5177\u8BC1\u636E\uFF1A${$}`:"2) \u5B50\u4EE3\u7406\u8FD4\u56DE\u6587\u672C\u7ED3\u679C\u3002","3) \u4EA7\u51FA\u4E3B\u7F16\u6392\u6C47\u603B\u5E76\u8FD4\u56DE\u7ED3\u6784\u5316\u7ED3\u679C\u3002"],todoTrace:s("todoTrace")??A,stepResults:s("stepResults")??k,summary:s("summary")??h,findings:s("findings")??R,blockers:c==="failed"?["\u5B50\u4EE3\u7406\u6267\u884C\u672A\u80FD\u5B8C\u6210\u3002"]:["none"],nextActions:["\u5982\u9700\u66F4\u6DF1\u5165\uFF0C\u53EF\u7EE7\u7EED\u8FFD\u95EE\u8BE5\u6B21\u59D4\u6258\u7684\u7EC6\u8282\u3002"],report:u}}formatCompactDelegationReportForDisplay(e){const t=typeof e.report=="string"?e.report.trim():"";return t&&Yt(t)?JSON.stringify(e):t||(Array.isArray(e.summary)?e.summary.find(o=>typeof o=="string"&&o.trim().length>0):void 0)?.trim()||"\u59D4\u6258\u5DF2\u5B8C\u6210\uFF0C\u672A\u8FD4\u56DE\u9644\u52A0\u62A5\u544A\u3002"}async*streamDelegateWithCompactRouter(e,t,n,o,s={}){if(!ve(e)||!this.options.bindingResolver)return null;const g=Q(e);if(!g)return null;const a=Ce(t).trim();if(!a)return null;const c=se(e),b=new Set(c.map(T=>T.name)),$=Je(a);let i=null;const A=c.map(T=>`- ${T.name}: ${T.description}`).join(`
31
+ `),k=H(e),h=ze(k),R=[g.init?.think===!1?"/no_think":"","You are planning delegation for a delegation-only agent.","Choose exactly one listed subagent when one specialist can responsibly handle the request.","If the request naturally requires multiple specialist-owned steps, return an ordered delegation plan instead of one subagent.","A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.","Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.","For multi-line or numbered requests, evaluate every requested item semantically before choosing the final owner list.","Use the agent routing policy as authoritative routing configuration when it maps request meaning to listed subagents.","Apply the routing policy and subagent catalog literally; do not assign work to a subagent when the policy says that subagent is not the owner.","When the routing policy or subagent catalog says a request class routes to one owner only, choose that single owner.","Evidence dimensions inside one request, such as tools, files, CI, output format, failure states, routing, or runtime paths, are inputs to the selected owner; they do not create extra owners unless the user asks those specialists to do their own work.","A request made from one specialist perspective is single-owner when that specialist can responsibly handle the whole requested assessment.","Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.","Do not merge one listed subagent's configured responsibility into another listed subagent's task.","A broad request can still be handleable when multiple listed subagents each own part of it; return a delegation plan in that case.","Do not refuse while any listed subagent can own the request or a subtask after applying the routing policy.","Refuse only when the request is outside every listed subagent's configured responsibility.",h?"Agent routing policy:":"",h,"For one specialist, return only JSON with this shape:",'{"subagent_type":"<listed subagent name>"}',"For multiple specialist steps, return only JSON with this shape:",`{"delegations":[{"subagent_type":"<listed subagent name>","description":"<only that specialist's owned portion>"}]}`,"If no listed subagent can handle the request, return only:",'{"status":"refused","reason":"No configured subagent can handle the request."}',"Available subagents:",A,"User request:",a].filter(Boolean).join(`
32
+
33
+ `);let u=null;const l=async(T,M)=>!u||typeof u.invoke!="function"?null:this.invokeWithProviderRetry(e,()=>this.withTimeout(()=>u.invoke(T,X(e,{sessionId:n,requestId:o,context:s.context,toolRuntimeContext:this.buildFunctionToolRuntimeContext(e,{...s,sessionId:n,requestId:o})})),ne(e),M,"invoke"));if(!i){if(u=await this.resolveModel(g),typeof u.invoke!="function")return null;const T=[R,[R,"Your previous router output was invalid.","Return only one JSON object now. Do not include prose, markdown, labels, or tool-call wrappers."].join(`
34
+
35
+ `),[g.init?.think===!1?"/no_think":"","Select one subagent or an ordered delegation plan from this exact list:",Array.from(b).join(", "),"Return JSON only. Single-specialist shape:",'{"subagent_type":"<one exact listed name>"}',"Multi-specialist shape:",'{"delegations":[{"subagent_type":"<one exact listed name>","description":"<owned subtask>"}]}',"User request:",a].filter(Boolean).join(`
36
+
37
+ `),[g.init?.think===!1?"/no_think":"","JSON only. Pick a listed subagent, return delegations, or refuse.","Listed subagents:",Array.from(b).join(", "),"Allowed outputs:",'{"subagent_type":"<listed name>"}','{"delegations":[{"subagent_type":"<listed name>","description":"<owned subtask>"}]}','{"status":"refused","reason":"No configured subagent can handle the request."}',"Request:",a].filter(Boolean).join(`
38
+
39
+ `),[g.init?.think===!1?"/no_think":"","Multi-specialist delegation is supported.","If a request needs multiple listed specialists, that is not a refusal condition.","A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.","Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.","Return a delegations array that assigns each specialist-owned work item to listed subagents.","Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.","Do not merge one listed subagent's configured responsibility into another listed subagent's task.","Do not turn supporting evidence dimensions into separate owners when one listed subagent owns the requested assessment.","Never return final response fields such as routing, todoTrace, stepResults, summary, findings, blockers, nextActions, or report.","Return JSON only with this exact shape:",'{"delegations":[{"subagent_type":"<one exact listed name>","description":"<owned subtask>"}]}',h?"Agent routing policy:":"",h,"Available subagents:",A,"User request:",a].filter(Boolean).join(`
40
+
41
+ `)];let M="";for(let x=0;x<T.length;x+=1){const D=x<=1||!M?T[x]:[T[x],"Previous output:",M].join(`
42
+
43
+ `),d=await l(D,x===0?"delegation router invoke":`delegation router retry invoke ${x}`);if(d===null)break;M=re(d);const y=ae(M,b);if(y){if(y.delegations&&y.delegations.length>1){i=y;break}if(y.subagentType&&!$){i=y;break}(!i||i.refusedReason||y.subagentType)&&(i=y.refusedReason&&x<T.length-1?i:y)}}}if(i?.delegations||i?.subagentType){const T=i.delegations??[{subagentType:i.subagentType,description:a}],M=T.map((d,y)=>`${y+1}. ${d.subagentType}: ${d.description}`).join(`
44
+ `),x=[g.init?.think===!1?"/no_think":"","Verify this delegation plan against the user request and routing policy.","Internally review every sentence or list item in the user request before returning JSON.","Return one corrected JSON object only.","Keep the candidate plan unchanged when it already covers every specialist-owned work item.","Return a single subagent_type when one listed subagent owns the whole request and the candidate plan only split supporting evidence dimensions.","A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.","Return multi-owner delegations only when the user asks for multiple independently owned specialist work items.","If the candidate omits a specialist-owned work item, add that listed subagent in the correct user-requested order.","If the candidate includes a subagent whose described work is not owned by that subagent, remove or replace it.","Evaluate each listed subagent independently against the request and include every listed owner whose configured responsibility is required.","Do not merge one listed subagent's configured responsibility into another listed subagent's task.","Do not turn supporting evidence dimensions into separate owners when one listed subagent owns the requested assessment.","Do not add a subagent unless the routing policy or subagent catalog makes ownership clear.","When the routing policy states that a subagent is not the owner for a domain, do not assign that domain to that subagent.","Use only listed subagent names.",h?"Agent routing policy:":"",h,"Available subagents:",A,"Candidate delegation plan:",M,"Allowed JSON shapes:",'{"subagent_type":"<listed subagent name>"}',`{"delegations":[{"subagent_type":"<listed subagent name>","description":"<only that specialist's owned portion>"}]}`,"User request:",a].filter(Boolean).join(`
45
+
46
+ `),D=await l(x,"delegation router coverage invoke");if(D!==null){const d=re(D),y=ae(d,b);if(y?.subagentType&&!$&&(i=y),y?.delegations&&y.delegations.length===1&&!$&&(i={subagentType:y.delegations[0].subagentType}),y?.delegations&&y.delegations.length>1){const S=new Set(T.map(U=>U.subagentType)),q=new Set(y.delegations.map(U=>U.subagentType));Array.from(S).every(U=>q.has(U))&&(i=y)}}if(T.length>1&&i?.delegations&&i.delegations.length>1){const d=i.delegations.map((q,_)=>`${_+1}. ${q.subagentType}: ${q.description}`).join(`
47
+ `),y=[g.init?.think===!1?"/no_think":"","Arbitrate whether this delegation plan is over-split.","The runtime supports both one-owner and multi-owner delegation.","Choose one owner when the routing policy or subagent catalog says one listed subagent owns the whole request.","A single objective with multiple evidence requirements is still single-owner when one listed subagent owns the objective.","Treat supporting evidence dimensions as inputs to that owner, not as separate owners.","Keep multi-owner delegation only when the user asked for multiple independently owned specialist work items.","Return exactly one JSON object and no prose.","Single-owner shape:",'{"subagent_type":"<listed subagent name>"}',"Multi-owner shape:",`{"delegations":[{"subagent_type":"<listed subagent name>","description":"<only that specialist's owned portion>"}]}`,h?"Agent routing policy:":"",h,"Available subagents:",A,"Candidate plan:",d,"User request:",a].filter(Boolean).join(`
48
+
49
+ `),S=await l(y,"delegation router over-split arbitration invoke");if(S!==null){const q=re(S),_=ae(q,b);_?.subagentType&&!$?i=_:_?.delegations&&_.delegations.length===1&&!$?i={subagentType:_.delegations[0].subagentType}:_?.delegations&&_.delegations.length>1&&(i=_)}}}if(i?.delegations?.length===1&&(i={subagentType:i.delegations[0].subagentType}),i?.delegations&&i.delegations.length>1){const M=i.delegations,x=[],D=[];yield{kind:"commentary",content:`Planned delegation tree: ${M.map(v=>v.subagentType).join(" -> ")}.`,agentId:e.agent.id};const d=async function*(v,N,j="",F={}){const I=this.options.bindingResolver?.(v);if(!I){const B=`Configured subagent '${v}' could not be resolved.`;return{sessionId:n,requestId:`${o}:${v}${j}`,agentId:v,state:"failed",output:B,finalMessageText:B,metadata:{executedToolResults:[]}}}const J=[];let P="";try{for await(const B of this.stream(I,N,n,[],{context:s.context,state:F.state??s.state,files:s.files,requestId:`${o}:${v}${j}`,memoryContext:s.memoryContext,profiling:s.profiling,suppressInitialRequiredPlanInstruction:F.suppressInitialRequiredPlanInstruction,externalPlanEvidence:F.externalPlanEvidence})){if(typeof B=="string"){P+=B;continue}if(B.kind==="content"){P+=B.content??"";continue}if(B.kind==="tool-result"&&G(J,{toolName:B.toolName,output:B.output,...B.isError!==void 0?{isError:B.isError}:{}}),B.kind==="upstream-event"){const we=Ke(B.event);we&&G(J,we)}yield{...B,agentId:B.agentId??I.agent.id}}}catch(B){return P=B instanceof Error?B.message:String(B),{sessionId:n,requestId:`${o}:${v}${j}`,agentId:I.agent.id,state:"failed",output:P,finalMessageText:P,metadata:{executedToolResults:J,...F.externalPlanEvidence===!0?{externalPlanEvidence:!0}:{}}}}const Re=F.externalPlanEvidence===!0&&Ue(J)?We(J):te(P);return{sessionId:n,requestId:`${o}:${v}${j}`,agentId:I.agent.id,state:"completed",output:Re,finalMessageText:Re,metadata:{executedToolResults:J,...F.externalPlanEvidence===!0?{externalPlanEvidence:!0}:{}}}}.bind(this);for(const[v,N]of M.entries()){const j=this.options.bindingResolver?.(N.subagentType),F=he({subagentType:N.subagentType,taskText:N.description,originalRequest:a});yield{kind:"commentary",content:`Delegating to ${N.subagentType}.`,agentId:e.agent.id},yield{kind:"commentary",content:"Starting delegated execution.",agentId:j?.agent.id??N.subagentType};let I=yield*d(N.subagentType,F);if(z(j,I)){const P=I;I=Z(yield*d(N.subagentType,[F,le].filter(Boolean).join(`
50
+
51
+ `),":plan-evidence-retry"),P)}if(z(j,I)){const P=I;I=Z(yield*d(N.subagentType,[F,Te].filter(Boolean).join(`
52
+
53
+ `),":plan-evidence-final-retry",be(j,s,F)),P)}if(z(j,I)){const P=ye(j?.agent.id??N.subagentType);I={...I,state:"failed",output:P,finalMessageText:P}}const J=Array.isArray(I.metadata?.executedToolResults)?I.metadata.executedToolResults:[];for(const P of J)typeof P.toolName=="string"&&(G(x,{toolName:P.toolName,output:P.output,...P.isError!==void 0?{isError:!!P.isError}:{}}),!L(P.toolName)&&(yield{kind:"commentary",content:`Running tool ${P.toolName}.`,agentId:j?.agent.id??N.subagentType},yield{kind:"commentary",content:`Tool ${P.toolName} ${P.isError===!0?"failed":"completed"}.`,agentId:j?.agent.id??N.subagentType}));D.push({subagentType:N.subagentType,result:I,output:typeof I.output=="string"?I.output:String(I.output??"")}),v<M.length-1&&(yield{kind:"commentary",content:"Continuing ordered delegation plan.",agentId:e.agent.id})}const y=D.filter(v=>v.result.state==="failed"),S=[...new Set(x.map(v=>v.toolName))],q=y.length>0?"failed":"completed",_=D.map(v=>`## ${v.subagentType}
54
+ ${v.output.trim()||"No visible output returned."}`).join(`
55
+
56
+ `),U={status:q,routing:M.map((v,N)=>`${N+1}) \u8DEF\u7531\u5224\u65AD: ${v.subagentType} \u8D1F\u8D23 ${v.description.trim()||"\u8BE5\u4E13\u4E1A\u57DF\u5B50\u4EFB\u52A1"}\u3002`),plan:M.map((v,N)=>`${N+1}) \u59D4\u6258 ${v.subagentType}: ${v.description.trim()||"\u6267\u884C\u5176\u4E13\u4E1A\u57DF\u4EFB\u52A1"}\u3002`),execution:D.map((v,N)=>`${N+1}) ${v.subagentType} ${v.result.state==="failed"?"failed":"completed"}\u3002`),todoTrace:D.map((v,N)=>`${N+1}) ${v.subagentType}: ${ie(v.result)?"TODO evidence observed":"TODO evidence missing"}\u3002`),stepResults:D.map((v,N)=>`${N+1}) ${v.subagentType}: delegated result collected; aggregate tools = ${S.length>0?S.join(", "):"none"}\u3002`),summary:[q==="failed"?`\u591A specialist \u7F16\u6392\u5B8C\u6210\uFF0C\u4F46 ${y.length} \u4E2A\u59D4\u6258\u8FD4\u56DE failed\u3002`:"\u591A specialist \u7F16\u6392\u5DF2\u5B8C\u6210\uFF0C\u6240\u6709\u59D4\u6258\u5747\u8FD4\u56DE completed\u3002"],findings:D.map(v=>`${v.subagentType}: ${v.output.trim().slice(0,500)||"No finding text returned."}`),blockers:y.length>0?y.map(v=>`${v.subagentType}: delegated execution failed.`):["none"],nextActions:y.length>0?["\u67E5\u770B failed specialist \u7684 blocker \u5E76\u5355\u72EC\u91CD\u8DD1\u8BE5\u59D4\u6258\u3002"]:["\u53EF\u57FA\u4E8E\u5404 specialist \u7ED3\u679C\u7EE7\u7EED\u505A\u6700\u7EC8\u4FEE\u590D\u6216\u53D1\u5E03\u51B3\u7B56\u3002"],report:_},ue=JSON.stringify(U);return{toolOutput:ue,delegatedSubagentType:"multiple",delegatedResult:{sessionId:n,requestId:o,agentId:e.agent.id,state:q,output:ue,finalMessageText:ue,metadata:{executedToolResults:x,delegations:D.map(v=>({subagentType:v.subagentType,state:v.result.state}))}}}}if(i?.refusedReason)return{toolOutput:i.refusedReason,delegatedSubagentType:null,delegatedResult:{sessionId:n,requestId:o,agentId:e.agent.id,state:"failed",output:i.refusedReason,finalMessageText:i.refusedReason}};let w=i?.subagentType??"";if(!b.has(w))return null;const m=this.options.bindingResolver(w);if(!m)return null;yield{kind:"commentary",content:`Delegating to ${w}.`,agentId:e.agent.id},yield{kind:"commentary",content:"Starting delegated execution.",agentId:m.agent.id};const O=`${o}:${w}`,E=async function*(T,M="",x={}){const D=[];let d="";try{for await(const S of this.stream(m,T,n,[],{context:s.context,state:x.state??s.state,files:s.files,requestId:`${O}${M}`,memoryContext:s.memoryContext,profiling:s.profiling,toolRuntimeContext:x.toolRuntimeContext??s.toolRuntimeContext,suppressInitialRequiredPlanInstruction:x.suppressInitialRequiredPlanInstruction,externalPlanEvidence:x.externalPlanEvidence})){if(typeof S=="string"){d+=S;continue}if(S.kind==="content"){d+=S.content??"";continue}if(S.kind==="tool-result"&&G(D,{toolName:S.toolName,output:S.output,...S.isError!==void 0?{isError:S.isError}:{}}),S.kind==="upstream-event"){const q=Ke(S.event);q&&G(D,q)}yield{...S,agentId:S.agentId??m.agent.id}}}catch(S){return d=S instanceof Error?S.message:String(S),{sessionId:n,requestId:`${O}${M}`,agentId:m.agent.id,state:"failed",output:d,finalMessageText:d,metadata:{executedToolResults:D,...x.externalPlanEvidence===!0?{externalPlanEvidence:!0}:{}}}}const y=x.externalPlanEvidence===!0&&Ue(D)?We(D):te(d);return{sessionId:n,requestId:`${O}${M}`,agentId:m.agent.id,state:"completed",output:y,finalMessageText:y,metadata:{executedToolResults:D,...x.externalPlanEvidence===!0?{externalPlanEvidence:!0}:{}}}}.bind(this),f=he({subagentType:w,taskText:a,originalRequest:a});let p=yield*E(f);if(z(m,p)){const T=p;p=Z(yield*E([f,le].filter(Boolean).join(`
57
+
58
+ `),":plan-evidence-retry"),T)}if(z(m,p)){const T=p;p=Z(yield*E([f,Te].filter(Boolean).join(`
59
+
60
+ `),":plan-evidence-final-retry",be(m,s,f)),T)}if(z(m,p)){const T=ye(m.agent.id);p={...p,state:"failed",output:T,finalMessageText:T}}const C=Array.isArray(p.metadata?.executedToolResults)?p.metadata.executedToolResults:[];for(const T of C){const M=typeof T.toolName=="string"?T.toolName:"";!M||L(M)||(yield{kind:"commentary",content:`Running tool ${M}.`,agentId:m.agent.id},yield{kind:"commentary",content:`Tool ${M} ${T.isError===!0?"failed":"completed"}.`,agentId:m.agent.id})}return{toolOutput:He(p),delegatedSubagentType:w,delegatedResult:p}}async*stream(e,t,n,o=[],s={}){ve(e)&&(yield{kind:"commentary",content:"Selecting a specialist for delegated execution."});const g=yield*this.streamDelegateWithCompactRouter(e,t,n,s.requestId??n,s);if(g){const u=this.buildCompactDelegationReport(g);yield{kind:"tool-result",toolName:"task",output:g.toolOutput},yield{kind:"content",content:g.delegatedSubagentType===null?String(g.toolOutput??""):this.formatCompactDelegationReportForDisplay(u)};return}const a=ne(e),c=It(e),b=a?Date.now()+a:void 0,{primaryTools:$,toolNameMapping:i,forceInvokeFallback:A,canUseDirectModelStream:k,langChainStreamModel:h}=await qt({binding:e,getToolNameMapping:u=>this.getToolNameMapping(u),resolveModel:u=>this.resolveModel(u),resolveTools:(u,l)=>this.resolveTools(u,l)}),R=this.buildFunctionToolRuntimeContext(e,{...s,sessionId:n,requestId:s.requestId});yield*mt({binding:e,input:t,sessionId:n,history:o,runtimeOptions:{...s,requestId:s.requestId,profiling:s.profiling,...R?{toolRuntimeContext:R}:{}},primaryTools:$,toolNameMapping:i,forceInvokeFallback:A,canUseDirectModelStream:k,langChainStreamModel:h,createRunnable:()=>this.create(e,{sessionId:n}),resolveInvocationConfig:(u,l)=>X(u,{sessionId:l.sessionId,requestId:l.requestId,...l.context?{context:l.context}:{},...l.toolRuntimeContext?{toolRuntimeContext:l.toolRuntimeContext}:{}}),withTimeout:(u,l,w,m)=>this.withTimeout(u,l,w,m),iterateWithTimeout:(u,l,w,m,O)=>this.iterateWithTimeout(u,l,w,m,O),invokeTimeoutMs:a,streamIdleTimeoutMs:c,streamDeadlineAt:b,invoke:(u,l,w,m,O,E,f)=>this.invoke(u,l,w,m,O,E,f),applyToolRecoveryInstruction:(u,l)=>yt(u,l),isRetryableProviderError:(u,l)=>jt(u,l),getSystemPrompt:u=>H(u),isLangChainBinding:Le,isDeepAgentBinding:Fe,countConfiguredTools:je,countConfiguredToolsForAgentId:u=>{const l=this.options.bindingResolver?.(u);return l?je(l):0}})}}export{De as AGENT_INTERRUPT_SENTINEL_PREFIX,Vt as AgentRuntimeAdapter,at as DEFAULT_DEEPAGENT_RECURSION_LIMIT,De as INTERRUPT_SENTINEL_PREFIX,Vt as RuntimeAdapter,kt as RuntimeOperationTimeoutError,Cn as buildAuthOmittingFetch,rt as buildDeepAgentCreateParams,Ne as buildLangChainCreateParams,Nn as buildToolNameMapping,qn as computeRemainingTimeoutMs,Pn as createModelFacingToolNameCandidates,On as createModelFacingToolNameLookupCandidates,jn as isRetryableProviderError,xn as materializeDeepAgentSkillSourcePaths,de as materializeModelExposedBuiltinMiddlewareTools,Dn as normalizeOpenAICompatibleInit,Mn as relativizeDeepAgentSkillSourcePaths,Fn as resolveBindingTimeout,Sn as resolveDeepAgentSkillSourcePaths,An as resolveDeepAgentSkillSourceRootPaths,X as resolveLangChainInvocationConfig,In as resolveModelFacingToolName,Ln as resolveProviderRetryPolicy,ce as resolveRunnableCheckpointer,ge as resolveRunnableInterruptOn,zn as resolveStreamIdleTimeout,Jn as resolveTimeoutMs,Bn as sanitizeToolNameForModel};