@n8n/agents 0.6.0 → 0.8.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (148) hide show
  1. package/dist/build.tsbuildinfo +1 -1
  2. package/dist/index.d.ts +18 -11
  3. package/dist/index.js +37 -10
  4. package/dist/index.js.map +1 -1
  5. package/dist/integrations/langsmith.d.ts +2 -0
  6. package/dist/integrations/langsmith.js +117 -2
  7. package/dist/integrations/langsmith.js.map +1 -1
  8. package/dist/runtime/agent-runtime.d.ts +30 -19
  9. package/dist/runtime/agent-runtime.js +616 -280
  10. package/dist/runtime/agent-runtime.js.map +1 -1
  11. package/dist/runtime/background-task-tracker.d.ts +6 -0
  12. package/dist/runtime/background-task-tracker.js +26 -0
  13. package/dist/runtime/background-task-tracker.js.map +1 -0
  14. package/dist/runtime/deferred-tool-manager.d.ts +28 -0
  15. package/dist/runtime/deferred-tool-manager.js +205 -0
  16. package/dist/runtime/deferred-tool-manager.js.map +1 -0
  17. package/dist/runtime/event-bus.d.ts +1 -0
  18. package/dist/runtime/event-bus.js +3 -0
  19. package/dist/runtime/event-bus.js.map +1 -1
  20. package/dist/runtime/json-value.d.ts +2 -0
  21. package/dist/runtime/json-value.js +43 -0
  22. package/dist/runtime/json-value.js.map +1 -0
  23. package/dist/runtime/memory-store.d.ts +34 -11
  24. package/dist/runtime/memory-store.js +210 -8
  25. package/dist/runtime/memory-store.js.map +1 -1
  26. package/dist/runtime/message-list.d.ts +6 -7
  27. package/dist/runtime/message-list.js +50 -6
  28. package/dist/runtime/message-list.js.map +1 -1
  29. package/dist/runtime/messages.d.ts +0 -2
  30. package/dist/runtime/messages.js +127 -101
  31. package/dist/runtime/messages.js.map +1 -1
  32. package/dist/runtime/model-factory.js +117 -34
  33. package/dist/runtime/model-factory.js.map +1 -1
  34. package/dist/runtime/observation-log-defaults.d.ts +20 -0
  35. package/dist/runtime/observation-log-defaults.js +523 -0
  36. package/dist/runtime/observation-log-defaults.js.map +1 -0
  37. package/dist/runtime/observation-log-observer.d.ts +64 -0
  38. package/dist/runtime/observation-log-observer.js +235 -0
  39. package/dist/runtime/observation-log-observer.js.map +1 -0
  40. package/dist/runtime/observation-log-reflector.d.ts +36 -0
  41. package/dist/runtime/observation-log-reflector.js +292 -0
  42. package/dist/runtime/observation-log-reflector.js.map +1 -0
  43. package/dist/runtime/observation-log-renderer.d.ts +6 -0
  44. package/dist/runtime/observation-log-renderer.js +73 -0
  45. package/dist/runtime/observation-log-renderer.js.map +1 -0
  46. package/dist/runtime/observation-log-store.d.ts +3 -0
  47. package/dist/runtime/observation-log-store.js +26 -0
  48. package/dist/runtime/observation-log-store.js.map +1 -0
  49. package/dist/runtime/provider-credentials.d.ts +167 -0
  50. package/dist/runtime/provider-credentials.js +34 -0
  51. package/dist/runtime/provider-credentials.js.map +1 -0
  52. package/dist/runtime/runtime-helpers.d.ts +3 -4
  53. package/dist/runtime/runtime-helpers.js +6 -32
  54. package/dist/runtime/runtime-helpers.js.map +1 -1
  55. package/dist/runtime/scoped-memory-task-runner.d.ts +79 -0
  56. package/dist/runtime/scoped-memory-task-runner.js +134 -0
  57. package/dist/runtime/scoped-memory-task-runner.js.map +1 -0
  58. package/dist/runtime/stream.js +25 -43
  59. package/dist/runtime/stream.js.map +1 -1
  60. package/dist/runtime/strip-orphaned-tool-messages.js +1 -25
  61. package/dist/runtime/strip-orphaned-tool-messages.js.map +1 -1
  62. package/dist/runtime/title-generation.d.ts +12 -3
  63. package/dist/runtime/title-generation.js +72 -3
  64. package/dist/runtime/title-generation.js.map +1 -1
  65. package/dist/runtime/tool-adapter.d.ts +1 -1
  66. package/dist/runtime/tool-adapter.js +3 -2
  67. package/dist/runtime/tool-adapter.js.map +1 -1
  68. package/dist/sdk/agent.d.ts +35 -22
  69. package/dist/sdk/agent.js +106 -331
  70. package/dist/sdk/agent.js.map +1 -1
  71. package/dist/sdk/catalog.d.ts +1 -0
  72. package/dist/sdk/catalog.js +1 -0
  73. package/dist/sdk/catalog.js.map +1 -1
  74. package/dist/sdk/eval.d.ts +0 -3
  75. package/dist/sdk/eval.js +4 -9
  76. package/dist/sdk/eval.js.map +1 -1
  77. package/dist/sdk/memory.d.ts +12 -12
  78. package/dist/sdk/memory.js +71 -51
  79. package/dist/sdk/memory.js.map +1 -1
  80. package/dist/sdk/provider-capabilities.js +4 -2
  81. package/dist/sdk/provider-capabilities.js.map +1 -1
  82. package/dist/sdk/provider-tools.d.ts +17 -2
  83. package/dist/sdk/provider-tools.js +19 -0
  84. package/dist/sdk/provider-tools.js.map +1 -1
  85. package/dist/sdk/telemetry.d.ts +2 -0
  86. package/dist/sdk/telemetry.js +6 -0
  87. package/dist/sdk/telemetry.js.map +1 -1
  88. package/dist/sdk/tool.d.ts +17 -10
  89. package/dist/sdk/tool.js +34 -0
  90. package/dist/sdk/tool.js.map +1 -1
  91. package/dist/sdk/verify.js +1 -4
  92. package/dist/sdk/verify.js.map +1 -1
  93. package/dist/storage/base-memory.d.ts +54 -0
  94. package/dist/storage/base-memory.js +48 -0
  95. package/dist/storage/base-memory.js.map +1 -0
  96. package/dist/types/index.d.ts +6 -3
  97. package/dist/types/index.js +7 -1
  98. package/dist/types/index.js.map +1 -1
  99. package/dist/types/runtime/event.d.ts +4 -9
  100. package/dist/types/runtime/event.js.map +1 -1
  101. package/dist/types/sdk/agent-builder.d.ts +5 -3
  102. package/dist/types/sdk/agent.d.ts +70 -27
  103. package/dist/types/sdk/credential-provider.d.ts +2 -3
  104. package/dist/types/sdk/memory.d.ts +33 -20
  105. package/dist/types/sdk/message.d.ts +11 -10
  106. package/dist/types/sdk/observation-log.d.ts +99 -0
  107. package/dist/types/sdk/observation-log.js +17 -0
  108. package/dist/types/sdk/observation-log.js.map +1 -0
  109. package/dist/types/sdk/observation.d.ts +9 -0
  110. package/dist/types/sdk/{schema.js → observation.js} +1 -1
  111. package/dist/types/sdk/observation.js.map +1 -0
  112. package/dist/types/sdk/provider.d.ts +5 -2
  113. package/dist/types/sdk/tool-descriptor.d.ts +13 -0
  114. package/dist/types/sdk/tool-descriptor.js +3 -0
  115. package/dist/types/sdk/tool-descriptor.js.map +1 -0
  116. package/dist/types/sdk/tool.d.ts +8 -3
  117. package/dist/types/telemetry.d.ts +1 -0
  118. package/dist/utils/parse.d.ts +10 -0
  119. package/dist/utils/parse.js +26 -0
  120. package/dist/utils/parse.js.map +1 -0
  121. package/dist/utils/zod.d.ts +1 -1
  122. package/dist/utils/zod.js.map +1 -1
  123. package/dist/workspace/tools/batch-str-replace-file.d.ts +3 -0
  124. package/dist/workspace/tools/batch-str-replace-file.js +67 -0
  125. package/dist/workspace/tools/batch-str-replace-file.js.map +1 -0
  126. package/dist/workspace/tools/str-replace-file.d.ts +3 -0
  127. package/dist/workspace/tools/str-replace-file.js +51 -0
  128. package/dist/workspace/tools/str-replace-file.js.map +1 -0
  129. package/dist/workspace/tools/workspace-tools.js +4 -0
  130. package/dist/workspace/tools/workspace-tools.js.map +1 -1
  131. package/package.json +16 -11
  132. package/dist/codegen/generate-agent-code.d.ts +0 -2
  133. package/dist/codegen/generate-agent-code.js +0 -197
  134. package/dist/codegen/generate-agent-code.js.map +0 -1
  135. package/dist/runtime/working-memory.d.ts +0 -14
  136. package/dist/runtime/working-memory.js +0 -69
  137. package/dist/runtime/working-memory.js.map +0 -1
  138. package/dist/sdk/from-schema.d.ts +0 -15
  139. package/dist/sdk/from-schema.js +0 -218
  140. package/dist/sdk/from-schema.js.map +0 -1
  141. package/dist/storage/postgres-memory.d.ts +0 -79
  142. package/dist/storage/postgres-memory.js +0 -410
  143. package/dist/storage/postgres-memory.js.map +0 -1
  144. package/dist/storage/sqlite-memory.d.ts +0 -60
  145. package/dist/storage/sqlite-memory.js +0 -348
  146. package/dist/storage/sqlite-memory.js.map +0 -1
  147. package/dist/types/sdk/schema.d.ts +0 -99
  148. package/dist/types/sdk/schema.js.map +0 -1
package/dist/sdk/agent.js CHANGED
@@ -2,21 +2,18 @@
2
2
  Object.defineProperty(exports, "__esModule", { value: true });
3
3
  exports.Agent = void 0;
4
4
  const zod_1 = require("zod");
5
- const agent_runtime_1 = require("../runtime/agent-runtime");
6
- const event_bus_1 = require("../runtime/event-bus");
7
- const memory_store_1 = require("../runtime/memory-store");
8
- const run_state_1 = require("../runtime/run-state");
9
- const tool_adapter_1 = require("../runtime/tool-adapter");
10
- const catalog_1 = require("./catalog");
11
- const from_schema_1 = require("./from-schema");
12
5
  const memory_1 = require("./memory");
13
6
  const telemetry_1 = require("./telemetry");
14
7
  const tool_1 = require("./tool");
15
- const zod_2 = require("../utils/zod");
8
+ const agent_runtime_1 = require("../runtime/agent-runtime");
9
+ const deferred_tool_manager_1 = require("../runtime/deferred-tool-manager");
10
+ const event_bus_1 = require("../runtime/event-bus");
11
+ const tool_adapter_1 = require("../runtime/tool-adapter");
16
12
  const DEFAULT_LAST_MESSAGES = 10;
17
13
  class Agent {
18
14
  constructor(name) {
19
15
  this.tools = [];
16
+ this.deferredTools = [];
20
17
  this.providerTools = [];
21
18
  this.inputGuardrails = [];
22
19
  this.outputGuardrails = [];
@@ -24,15 +21,9 @@ class Agent {
24
21
  this.middlewares = [];
25
22
  this.requireToolApprovalValue = false;
26
23
  this.mcpClients = [];
27
- this.agentHandlers = new Map();
28
- this.activeEventBuses = new Set();
24
+ this.eventBus = new event_bus_1.AgentEventBus();
29
25
  this.name = name;
30
26
  }
31
- static async fromSchema(schema, name, options) {
32
- const agent = new Agent(name);
33
- await (0, from_schema_1.fromSchema)(agent, schema, options);
34
- return agent;
35
- }
36
27
  hasCheckpointStorage() {
37
28
  return this.checkpointStore !== undefined;
38
29
  }
@@ -41,12 +32,10 @@ class Agent {
41
32
  }
42
33
  model(providerOrIdOrConfig, modelName) {
43
34
  if (typeof providerOrIdOrConfig === 'string') {
44
- this.modelId = modelName ? `${providerOrIdOrConfig}/${modelName}` : providerOrIdOrConfig;
45
- this.modelConfigObj = undefined;
35
+ this.modelConfig = modelName ? `${providerOrIdOrConfig}/${modelName}` : providerOrIdOrConfig;
46
36
  }
47
37
  else {
48
- this.modelConfigObj = providerOrIdOrConfig;
49
- this.modelId = undefined;
38
+ this.modelConfig = providerOrIdOrConfig;
50
39
  }
51
40
  return this;
52
41
  }
@@ -66,6 +55,17 @@ class Agent {
66
55
  this.tools.push(built);
67
56
  return this;
68
57
  }
58
+ deferredTool(t, options) {
59
+ const tools = Array.isArray(t) ? t : [t];
60
+ for (const tool of tools) {
61
+ const built = 'build' in tool ? tool.build() : tool;
62
+ this.deferredTools.push(built);
63
+ }
64
+ if (options?.search?.topK !== undefined) {
65
+ this.deferredToolSearchTopK = options.search.topK;
66
+ }
67
+ return this;
68
+ }
69
69
  providerTool(builtProviderTool) {
70
70
  this.providerTools.push(builtProviderTool);
71
71
  return this;
@@ -78,7 +78,7 @@ class Agent {
78
78
  this.memoryConfig = m.build();
79
79
  }
80
80
  else if ('memory' in m && 'lastMessages' in m) {
81
- this.memoryConfig = m;
81
+ this.memoryConfig = (0, memory_1.normalizeMemoryConfig)(m);
82
82
  }
83
83
  else if (typeof m === 'object' &&
84
84
  m !== null &&
@@ -88,7 +88,7 @@ class Agent {
88
88
  }
89
89
  else {
90
90
  throw new Error('Invalid memory configuration. Use: new Memory().lastMessages(N) for in-process memory, ' +
91
- 'or new Memory().storage(new SqliteMemory(path)).lastMessages(N) for persistent storage. ' +
91
+ 'or new Memory().storage(myBuiltMemoryBackend).lastMessages(N) for a persistent backend. ' +
92
92
  'See the Memory class documentation for all options.');
93
93
  }
94
94
  return this;
@@ -114,20 +114,6 @@ class Agent {
114
114
  this.checkpointStore = storage;
115
115
  return this;
116
116
  }
117
- credential(name) {
118
- this.credentialName = name;
119
- return this;
120
- }
121
- credentialProvider(provider) {
122
- this.credProvider = provider;
123
- return this;
124
- }
125
- get declaredCredential() {
126
- return this.credentialName;
127
- }
128
- set resolvedApiKey(key) {
129
- this.resolvedKey = key;
130
- }
131
117
  structuredOutput(schema) {
132
118
  this.outputSchema = schema;
133
119
  return this;
@@ -173,21 +159,10 @@ class Agent {
173
159
  return [...this.agentEvals];
174
160
  }
175
161
  on(event, handler) {
176
- let set = this.agentHandlers.get(event);
177
- if (!set) {
178
- set = new Set();
179
- this.agentHandlers.set(event, set);
180
- }
181
- set.add(handler);
162
+ this.eventBus.on(event, handler);
182
163
  }
183
164
  off(event, handler) {
184
- const set = this.agentHandlers.get(event);
185
- if (!set)
186
- return;
187
- set.delete(handler);
188
- if (set.size === 0) {
189
- this.agentHandlers.delete(event);
190
- }
165
+ this.eventBus.off(event, handler);
191
166
  }
192
167
  asTool(description) {
193
168
  const agent = this;
@@ -224,220 +199,72 @@ class Agent {
224
199
  });
225
200
  return tool.build();
226
201
  }
227
- describe() {
202
+ get snapshot() {
228
203
  let model;
229
- if (this.modelConfigObj) {
230
- model = { provider: null, name: null, raw: 'object' };
231
- }
232
- else if (this.modelId) {
233
- const slashIdx = this.modelId.indexOf('/');
204
+ const rawModelId = typeof this.modelConfig === 'string'
205
+ ? this.modelConfig
206
+ : this.modelConfig && typeof this.modelConfig === 'object' && 'id' in this.modelConfig
207
+ ? this.modelConfig.id
208
+ : undefined;
209
+ if (rawModelId) {
210
+ const slashIdx = rawModelId.indexOf('/');
234
211
  if (slashIdx === -1) {
235
- model = { provider: null, name: this.modelId };
212
+ model = { provider: null, name: rawModelId };
236
213
  }
237
214
  else {
238
215
  model = {
239
- provider: this.modelId.slice(0, slashIdx),
240
- name: this.modelId.slice(slashIdx + 1),
216
+ provider: rawModelId.slice(0, slashIdx),
217
+ name: rawModelId.slice(slashIdx + 1),
241
218
  };
242
219
  }
243
220
  }
244
221
  else {
245
222
  model = { provider: null, name: null };
246
223
  }
247
- const toolSchemas = this.tools.map((tool) => {
248
- const isWorkflow = '__workflowTool' in tool && Boolean(tool.__workflowTool);
249
- return {
250
- name: tool.name,
251
- description: tool.description,
252
- type: isWorkflow ? 'workflow' : 'custom',
253
- editable: !isWorkflow,
254
- inputSchemaSource: null,
255
- outputSchemaSource: null,
256
- handlerSource: tool.handler?.toString() ?? null,
257
- suspendSchemaSource: null,
258
- resumeSchemaSource: null,
259
- toMessageSource: null,
260
- requireApproval: tool.withDefaultApproval ?? false,
261
- needsApprovalFnSource: null,
262
- providerOptions: tool.providerOptions ?? null,
263
- inputSchema: (0, zod_2.zodToJsonSchema)(tool.inputSchema),
264
- outputSchema: (0, zod_2.zodToJsonSchema)(tool.outputSchema),
265
- hasSuspend: Boolean(tool.suspendSchema),
266
- hasResume: Boolean(tool.resumeSchema),
267
- hasToMessage: Boolean(tool.toMessage),
268
- };
269
- });
270
- const providerToolSchemas = this.providerTools.map((pt) => ({
271
- name: pt.name,
272
- source: '',
273
- }));
274
- const guardrails = [
275
- ...this.inputGuardrails.map((g) => ({
276
- name: g.name,
277
- guardType: g.guardType,
278
- strategy: g.strategy,
279
- position: 'input',
280
- config: g._config,
281
- source: '',
282
- })),
283
- ...this.outputGuardrails.map((g) => ({
284
- name: g.name,
285
- guardType: g.guardType,
286
- strategy: g.strategy,
287
- position: 'output',
288
- config: g._config,
289
- source: '',
290
- })),
291
- ];
292
- let mcp = null;
293
- if (this.mcpClients.length > 0) {
294
- mcp = [];
295
- for (const client of this.mcpClients) {
296
- for (const serverName of client.serverNames) {
297
- mcp.push({
298
- name: serverName,
299
- configSource: '',
300
- });
301
- }
302
- }
303
- }
304
- const telemetry = this.telemetryBuilder || this.telemetryConfig ? { source: '' } : null;
305
- const checkpoint = this.checkpointStore === 'memory' ? 'memory' : null;
306
- let memory = null;
307
- if (this.memoryConfig) {
308
- const mc = this.memoryConfig;
309
- let semanticRecall = null;
310
- if (mc.semanticRecall) {
311
- semanticRecall = {
312
- topK: mc.semanticRecall.topK,
313
- messageRange: mc.semanticRecall.messageRange
314
- ? {
315
- before: mc.semanticRecall.messageRange.before,
316
- after: mc.semanticRecall.messageRange.after,
317
- }
318
- : null,
319
- embedder: mc.semanticRecall.embedder ?? null,
320
- };
321
- }
322
- let workingMemory = null;
323
- if (mc.workingMemory) {
324
- workingMemory = {
325
- type: mc.workingMemory.structured ? 'structured' : 'freeform',
326
- ...(mc.workingMemory.schema
327
- ? { schema: (0, zod_2.zodToJsonSchema)(mc.workingMemory.schema) ?? undefined }
328
- : {}),
329
- ...(mc.workingMemory.template ? { template: mc.workingMemory.template } : {}),
330
- };
331
- }
332
- memory = {
333
- source: null,
334
- storage: mc.memory instanceof memory_store_1.InMemoryMemory ? 'memory' : 'custom',
335
- lastMessages: mc.lastMessages ?? null,
336
- semanticRecall,
337
- workingMemory,
338
- };
339
- }
340
- const evaluations = this.agentEvals.map((e) => ({
341
- name: e.name,
342
- description: e.description ?? null,
343
- type: e.evalType,
344
- modelId: e.modelId ?? null,
345
- hasCredential: e.credentialName !== null,
346
- credentialName: e.credentialName,
347
- handlerSource: null,
348
- }));
349
- const structuredOutput = {
350
- enabled: Boolean(this.outputSchema),
351
- schemaSource: null,
352
- };
353
- let thinking = null;
354
- if (this.thinkingConfig) {
355
- const provider = this.modelId?.split('/')[0];
356
- if (provider === 'anthropic') {
357
- thinking = {
358
- provider: 'anthropic',
359
- budgetTokens: 'budgetTokens' in this.thinkingConfig
360
- ? this.thinkingConfig.budgetTokens
361
- : undefined,
362
- };
363
- }
364
- else if (provider === 'openai') {
365
- thinking = {
366
- provider: 'openai',
367
- reasoningEffort: 'reasoningEffort' in this.thinkingConfig
368
- ? String(this.thinkingConfig.reasoningEffort)
369
- : undefined,
370
- };
371
- }
372
- }
373
224
  return {
225
+ name: this.name,
374
226
  model,
375
- credential: this.credentialName ?? null,
376
227
  instructions: this.instructionsText ?? null,
377
- description: null,
378
- tools: toolSchemas,
379
- providerTools: providerToolSchemas,
380
- memory,
381
- evaluations,
382
- guardrails,
383
- mcp,
384
- telemetry,
385
- checkpoint,
386
- config: {
387
- structuredOutput,
388
- thinking,
389
- toolCallConcurrency: this.concurrencyValue ?? null,
390
- requireToolApproval: this.requireToolApprovalValue,
391
- },
228
+ tools: this.tools.map((t) => ({ name: t.name, description: t.description })),
229
+ hasMemory: this.memoryConfig !== undefined,
230
+ hasObservationalMemory: this.memoryConfig?.observationalMemory !== undefined,
231
+ thinking: this.thinkingConfig ?? null,
232
+ toolCallConcurrency: this.concurrencyValue ?? null,
233
+ requireToolApproval: this.requireToolApprovalValue,
392
234
  };
393
235
  }
394
- abort() {
395
- for (const bus of this.activeEventBuses) {
396
- bus.abort();
236
+ getState() {
237
+ if (!this.runtime) {
238
+ return {
239
+ persistence: undefined,
240
+ status: 'idle',
241
+ messageList: { messages: [], historyIds: [], inputIds: [], responseIds: [] },
242
+ pendingToolCalls: {},
243
+ };
397
244
  }
245
+ return this.runtime.getState();
246
+ }
247
+ abort() {
248
+ this.eventBus.abort();
249
+ }
250
+ async close() {
251
+ if (this.runtime)
252
+ await this.runtime.dispose();
398
253
  }
399
254
  async generate(input, options) {
400
- const config = await this.ensureBuilt();
401
- const { runtime, bus } = this.createRuntime(config);
402
- try {
403
- return await runtime.generate(this.toMessages(input), options);
404
- }
405
- finally {
406
- this.cleanupBus(bus);
407
- }
255
+ const runtime = await this.ensureBuilt();
256
+ return await runtime.generate(this.toMessages(input), options);
408
257
  }
409
258
  async stream(input, options) {
410
- const config = await this.ensureBuilt();
411
- const { runtime, bus } = this.createRuntime(config);
412
- try {
413
- const result = await runtime.stream(this.toMessages(input), options);
414
- return { ...result, stream: this.trackStreamBus(result.stream, bus) };
415
- }
416
- catch (error) {
417
- this.cleanupBus(bus);
418
- throw error;
419
- }
259
+ const runtime = await this.ensureBuilt();
260
+ return await runtime.stream(this.toMessages(input), options);
420
261
  }
421
262
  async resume(method, data, options) {
422
- const config = await this.ensureBuilt();
263
+ const runtime = await this.ensureBuilt();
423
264
  if (method === 'generate') {
424
- const { runtime, bus } = this.createRuntime(config);
425
- try {
426
- return await runtime.resume('generate', data, options);
427
- }
428
- finally {
429
- this.cleanupBus(bus);
430
- }
431
- }
432
- const { runtime, bus } = this.createRuntime(config);
433
- try {
434
- const result = await runtime.resume('stream', data, options);
435
- return { ...result, stream: this.trackStreamBus(result.stream, bus) };
436
- }
437
- catch (error) {
438
- this.cleanupBus(bus);
439
- throw error;
265
+ return await runtime.resume('generate', data, options);
440
266
  }
267
+ return await runtime.resume('stream', data, options);
441
268
  }
442
269
  async approve(method, options) {
443
270
  if (method === 'generate') {
@@ -462,76 +289,32 @@ class Agent {
462
289
  }
463
290
  return await this.buildPromise;
464
291
  }
465
- createRuntime(config) {
466
- const bus = new event_bus_1.AgentEventBus();
467
- for (const [event, handlers] of this.agentHandlers) {
468
- for (const handler of handlers) {
469
- bus.on(event, handler);
470
- }
471
- }
472
- this.activeEventBuses.add(bus);
473
- const runtime = new agent_runtime_1.AgentRuntime({ ...config, eventBus: bus });
474
- return { runtime, bus };
475
- }
476
- trackStreamBus(stream, bus) {
477
- let cleanedUp = false;
478
- const cleanup = () => {
479
- if (!cleanedUp) {
480
- cleanedUp = true;
481
- this.cleanupBus(bus);
482
- }
483
- };
484
- const reader = stream.getReader();
485
- return new ReadableStream({
486
- async pull(controller) {
487
- try {
488
- const { done, value } = await reader.read();
489
- if (done) {
490
- controller.close();
491
- cleanup();
492
- }
493
- else {
494
- controller.enqueue(value);
495
- }
496
- }
497
- catch (error) {
498
- controller.error(error);
499
- cleanup();
500
- }
501
- },
502
- cancel() {
503
- reader.cancel().catch(() => { });
504
- cleanup();
505
- },
506
- });
507
- }
508
- cleanupBus(bus) {
509
- this.activeEventBuses.delete(bus);
510
- bus.dispose();
511
- }
512
292
  toMessages(input) {
513
293
  if (Array.isArray(input))
514
294
  return input;
515
295
  return [{ role: 'user', content: [{ type: 'text', text: input }] }];
516
296
  }
517
297
  async build() {
518
- const hasModel = this.modelId ?? this.modelConfigObj;
519
- if (!hasModel) {
298
+ if (!this.modelConfig) {
520
299
  throw new Error(`Agent "${this.name}" requires a model`);
521
300
  }
522
301
  if (!this.instructionsText) {
523
302
  throw new Error(`Agent "${this.name}" requires instructions`);
524
303
  }
525
304
  const finalTools = [...this.tools];
305
+ const configuredDeferredTools = [...this.deferredTools];
526
306
  if (this.workspaceInstance) {
527
307
  const wsTools = this.workspaceInstance.getTools();
528
308
  finalTools.push(...wsTools);
529
309
  }
530
310
  let finalStaticTools = finalTools;
311
+ let finalDeferredTools = configuredDeferredTools;
531
312
  if (this.requireToolApprovalValue) {
532
313
  finalStaticTools = finalTools.map((t) => t.suspendSchema ? t : (0, tool_1.wrapToolForApproval)(t, { requireApproval: true }));
314
+ finalDeferredTools = configuredDeferredTools.map((t) => t.suspendSchema ? t : (0, tool_1.wrapToolForApproval)(t, { requireApproval: true }));
533
315
  }
534
- const staticNeedsCheckpoint = finalStaticTools.some((t) => t.suspendSchema);
316
+ const staticNeedsCheckpoint = finalStaticTools.some((t) => t.suspendSchema) ||
317
+ finalDeferredTools.some((t) => t.suspendSchema);
535
318
  const mcpNeedsCheckpoint = (this.requireToolApprovalValue && this.mcpClients.length > 0) ||
536
319
  this.mcpClients.some((c) => c.declaresApproval());
537
320
  if ((staticNeedsCheckpoint || mcpNeedsCheckpoint) && !this.checkpointStore) {
@@ -545,38 +328,37 @@ class Agent {
545
328
  mcpTools = mcpTools.map((t) => t.suspendSchema ? t : (0, tool_1.wrapToolForApproval)(t, { requireApproval: true }));
546
329
  }
547
330
  const staticNames = new Set(finalStaticTools.map((t) => t.name));
548
- const collisions = mcpTools.filter((t) => staticNames.has(t.name)).map((t) => t.name);
331
+ const reservedDeferredToolNames = new Set([deferred_tool_manager_1.SEARCH_TOOLS_TOOL_NAME, deferred_tool_manager_1.LOAD_TOOL_TOOL_NAME]);
332
+ const deferredNames = new Set();
333
+ const deferredCollisions = [];
334
+ for (const tool of finalDeferredTools) {
335
+ if (staticNames.has(tool.name) ||
336
+ reservedDeferredToolNames.has(tool.name) ||
337
+ deferredNames.has(tool.name)) {
338
+ deferredCollisions.push(tool.name);
339
+ }
340
+ deferredNames.add(tool.name);
341
+ }
342
+ if (deferredCollisions.length > 0) {
343
+ throw new Error(`Deferred tool name collision — the following tool names resolve to duplicates or reserved tools: ${deferredCollisions.join(', ')}`);
344
+ }
345
+ const collisions = mcpTools
346
+ .filter((t) => staticNames.has(t.name) || deferredNames.has(t.name))
347
+ .map((t) => t.name);
549
348
  if (collisions.length > 0) {
550
349
  throw new Error(`MCP tool name collision — the following tool names resolve to duplicates: ${collisions.join(', ')}`);
551
350
  }
552
351
  const allTools = [...finalStaticTools, ...mcpTools];
553
- const allNeedCheckpoint = allTools.some((t) => t.suspendSchema);
352
+ const allNeedCheckpoint = allTools.some((t) => t.suspendSchema) || finalDeferredTools.some((t) => t.suspendSchema);
554
353
  if (allNeedCheckpoint && !this.checkpointStore) {
555
354
  throw new Error(`Agent "${this.name}" has tools requiring approval or suspend/resume but no checkpoint storage. ` +
556
355
  "Add .checkpoint('memory') for in-process storage, " +
557
356
  'or pass a persistent store (e.g. LibSQLStore, PgStore).');
558
357
  }
559
- if (this.credProvider && this.credentialName) {
560
- const resolved = await this.credProvider.resolve(this.credentialName);
561
- this.resolvedKey = resolved.apiKey;
562
- }
563
- let modelConfig;
564
- if (this.modelConfigObj) {
565
- if (this.resolvedKey &&
566
- typeof this.modelConfigObj === 'object' &&
567
- 'id' in this.modelConfigObj) {
568
- modelConfig = { ...this.modelConfigObj, apiKey: this.resolvedKey };
569
- }
570
- else {
571
- modelConfig = this.modelConfigObj;
572
- }
573
- }
574
- else if (this.resolvedKey) {
575
- modelConfig = { id: this.modelId, apiKey: this.resolvedKey };
576
- }
577
- else {
578
- modelConfig = this.modelId;
579
- }
358
+ const modelConfig = this.modelConfig;
359
+ const memoryConfig = this.memoryConfig
360
+ ? (0, memory_1.resolveMemoryConfigDefaults)(this.memoryConfig, { defaultModel: modelConfig })
361
+ : undefined;
580
362
  let instructions = this.instructionsText;
581
363
  if (this.workspaceInstance) {
582
364
  const wsInstructions = this.workspaceInstance.getInstructions();
@@ -584,38 +366,31 @@ class Agent {
584
366
  instructions = `${instructions}\n\n${wsInstructions}`;
585
367
  }
586
368
  }
587
- let modelCost;
588
- try {
589
- const modelId = typeof modelConfig === 'string'
590
- ? modelConfig
591
- : 'id' in modelConfig
592
- ? modelConfig.id
593
- : undefined;
594
- modelCost = modelId ? await (0, catalog_1.getModelCost)(modelId) : undefined;
595
- }
596
- catch {
597
- }
598
- const runState = new run_state_1.RunStateManager(this.checkpointStore);
599
- return {
369
+ this.runtime = new agent_runtime_1.AgentRuntime({
600
370
  name: this.name,
601
371
  model: modelConfig,
602
372
  instructions,
603
373
  tools: allTools.length > 0 ? allTools : undefined,
374
+ deferredTools: finalDeferredTools.length > 0 ? finalDeferredTools : undefined,
375
+ toolSearch: finalDeferredTools.length > 0 && this.deferredToolSearchTopK !== undefined
376
+ ? { topK: this.deferredToolSearchTopK }
377
+ : undefined,
604
378
  instructionProviderOptions: this.instructionProviderOpts,
605
379
  providerTools: this.providerTools.length > 0 ? this.providerTools : undefined,
606
- memory: this.memoryConfig?.memory,
607
- lastMessages: this.memoryConfig?.lastMessages,
608
- workingMemory: this.memoryConfig?.workingMemory,
609
- semanticRecall: this.memoryConfig?.semanticRecall,
380
+ memory: memoryConfig?.memory,
381
+ lastMessages: memoryConfig?.lastMessages,
382
+ observationLog: memoryConfig?.observationLog,
383
+ observationalMemory: memoryConfig?.observationalMemory,
384
+ semanticRecall: memoryConfig?.semanticRecall,
610
385
  structuredOutput: this.outputSchema,
611
386
  checkpointStorage: this.checkpointStore,
612
387
  thinking: this.thinkingConfig,
388
+ eventBus: this.eventBus,
613
389
  toolCallConcurrency: this.concurrencyValue,
614
- titleGeneration: this.memoryConfig?.titleGeneration,
390
+ titleGeneration: memoryConfig?.titleGeneration,
615
391
  telemetry: this.telemetryConfig ?? (await this.telemetryBuilder?.build()),
616
- modelCost,
617
- runState,
618
- };
392
+ });
393
+ return this.runtime;
619
394
  }
620
395
  }
621
396
  exports.Agent = Agent;