@n8n/agents 0.26.3 → 0.27.1

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 (70) hide show
  1. package/dist/build.tsbuildinfo +1 -1
  2. package/dist/runtime/loop/agent-runtime.d.ts +24 -51
  3. package/dist/runtime/loop/agent-runtime.js +321 -318
  4. package/dist/runtime/loop/agent-runtime.js.map +1 -1
  5. package/dist/runtime/loop/checkpoint-data.d.ts +12 -0
  6. package/dist/runtime/loop/checkpoint-data.js +65 -0
  7. package/dist/runtime/loop/checkpoint-data.js.map +1 -0
  8. package/dist/runtime/loop/execution-counter.js +1 -5
  9. package/dist/runtime/loop/execution-counter.js.map +1 -1
  10. package/dist/runtime/loop/generate-sink.d.ts +2 -2
  11. package/dist/runtime/loop/generate-sink.js +3 -5
  12. package/dist/runtime/loop/generate-sink.js.map +1 -1
  13. package/dist/runtime/loop/run-output-sink.d.ts +3 -78
  14. package/dist/runtime/loop/run-output-sink.js +7 -0
  15. package/dist/runtime/loop/run-output-sink.js.map +1 -1
  16. package/dist/runtime/loop/runtime-context.d.ts +17 -1
  17. package/dist/runtime/loop/runtime-context.js +49 -20
  18. package/dist/runtime/loop/runtime-context.js.map +1 -1
  19. package/dist/runtime/loop/runtime-helpers.d.ts +1 -1
  20. package/dist/runtime/loop/stream-sink.d.ts +9 -2
  21. package/dist/runtime/loop/stream-sink.js +78 -56
  22. package/dist/runtime/loop/stream-sink.js.map +1 -1
  23. package/dist/runtime/memory/memory-orchestrator.d.ts +1 -1
  24. package/dist/runtime/memory/memory-orchestrator.js +8 -8
  25. package/dist/runtime/memory/memory-orchestrator.js.map +1 -1
  26. package/dist/runtime/memory/memory-store.d.ts +1 -1
  27. package/dist/runtime/memory/memory-store.js +7 -2
  28. package/dist/runtime/memory/memory-store.js.map +1 -1
  29. package/dist/runtime/memory/tool-result-memory.d.ts +7 -0
  30. package/dist/runtime/memory/tool-result-memory.js +65 -0
  31. package/dist/runtime/memory/tool-result-memory.js.map +1 -0
  32. package/dist/runtime/model/messages.js +20 -9
  33. package/dist/runtime/model/messages.js.map +1 -1
  34. package/dist/runtime/model/raw-error.d.ts +1 -1
  35. package/dist/runtime/state/run-state.d.ts +2 -2
  36. package/dist/runtime/state/run-state.js +4 -4
  37. package/dist/runtime/state/run-state.js.map +1 -1
  38. package/dist/runtime/telemetry/runtime-telemetry.d.ts +1 -1
  39. package/dist/runtime/tools/delegate-sub-agent-runner.d.ts +13 -0
  40. package/dist/runtime/tools/delegate-sub-agent-runner.js +361 -0
  41. package/dist/runtime/tools/delegate-sub-agent-runner.js.map +1 -0
  42. package/dist/runtime/tools/delegate-sub-agent-tool.d.ts +5 -241
  43. package/dist/runtime/tools/delegate-sub-agent-tool.js +94 -487
  44. package/dist/runtime/tools/delegate-sub-agent-tool.js.map +1 -1
  45. package/dist/runtime/tools/tool-adapter.js +28 -28
  46. package/dist/runtime/tools/tool-adapter.js.map +1 -1
  47. package/dist/runtime/tools/tool-call-executor.d.ts +19 -86
  48. package/dist/runtime/tools/tool-call-executor.js +236 -579
  49. package/dist/runtime/tools/tool-call-executor.js.map +1 -1
  50. package/dist/runtime/tools/tool-call-runner.d.ts +25 -0
  51. package/dist/runtime/tools/tool-call-runner.js +328 -0
  52. package/dist/runtime/tools/tool-call-runner.js.map +1 -0
  53. package/dist/runtime/tools/tool-result-guard.d.ts +2 -7
  54. package/dist/runtime/tools/tool-result-guard.js +13 -70
  55. package/dist/runtime/tools/tool-result-guard.js.map +1 -1
  56. package/dist/types/runtime/agent-loop.d.ts +73 -0
  57. package/dist/types/runtime/agent-loop.js +3 -0
  58. package/dist/types/runtime/agent-loop.js.map +1 -0
  59. package/dist/types/runtime/agent-runtime.d.ts +51 -0
  60. package/dist/types/runtime/agent-runtime.js +3 -0
  61. package/dist/types/runtime/agent-runtime.js.map +1 -0
  62. package/dist/types/runtime/delegation.d.ts +234 -0
  63. package/dist/types/runtime/delegation.js +82 -0
  64. package/dist/types/runtime/delegation.js.map +1 -0
  65. package/dist/types/runtime/tool-execution.d.ts +103 -0
  66. package/dist/types/runtime/tool-execution.js +3 -0
  67. package/dist/types/runtime/tool-execution.js.map +1 -0
  68. package/dist/types/sdk/agent-builder.d.ts +1 -1
  69. package/dist/types/sdk/memory.d.ts +2 -1
  70. package/package.json +6 -6
@@ -1,133 +1,25 @@
1
1
  "use strict";
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
- exports.SUB_AGENT_TASK_DIFFICULTIES = exports.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY = exports.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE = exports.INLINE_SUB_AGENT_ID = exports.DELEGATE_SUB_AGENT_TOOL_NAME = void 0;
4
- exports.parseDelegateSubAgentContinuation = parseDelegateSubAgentContinuation;
3
+ exports.parseDelegateSubAgentContinuation = exports.SUB_AGENT_TASK_DIFFICULTIES = exports.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY = exports.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE = exports.INLINE_SUB_AGENT_ID = exports.DELEGATE_SUB_AGENT_TOOL_NAME = exports.renderDelegateSubAgentPrompt = exports.generateResultToDelegateSubAgentOutput = exports.failedDelegatedChildSuspendOutput = void 0;
5
4
  exports.createDelegateSubAgentTool = createDelegateSubAgentTool;
6
5
  exports.getInlineDelegateSubAgentToolOptions = getInlineDelegateSubAgentToolOptions;
7
6
  exports.isDelegateSubAgentTool = isDelegateSubAgentTool;
8
- exports.renderDelegateSubAgentPrompt = renderDelegateSubAgentPrompt;
9
- exports.failedDelegatedChildSuspendOutput = failedDelegatedChildSuspendOutput;
10
- exports.generateResultToDelegateSubAgentOutput = generateResultToDelegateSubAgentOutput;
11
- const is_record_1 = require("@n8n/utils/is-record");
12
- const zod_1 = require("zod");
7
+ const delegate_sub_agent_runner_1 = require("./delegate-sub-agent-runner");
13
8
  const sdk_owned_tool_1 = require("./sdk-owned-tool");
14
9
  const sub_agent_task_path_1 = require("./sub-agent-task-path");
15
- const abort_1 = require("../../sdk/abort");
16
- const message_1 = require("../../sdk/message");
17
10
  const tool_1 = require("../../sdk/tool");
18
- const execution_counter_1 = require("../loop/execution-counter");
19
- exports.DELEGATE_SUB_AGENT_TOOL_NAME = 'delegate_subagent';
20
- exports.INLINE_SUB_AGENT_ID = 'inline';
21
- exports.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE = 'agents.chat.delegate.childSuspendUnsupported';
22
- exports.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY = 'inlineDelegateSubAgent';
23
- exports.SUB_AGENT_TASK_DIFFICULTIES = ['low', 'medium', 'high'];
24
- const SubAgentTaskDifficultySchema = zod_1.z.enum(exports.SUB_AGENT_TASK_DIFFICULTIES);
25
- const jsonValueSchema = zod_1.z.lazy(() => zod_1.z.union([
26
- zod_1.z.string(),
27
- zod_1.z.number(),
28
- zod_1.z.boolean(),
29
- zod_1.z.null(),
30
- zod_1.z.array(jsonValueSchema),
31
- zod_1.z.record(zod_1.z.string(), jsonValueSchema),
32
- ]));
33
- const delegateSubAgentInputSchema = zod_1.z.object({
34
- subAgentId: zod_1.z
35
- .string()
36
- .min(1)
37
- .describe('Required. Use "inline" for a one-off inline sub-agent. Use an exact configured sub-agent ID only when one is listed and fits the task.'),
38
- taskName: zod_1.z
39
- .string()
40
- .min(1)
41
- .describe('Short human-readable name for this delegated task, e.g. "research_api".'),
42
- goal: zod_1.z.string().min(1).describe('The concrete goal the sub-agent should accomplish.'),
43
- context: zod_1.z
44
- .string()
45
- .optional()
46
- .describe('All details the child needs, since it sees nothing else: constraints, paths, data, prior decisions, acceptance criteria, and what you have already tried or ruled out.'),
47
- expectedOutput: zod_1.z.string().optional().describe('The expected shape or contents of the answer.'),
48
- difficulty: SubAgentTaskDifficultySchema.optional().describe('Optional difficulty estimate for this delegated task. Use low for simple bounded work, medium for moderate analysis or implementation, and high for complex research, architecture, or multi-step reasoning.'),
49
- });
50
- const delegateSubAgentOutputSchema = zod_1.z.object({
51
- status: zod_1.z.enum(['completed', 'failed', 'suspended', 'cancelled']),
52
- taskPath: zod_1.z.string().optional(),
53
- runId: zod_1.z.string().optional(),
54
- threadId: zod_1.z.string().optional(),
55
- model: zod_1.z.string().optional(),
56
- answer: zod_1.z.string(),
57
- structuredOutput: zod_1.z.unknown().optional(),
58
- usage: zod_1.z
59
- .object({
60
- promptTokens: zod_1.z.number().optional(),
61
- completionTokens: zod_1.z.number().optional(),
62
- totalTokens: zod_1.z.number().optional(),
63
- cost: zod_1.z.number().optional(),
64
- })
65
- .optional(),
66
- finishReason: zod_1.z.string().optional(),
67
- error: zod_1.z.string().optional(),
68
- resumeContext: jsonValueSchema.optional(),
69
- pendingSuspend: zod_1.z
70
- .array(zod_1.z.object({
71
- runId: zod_1.z.string(),
72
- toolCallId: zod_1.z.string(),
73
- toolName: zod_1.z.string(),
74
- input: zod_1.z.unknown(),
75
- suspendPayload: zod_1.z.unknown(),
76
- resumeSchema: zod_1.z.unknown().optional(),
77
- }))
78
- .optional(),
79
- });
80
- const delegateSubAgentContinuationSchema = zod_1.z.object({
81
- runId: zod_1.z.string(),
82
- toolCallId: zod_1.z.string(),
83
- taskPath: zod_1.z.string(),
84
- subAgentId: zod_1.z.string(),
85
- childCount: zod_1.z.number().int().nonnegative(),
86
- threadId: zod_1.z.string().optional(),
87
- resumeContext: jsonValueSchema.optional(),
88
- });
89
- const delegateSubAgentSuspendSchema = zod_1.z.unknown();
90
- const delegateSubAgentResumeSchema = zod_1.z.unknown();
91
- function parseDelegateSubAgentContinuation(value) {
92
- const parsed = delegateSubAgentContinuationSchema.safeParse(value);
93
- return parsed.success ? parsed.data : undefined;
94
- }
95
- const SUB_AGENT_FORWARD_CHAR_BUDGET = 20_000;
96
- const FORWARDED_CHILD_CHUNK_TYPES = new Set([
97
- 'text-delta',
98
- 'reasoning-start',
99
- 'reasoning-delta',
100
- 'reasoning-end',
101
- 'tool-input-start',
102
- 'tool-execution-start',
103
- 'tool-execution-end',
104
- ]);
105
- function isForwardedChildChunk(chunk) {
106
- return FORWARDED_CHILD_CHUNK_TYPES.has(chunk.type);
107
- }
108
- function createEmitChunkHelper(ctx, request) {
109
- let forwardedChars = 0;
110
- return (chunk) => {
111
- if (request.parentToolCallId === undefined)
112
- return;
113
- if (!isForwardedChildChunk(chunk))
114
- return;
115
- let forwarded = chunk;
116
- if (chunk.type === 'text-delta' || chunk.type === 'reasoning-delta') {
117
- const remaining = SUB_AGENT_FORWARD_CHAR_BUDGET - forwardedChars;
118
- if (remaining <= 0)
119
- return;
120
- const delta = chunk.delta.slice(0, remaining);
121
- forwardedChars += delta.length;
122
- forwarded = { ...chunk, delta };
123
- }
124
- ctx.emitEvent?.({
125
- type: "subagent_chunk",
126
- ...subAgentLifecycleBase(request),
127
- chunk: forwarded,
128
- });
129
- };
130
- }
11
+ const delegation_1 = require("../../types/runtime/delegation");
12
+ var delegate_sub_agent_runner_2 = require("./delegate-sub-agent-runner");
13
+ Object.defineProperty(exports, "failedDelegatedChildSuspendOutput", { enumerable: true, get: function () { return delegate_sub_agent_runner_2.failedDelegatedChildSuspendOutput; } });
14
+ Object.defineProperty(exports, "generateResultToDelegateSubAgentOutput", { enumerable: true, get: function () { return delegate_sub_agent_runner_2.generateResultToDelegateSubAgentOutput; } });
15
+ Object.defineProperty(exports, "renderDelegateSubAgentPrompt", { enumerable: true, get: function () { return delegate_sub_agent_runner_2.renderDelegateSubAgentPrompt; } });
16
+ var delegation_2 = require("../../types/runtime/delegation");
17
+ Object.defineProperty(exports, "DELEGATE_SUB_AGENT_TOOL_NAME", { enumerable: true, get: function () { return delegation_2.DELEGATE_SUB_AGENT_TOOL_NAME; } });
18
+ Object.defineProperty(exports, "INLINE_SUB_AGENT_ID", { enumerable: true, get: function () { return delegation_2.INLINE_SUB_AGENT_ID; } });
19
+ Object.defineProperty(exports, "DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE", { enumerable: true, get: function () { return delegation_2.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE; } });
20
+ Object.defineProperty(exports, "INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY", { enumerable: true, get: function () { return delegation_2.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY; } });
21
+ Object.defineProperty(exports, "SUB_AGENT_TASK_DIFFICULTIES", { enumerable: true, get: function () { return delegation_2.SUB_AGENT_TASK_DIFFICULTIES; } });
22
+ Object.defineProperty(exports, "parseDelegateSubAgentContinuation", { enumerable: true, get: function () { return delegation_2.parseDelegateSubAgentContinuation; } });
131
23
  function resolveDelegateSubAgentPolicy(policy, toolName) {
132
24
  const resolvedPolicy = {
133
25
  ...policy,
@@ -145,7 +37,7 @@ function resolveDelegateSubAgentPolicy(policy, toolName) {
145
37
  const DELEGATE_SUB_AGENT_TOOL_NAME_PATTERN = /^[a-zA-Z][a-zA-Z0-9_-]{0,63}$/;
146
38
  function resolveDelegateSubAgentToolName(name) {
147
39
  if (name === undefined)
148
- return exports.DELEGATE_SUB_AGENT_TOOL_NAME;
40
+ return delegation_1.DELEGATE_SUB_AGENT_TOOL_NAME;
149
41
  if (!DELEGATE_SUB_AGENT_TOOL_NAME_PATTERN.test(name)) {
150
42
  throw new Error(`Invalid delegate sub-agent tool name "${name}": must start with a letter and contain only letters, digits, underscores, and hyphens (max 64 characters)`);
151
43
  }
@@ -178,6 +70,18 @@ function resolveDelegateSubAgentSystemInstruction(options, toolName, inlineProvi
178
70
  function createDelegateSubAgentTool(options = {}) {
179
71
  const childPathIndexes = new Map();
180
72
  const toolName = resolveDelegateSubAgentToolName(options.name);
73
+ const resolvedOptions = resolveDelegateSubAgentOptions(options, toolName);
74
+ const tool = buildDelegateSubAgentTool(toolName, resolvedOptions, childPathIndexes);
75
+ return (0, sdk_owned_tool_1.withSdkOwnedBuiltInMetadata)({
76
+ ...tool,
77
+ ...createDelegateCancellationHandler(resolvedOptions, childPathIndexes),
78
+ metadata: {
79
+ ...tool.metadata,
80
+ [delegation_1.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY]: buildDelegateToolMetadata(resolvedOptions),
81
+ },
82
+ });
83
+ }
84
+ function resolveDelegateSubAgentOptions(options, toolName) {
181
85
  const resolvedOptions = {
182
86
  ...options,
183
87
  policy: resolveDelegateSubAgentPolicy(options.policy, toolName),
@@ -186,85 +90,87 @@ function createDelegateSubAgentTool(options = {}) {
186
90
  (resolvedOptions.cancelSubAgent === undefined)) {
187
91
  throw new Error(`${toolName} requires resumeSubAgent and cancelSubAgent to be configured together`);
188
92
  }
93
+ return resolvedOptions;
94
+ }
95
+ function buildDelegateSubAgentTool(toolName, resolvedOptions, childPathIndexes) {
189
96
  const inlineProviderToolInstruction = resolvedOptions.resolveInlineSubAgentProviderTools
190
97
  ? "Provider-defined tools are loaded for the inline child's selected model provider."
191
98
  : 'Inline children do not inherit provider-defined tools.';
192
99
  const toolBuilder = new tool_1.Tool(toolName)
193
100
  .description(resolveDelegateSubAgentDescription(resolvedOptions))
194
101
  .systemInstruction(resolveDelegateSubAgentSystemInstruction(resolvedOptions, toolName, inlineProviderToolInstruction))
195
- .input(delegateSubAgentInputSchema)
196
- .output(delegateSubAgentOutputSchema);
197
- const handler = async (input, ctx) => await handleDelegateSubAgent(input, ctx, resolvedOptions, childPathIndexes);
102
+ .input(delegation_1.delegateSubAgentInputSchema)
103
+ .output(delegation_1.delegateSubAgentOutputSchema);
104
+ const handler = async (input, ctx) => await (0, delegate_sub_agent_runner_1.handleDelegateSubAgent)(input, ctx, resolvedOptions, childPathIndexes);
198
105
  const toModelOutput = (output) => resolvedOptions.toModelOutput ? resolvedOptions.toModelOutput(output) : output;
199
- const tool = resolvedOptions.resumeSubAgent
200
- ? toolBuilder
201
- .suspend(delegateSubAgentSuspendSchema)
202
- .resume(delegateSubAgentResumeSchema)
106
+ if (resolvedOptions.resumeSubAgent) {
107
+ return toolBuilder
108
+ .suspend(delegation_1.delegateSubAgentSuspendSchema)
109
+ .resume(delegation_1.delegateSubAgentResumeSchema)
203
110
  .handler(handler)
204
111
  .toModelOutput(toModelOutput)
205
- .build()
206
- : toolBuilder.handler(handler).toModelOutput(toModelOutput).build();
207
- return (0, sdk_owned_tool_1.withSdkOwnedBuiltInMetadata)({
208
- ...tool,
209
- ...(resolvedOptions.cancelSubAgent !== undefined
112
+ .build();
113
+ }
114
+ return toolBuilder.handler(handler).toModelOutput(toModelOutput).build();
115
+ }
116
+ function createDelegateCancellationHandler(options, childPathIndexes) {
117
+ if (options.cancelSubAgent === undefined)
118
+ return {};
119
+ return {
120
+ onCancellation: async (rawInput, ctx) => {
121
+ const parsedInput = delegation_1.delegateSubAgentInputSchema.safeParse(rawInput);
122
+ if (!parsedInput.success) {
123
+ throw new Error('Delegated child input is missing or invalid');
124
+ }
125
+ await (0, delegate_sub_agent_runner_1.cancelDelegatedSubAgent)(parsedInput.data, ctx, options, childPathIndexes);
126
+ },
127
+ };
128
+ }
129
+ function buildDelegateToolMetadata(resolvedOptions) {
130
+ return {
131
+ ...(resolvedOptions.name !== undefined ? { name: resolvedOptions.name } : {}),
132
+ ...(resolvedOptions.availableSubAgents !== undefined
133
+ ? { availableSubAgents: resolvedOptions.availableSubAgents }
134
+ : {}),
135
+ policy: resolvedOptions.policy,
136
+ ...(resolvedOptions.inlineSubAgentBlockedTools !== undefined
137
+ ? { inlineSubAgentBlockedTools: resolvedOptions.inlineSubAgentBlockedTools }
138
+ : {}),
139
+ ...(resolvedOptions.inlineSubAgentModelsByDifficulty !== undefined
210
140
  ? {
211
- onCancellation: async (rawInput, ctx) => {
212
- const parsedInput = delegateSubAgentInputSchema.safeParse(rawInput);
213
- if (!parsedInput.success) {
214
- throw new Error('Delegated child input is missing or invalid');
215
- }
216
- await cancelDelegatedSubAgent(parsedInput.data, ctx, resolvedOptions, childPathIndexes);
217
- },
141
+ inlineSubAgentModelsByDifficulty: resolvedOptions.inlineSubAgentModelsByDifficulty,
218
142
  }
219
143
  : {}),
220
- metadata: {
221
- ...tool.metadata,
222
- [exports.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY]: {
223
- ...(resolvedOptions.name !== undefined ? { name: resolvedOptions.name } : {}),
224
- ...(resolvedOptions.availableSubAgents !== undefined
225
- ? { availableSubAgents: resolvedOptions.availableSubAgents }
226
- : {}),
227
- policy: resolvedOptions.policy,
228
- ...(resolvedOptions.inlineSubAgentBlockedTools !== undefined
229
- ? { inlineSubAgentBlockedTools: resolvedOptions.inlineSubAgentBlockedTools }
230
- : {}),
231
- ...(resolvedOptions.inlineSubAgentModelsByDifficulty !== undefined
232
- ? {
233
- inlineSubAgentModelsByDifficulty: resolvedOptions.inlineSubAgentModelsByDifficulty,
234
- }
235
- : {}),
236
- ...(resolvedOptions.resolveInlineSubAgentProviderTools !== undefined
237
- ? {
238
- resolveInlineSubAgentProviderTools: resolvedOptions.resolveInlineSubAgentProviderTools,
239
- }
240
- : {}),
241
- ...(resolvedOptions.runSubAgent !== undefined
242
- ? { runSubAgent: resolvedOptions.runSubAgent }
243
- : {}),
244
- ...(resolvedOptions.resumeSubAgent !== undefined
245
- ? { resumeSubAgent: resolvedOptions.resumeSubAgent }
246
- : {}),
247
- ...(resolvedOptions.shouldRetrySubAgentResumeError !== undefined
248
- ? { shouldRetrySubAgentResumeError: resolvedOptions.shouldRetrySubAgentResumeError }
249
- : {}),
250
- ...(resolvedOptions.cancelSubAgent !== undefined
251
- ? { cancelSubAgent: resolvedOptions.cancelSubAgent }
252
- : {}),
253
- ...(resolvedOptions.systemInstruction !== undefined
254
- ? { systemInstruction: resolvedOptions.systemInstruction }
255
- : {}),
256
- ...(resolvedOptions.description !== undefined
257
- ? { description: resolvedOptions.description }
258
- : {}),
259
- ...(resolvedOptions.toModelOutput !== undefined
260
- ? { toModelOutput: resolvedOptions.toModelOutput }
261
- : {}),
262
- },
263
- },
264
- });
144
+ ...(resolvedOptions.resolveInlineSubAgentProviderTools !== undefined
145
+ ? {
146
+ resolveInlineSubAgentProviderTools: resolvedOptions.resolveInlineSubAgentProviderTools,
147
+ }
148
+ : {}),
149
+ ...(resolvedOptions.runSubAgent !== undefined
150
+ ? { runSubAgent: resolvedOptions.runSubAgent }
151
+ : {}),
152
+ ...(resolvedOptions.resumeSubAgent !== undefined
153
+ ? { resumeSubAgent: resolvedOptions.resumeSubAgent }
154
+ : {}),
155
+ ...(resolvedOptions.shouldRetrySubAgentResumeError !== undefined
156
+ ? { shouldRetrySubAgentResumeError: resolvedOptions.shouldRetrySubAgentResumeError }
157
+ : {}),
158
+ ...(resolvedOptions.cancelSubAgent !== undefined
159
+ ? { cancelSubAgent: resolvedOptions.cancelSubAgent }
160
+ : {}),
161
+ ...(resolvedOptions.systemInstruction !== undefined
162
+ ? { systemInstruction: resolvedOptions.systemInstruction }
163
+ : {}),
164
+ ...(resolvedOptions.description !== undefined
165
+ ? { description: resolvedOptions.description }
166
+ : {}),
167
+ ...(resolvedOptions.toModelOutput !== undefined
168
+ ? { toModelOutput: resolvedOptions.toModelOutput }
169
+ : {}),
170
+ };
265
171
  }
266
172
  function getInlineDelegateSubAgentToolOptions(tool) {
267
- const value = tool.metadata?.[exports.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY];
173
+ const value = tool.metadata?.[delegation_1.INLINE_DELEGATE_SUB_AGENT_TOOL_METADATA_KEY];
268
174
  if (typeof value !== 'object' || value === null)
269
175
  return undefined;
270
176
  return value;
@@ -296,303 +202,4 @@ function formatDelegationPolicyInstructions(policy, toolName) {
296
202
  ].join('\n'),
297
203
  ];
298
204
  }
299
- async function handleDelegateSubAgent(input, ctx, options, childPathIndexes) {
300
- let taskPath;
301
- let request;
302
- let startedAt;
303
- try {
304
- if (options.resumeSubAgent !== undefined &&
305
- isInterruptibleToolContext(ctx) &&
306
- ctx.continuation !== undefined) {
307
- const restored = restoreDelegateRequest(input, ctx, ctx.continuation, options.policy, childPathIndexes);
308
- const { checkpoint } = restored;
309
- taskPath = checkpoint.taskPath;
310
- request = restored.request;
311
- startedAt = Date.now();
312
- emitSubAgentStarted(ctx, request, startedAt);
313
- let output;
314
- try {
315
- output = await options.resumeSubAgent({
316
- ...request,
317
- ...getChildCheckpointTarget(checkpoint),
318
- resumeData: ctx.resumeData,
319
- }, createRunnerHelpers(ctx, request, options.name));
320
- }
321
- catch (error) {
322
- if (ctx.abortSignal?.aborted || (0, abort_1.isAbortError)(error))
323
- throw error;
324
- if (options.shouldRetrySubAgentResumeError?.(error) === false)
325
- throw error;
326
- return await ctx.suspend(ctx.suspendPayload);
327
- }
328
- emitSubAgentCompleted(ctx, request, output, startedAt);
329
- if (output.status === 'suspended') {
330
- return await cascadeChildSuspension(ctx, request, output);
331
- }
332
- return output;
333
- }
334
- const childPathIndexKey = getChildPathIndexKey(ctx);
335
- const childPathIndex = childPathIndexes.get(childPathIndexKey) ?? 0;
336
- taskPath = (0, sub_agent_task_path_1.createChildSubAgentTaskPath)(input.taskName, childPathIndex);
337
- childPathIndexes.set(childPathIndexKey, childPathIndex + 1);
338
- request = createDelegateSubAgentRequest(input, ctx, taskPath, childPathIndex, options.policy);
339
- startedAt = Date.now();
340
- emitSubAgentStarted(ctx, request, startedAt);
341
- const toolName = options.name ?? exports.DELEGATE_SUB_AGENT_TOOL_NAME;
342
- if (!options.runSubAgent) {
343
- throw new Error(`${toolName} was registered without a runSubAgent callback, and no host runner was provided. Register it on an Agent (for inline delegation) or pass runSubAgent.`);
344
- }
345
- const output = await options.runSubAgent(request, createRunnerHelpers(ctx, request, options.name));
346
- emitSubAgentCompleted(ctx, request, output, startedAt);
347
- if (output.status === 'suspended' &&
348
- options.resumeSubAgent !== undefined &&
349
- isInterruptibleToolContext(ctx)) {
350
- return await cascadeChildSuspension(ctx, request, output);
351
- }
352
- return output;
353
- }
354
- catch (error) {
355
- const aborted = ctx.abortSignal ? ctx.abortSignal.aborted : (0, abort_1.isAbortError)(error);
356
- const output = {
357
- status: aborted ? 'cancelled' : 'failed',
358
- ...(taskPath !== undefined ? { taskPath } : {}),
359
- answer: '',
360
- ...(aborted ? {} : { error: stringifyUnknown(error) }),
361
- };
362
- if (request !== undefined && startedAt !== undefined) {
363
- emitSubAgentCompleted(ctx, request, output, startedAt);
364
- }
365
- if (aborted)
366
- throw error;
367
- return output;
368
- }
369
- }
370
- function createDelegateSubAgentRequest(input, ctx, taskPath, childCount, policy) {
371
- return {
372
- ...input,
373
- taskPath,
374
- childCount,
375
- ...(ctx.runId !== undefined ? { parentRunId: ctx.runId } : {}),
376
- ...(ctx.persistence?.threadId !== undefined
377
- ? { parentThreadId: ctx.persistence.threadId }
378
- : {}),
379
- ...(ctx.persistence?.resourceId !== undefined
380
- ? { parentResourceId: ctx.persistence.resourceId }
381
- : {}),
382
- ...(ctx.persistence?.hostMetadata !== undefined
383
- ? { parentHostMetadata: ctx.persistence.hostMetadata }
384
- : {}),
385
- ...(ctx.abortSignal !== undefined ? { parentAbortSignal: ctx.abortSignal } : {}),
386
- ...(ctx.toolCallId !== undefined ? { parentToolCallId: ctx.toolCallId } : {}),
387
- ...(ctx.executionCounter !== undefined
388
- ? { parentExecutionCounter: (0, execution_counter_1.withoutMessageCount)(ctx.executionCounter) }
389
- : {}),
390
- ...(ctx.parentTelemetry !== undefined ? { parentTelemetry: ctx.parentTelemetry } : {}),
391
- ...(policy !== undefined ? { policy } : {}),
392
- };
393
- }
394
- function isJsonSchemaObject(value) {
395
- return (0, is_record_1.isRecord)(value);
396
- }
397
- async function cancelDelegatedSubAgent(input, ctx, options, childPathIndexes) {
398
- if (options.cancelSubAgent === undefined || ctx.continuation === undefined)
399
- return;
400
- const { checkpoint, request } = restoreDelegateRequest(input, ctx, ctx.continuation, options.policy, childPathIndexes);
401
- await options.cancelSubAgent({
402
- ...request,
403
- ...getChildCheckpointTarget(checkpoint),
404
- reason: ctx.cancellation.message,
405
- }, createRunnerHelpers(ctx, request, options.name));
406
- }
407
- function restoreDelegateRequest(input, ctx, continuation, policy, childPathIndexes) {
408
- const checkpoint = parseDelegateSubAgentContinuation(continuation);
409
- if (!checkpoint) {
410
- throw new Error('Delegated child checkpoint metadata is missing or invalid');
411
- }
412
- if (checkpoint.subAgentId !== input.subAgentId) {
413
- throw new Error('Delegated child checkpoint does not match the selected sub-agent');
414
- }
415
- const { taskPath } = checkpoint;
416
- (0, sub_agent_task_path_1.assertSubAgentTaskPath)(taskPath);
417
- const key = getChildPathIndexKey(ctx);
418
- childPathIndexes.set(key, Math.max(childPathIndexes.get(key) ?? 0, checkpoint.childCount + 1));
419
- const request = createDelegateSubAgentRequest(input, ctx, taskPath, checkpoint.childCount, policy);
420
- return { checkpoint: { ...checkpoint, taskPath }, request };
421
- }
422
- function getChildCheckpointTarget(checkpoint) {
423
- return {
424
- childRunId: checkpoint.runId,
425
- childToolCallId: checkpoint.toolCallId,
426
- ...(checkpoint.threadId !== undefined ? { childThreadId: checkpoint.threadId } : {}),
427
- ...(checkpoint.resumeContext !== undefined ? { resumeContext: checkpoint.resumeContext } : {}),
428
- };
429
- }
430
- function createRunnerHelpers(ctx, request, configuredToolName) {
431
- const toolName = configuredToolName ?? exports.DELEGATE_SUB_AGENT_TOOL_NAME;
432
- return {
433
- runInlineSubAgent: () => {
434
- throw new Error(`${toolName} host runner does not support inline delegation without helpers.runInlineSubAgent from an Agent build.`);
435
- },
436
- emitChunk: createEmitChunkHelper(ctx, request),
437
- };
438
- }
439
- function isInterruptibleToolContext(ctx) {
440
- return 'suspend' in ctx;
441
- }
442
- async function cascadeChildSuspension(ctx, request, output) {
443
- const suspension = output.pendingSuspend?.[0];
444
- if (!suspension || !isJsonSchemaObject(suspension.resumeSchema)) {
445
- throw new Error(exports.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE);
446
- }
447
- return await ctx.suspend(suspension.suspendPayload, {
448
- resumeSchema: suspension.resumeSchema,
449
- continuation: {
450
- runId: suspension.runId,
451
- toolCallId: suspension.toolCallId,
452
- taskPath: request.taskPath,
453
- subAgentId: request.subAgentId,
454
- childCount: request.childCount,
455
- ...(output.threadId !== undefined ? { threadId: output.threadId } : {}),
456
- ...(output.resumeContext !== undefined ? { resumeContext: output.resumeContext } : {}),
457
- },
458
- });
459
- }
460
- function emitSubAgentStarted(ctx, request, startedAt) {
461
- ctx.emitEvent?.({
462
- type: "subagent_started",
463
- ...subAgentLifecycleBase(request),
464
- startedAt,
465
- });
466
- }
467
- function emitSubAgentCompleted(ctx, request, output, startedAt) {
468
- const finishedAt = Date.now();
469
- ctx.emitEvent?.({
470
- type: "subagent_completed",
471
- ...subAgentLifecycleBase(request),
472
- status: output.status,
473
- startedAt,
474
- finishedAt,
475
- durationMs: finishedAt - startedAt,
476
- ...(output.runId !== undefined ? { runId: output.runId } : {}),
477
- ...(output.threadId !== undefined ? { threadId: output.threadId } : {}),
478
- ...(output.usage !== undefined ? { usage: output.usage } : {}),
479
- ...(output.finishReason !== undefined ? { finishReason: output.finishReason } : {}),
480
- ...(output.model !== undefined ? { model: output.model } : {}),
481
- ...(output.error !== undefined ? { error: output.error } : {}),
482
- });
483
- }
484
- function subAgentLifecycleBase(request) {
485
- return {
486
- taskName: request.taskName,
487
- taskPath: request.taskPath,
488
- ...(request.parentRunId !== undefined ? { parentRunId: request.parentRunId } : {}),
489
- ...(request.parentToolCallId !== undefined
490
- ? { parentToolCallId: request.parentToolCallId }
491
- : {}),
492
- ...(request.subAgentId !== undefined ? { subAgentId: request.subAgentId } : {}),
493
- };
494
- }
495
- function getChildPathIndexKey(ctx) {
496
- return ctx.runId ?? ctx.persistence?.threadId ?? ctx.persistence?.resourceId ?? 'adhoc';
497
- }
498
- function stringifyUnknown(value) {
499
- if (value instanceof Error)
500
- return value.message;
501
- if (typeof value === 'string')
502
- return value;
503
- if (typeof value === 'number' || typeof value === 'boolean' || value === null) {
504
- return String(value);
505
- }
506
- try {
507
- return JSON.stringify(value);
508
- }
509
- catch {
510
- return 'Unknown error';
511
- }
512
- }
513
- function renderDelegateSubAgentPrompt(request) {
514
- const sections = [
515
- 'You are a focused subagent working on a specific delegated task.',
516
- `YOUR TASK:\n${request.goal}`,
517
- ];
518
- if (request.context) {
519
- sections.push(`CONTEXT:\n${request.context}`);
520
- }
521
- if (request.expectedOutput) {
522
- sections.push(`EXPECTED OUTPUT:\n${request.expectedOutput}`);
523
- }
524
- sections.push([
525
- 'Complete this task using the tools available to you. When finished, provide a clear, concise summary of:',
526
- '- What you did',
527
- '- What you found or accomplished',
528
- '- Important outputs, decisions, or evidence',
529
- '- Any issues, assumptions, or limitations',
530
- '',
531
- 'If the information above is insufficient, do your best with explicitly stated assumptions and note what was missing, rather than stopping to ask.',
532
- '',
533
- 'Be thorough but concise -- your response is returned to the parent agent as a summary.',
534
- ].join('\n'));
535
- return sections.join('\n\n');
536
- }
537
- function resolveDelegateSubAgentStatus(result) {
538
- if (result.finishReason === 'error' || result.error !== undefined) {
539
- return result.getState().status === 'cancelled' ? 'cancelled' : 'failed';
540
- }
541
- if (result.pendingSuspend !== undefined && result.pendingSuspend.length > 0) {
542
- return 'suspended';
543
- }
544
- return 'completed';
545
- }
546
- function failedDelegatedChildSuspendOutput(taskPath, model) {
547
- return {
548
- status: 'failed',
549
- taskPath,
550
- answer: '',
551
- error: exports.DELEGATED_CHILD_SUSPEND_UNSUPPORTED_MESSAGE,
552
- ...(model !== undefined ? { model } : {}),
553
- };
554
- }
555
- function generateResultToDelegateSubAgentOutput(taskPath, result, threadId) {
556
- const status = resolveDelegateSubAgentStatus(result);
557
- return {
558
- status,
559
- taskPath,
560
- runId: result.runId,
561
- ...(threadId !== undefined ? { threadId } : {}),
562
- ...(result.model !== undefined ? { model: result.model } : {}),
563
- answer: lastText(result.messages),
564
- ...(result.structuredOutput !== undefined ? { structuredOutput: result.structuredOutput } : {}),
565
- ...(result.usage !== undefined
566
- ? {
567
- usage: {
568
- promptTokens: result.usage.promptTokens,
569
- completionTokens: result.usage.completionTokens,
570
- totalTokens: result.usage.totalTokens,
571
- ...(result.usage.cost !== undefined ? { cost: result.usage.cost } : {}),
572
- },
573
- }
574
- : {}),
575
- ...(result.finishReason !== undefined ? { finishReason: result.finishReason } : {}),
576
- ...(result.error !== undefined ? { error: stringifyUnknown(result.error) } : {}),
577
- ...(status === 'suspended' && result.pendingSuspend !== undefined
578
- ? { pendingSuspend: result.pendingSuspend }
579
- : {}),
580
- };
581
- }
582
- function lastText(messages) {
583
- const llmMessages = (0, message_1.filterLlmMessages)(messages);
584
- for (let i = llmMessages.length - 1; i >= 0; i--) {
585
- const message = llmMessages[i];
586
- if (!message)
587
- continue;
588
- const text = message.content
589
- .filter((content) => content.type === 'text')
590
- .map((content) => content.text)
591
- .join('\n')
592
- .trim();
593
- if (text)
594
- return text;
595
- }
596
- return '';
597
- }
598
205
  //# sourceMappingURL=delegate-sub-agent-tool.js.map