@deepagents/agent 0.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (57) hide show
  1. package/dist/index.d.ts +5 -0
  2. package/dist/index.d.ts.map +1 -0
  3. package/dist/index.js +916 -0
  4. package/dist/index.js.map +7 -0
  5. package/dist/lib/agent.d.ts +100 -0
  6. package/dist/lib/agent.d.ts.map +1 -0
  7. package/dist/lib/blog/deepagents.d.ts +12 -0
  8. package/dist/lib/blog/deepagents.d.ts.map +1 -0
  9. package/dist/lib/blog/docker.d.ts +4 -0
  10. package/dist/lib/blog/docker.d.ts.map +1 -0
  11. package/dist/lib/blog/mesh.d.ts +4 -0
  12. package/dist/lib/blog/mesh.d.ts.map +1 -0
  13. package/dist/lib/blog/package-star.d.ts +4 -0
  14. package/dist/lib/blog/package-star.d.ts.map +1 -0
  15. package/dist/lib/blog/research.d.ts +4 -0
  16. package/dist/lib/blog/research.d.ts.map +1 -0
  17. package/dist/lib/blog/star.d.ts +4 -0
  18. package/dist/lib/blog/star.d.ts.map +1 -0
  19. package/dist/lib/examples/animated_svg.d.ts +2 -0
  20. package/dist/lib/examples/animated_svg.d.ts.map +1 -0
  21. package/dist/lib/examples/finanicals_bot.d.ts +2 -0
  22. package/dist/lib/examples/finanicals_bot.d.ts.map +1 -0
  23. package/dist/lib/examples/plan_and_act_example.d.ts +2 -0
  24. package/dist/lib/examples/plan_and_act_example.d.ts.map +1 -0
  25. package/dist/lib/examples/planner.d.ts +15 -0
  26. package/dist/lib/examples/planner.d.ts.map +1 -0
  27. package/dist/lib/examples/research_bot.d.ts +2 -0
  28. package/dist/lib/examples/research_bot.d.ts.map +1 -0
  29. package/dist/lib/memory.d.ts +701 -0
  30. package/dist/lib/memory.d.ts.map +1 -0
  31. package/dist/lib/models.d.ts +7 -0
  32. package/dist/lib/models.d.ts.map +1 -0
  33. package/dist/lib/patterns/plan_and_act/plan_and_act.d.ts +56 -0
  34. package/dist/lib/patterns/plan_and_act/plan_and_act.d.ts.map +1 -0
  35. package/dist/lib/patterns/plan_and_execute/plan_and_execute.d.ts +3 -0
  36. package/dist/lib/patterns/plan_and_execute/plan_and_execute.d.ts.map +1 -0
  37. package/dist/lib/patterns/plan_and_execute/plan_and_execute_os.d.ts +2 -0
  38. package/dist/lib/patterns/plan_and_execute/plan_and_execute_os.d.ts.map +1 -0
  39. package/dist/lib/patterns/plan_and_execute/plan_and_execute_supervisor.d.ts +2 -0
  40. package/dist/lib/patterns/plan_and_execute/plan_and_execute_supervisor.d.ts.map +1 -0
  41. package/dist/lib/patterns/plan_and_execute/plan_and_execute_triage.d.ts +2 -0
  42. package/dist/lib/patterns/plan_and_execute/plan_and_execute_triage.d.ts.map +1 -0
  43. package/dist/lib/patterns/rewoo/rewoo.d.ts +64 -0
  44. package/dist/lib/patterns/rewoo/rewoo.d.ts.map +1 -0
  45. package/dist/lib/patterns/supervisor.d.ts +12 -0
  46. package/dist/lib/patterns/supervisor.d.ts.map +1 -0
  47. package/dist/lib/prompts.d.ts +3 -0
  48. package/dist/lib/prompts.d.ts.map +1 -0
  49. package/dist/lib/rag.d.ts +2 -0
  50. package/dist/lib/rag.d.ts.map +1 -0
  51. package/dist/lib/stream_utils.d.ts +26 -0
  52. package/dist/lib/stream_utils.d.ts.map +1 -0
  53. package/dist/lib/swarm.d.ts +23 -0
  54. package/dist/lib/swarm.d.ts.map +1 -0
  55. package/dist/lib/visualize.d.ts +32 -0
  56. package/dist/lib/visualize.d.ts.map +1 -0
  57. package/package.json +44 -0
package/dist/index.js ADDED
@@ -0,0 +1,916 @@
1
+ // packages/agent/src/lib/agent.ts
2
+ import {
3
+ Output as Output2,
4
+ dynamicTool,
5
+ generateText as generateText2,
6
+ jsonSchema,
7
+ stepCountIs as stepCountIs2,
8
+ tool
9
+ } from "ai";
10
+ import chalk2 from "chalk";
11
+ import { snakecase } from "stringcase";
12
+ import z from "zod";
13
+
14
+ // packages/agent/src/lib/prompts.ts
15
+ import dedent from "dedent";
16
+ var RECOMMENDED_PROMPT_PREFIX = [
17
+ `# System context`,
18
+ `You are part of a multi-agent system called the DeepAgents SDK, designed to make agent coordination and execution easy.`,
19
+ `Agents uses two primary abstraction: **Agents** and **Handoffs**.`,
20
+ `An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate.`,
21
+ `Handoffs are achieved by calling a handoff function, generally named \`transfer_to_<agent_name>\`.`,
22
+ `Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.`
23
+ // 'Do not pass context between agents. the agents already have the complete context without agent to agent communication.',
24
+ // From 4.1 beast mode
25
+ // `Please keep going until the user’s query is completely resolved, before ending your turn and yielding back to the user.`,
26
+ // `Your thinking should be thorough and so it's fine if it's very long. However, avoid unnecessary repetition and verbosity. You should be concise, but thorough.`,
27
+ // `You MUST iterate and keep going until the problem is solved.`,
28
+ // `You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.`,
29
+ // `Only terminate your turn when you are sure that the problem is solved and all items have been checked off. Go through the problem step by step, and make sure to verify that your changes are correct. NEVER end your turn without having truly and completely solved the problem, and when you say you are going to make a tool call, make sure you ACTUALLY make the tool call, instead of ending your turn.`,
30
+ // `Always tell the user what you are going to do before making a tool call with a single concise sentence. This will help them understand what you are doing and why.`,
31
+ // `If the user request is "resume" or "continue" or "try again", check the previous conversation history to see what the next incomplete step in the todo list is. Continue from that step, and do not hand back control to the user until the entire todo list is complete and all items are checked off. Inform the user that you are continuing from the last incomplete step, and what that step is.`,
32
+ // `Take your time and think through every step - remember to check your solution rigorously and watch out for boundary cases, especially with the changes you made. Use the sequential thinking tool if available. Your solution must be perfect. If not, continue working on it. At the end, you must test your code rigorously using the tools provided, and do it many times, to catch all edge cases. If it is not robust, iterate more and make it perfect. Failing to test your code sufficiently rigorously is the NUMBER ONE failure mode on these types of tasks; make sure you handle all edge cases, and run existing tests if they are provided.`,
33
+ // `You MUST plan extensively before each function call, and reflect extensively on the outcomes of the previous function calls. DO NOT do this entire process by making function calls only, as this can impair your ability to solve the problem and think insightfully.`,
34
+ // `You MUST keep working until the problem is completely solved, and all items in the todo list are checked off. Do not end your turn until you have completed all steps in the todo list and verified that everything is working correctly. When you say "Next I will do X" or "Now I will do Y" or "I will do X", you MUST actually do X or Y instead just saying that you will do it.`,
35
+ // `You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.`,
36
+ ].join("\n");
37
+ var SUPERVISOR_PROMPT_PREFIX = dedent`
38
+ # System Context
39
+ You are part of a multi-agent system called the DeepAgents SDK, designed to facilitate agent coordination and execution.
40
+
41
+ - The primary agent, known as the "Supervisor Agent," coordinates communication between specialized agents. The Supervisor Agent does not perform specialized tasks but acts as the central point for communication.
42
+ - Specialized agents must transfer control back to the Supervisor Agent upon completing their tasks.
43
+
44
+ **Core Directives:**
45
+ - Begin with a concise checklist (3-7 bullets) of what you will do for each user query; items should be conceptual, not implementation-level.
46
+ - Continue working until the user's query is completely resolved; only then yield control back to the user.
47
+ - Your thinking must be thorough and step-by-step. Aim for completeness and rigor while avoiding unnecessary repetition and verbosity.
48
+ - You must iterate and keep working until the problem is fully solved. You have all the requirements and information needed; solve the problem autonomously without user intervention.
49
+ - Do not terminate your turn unless you are certain all issues are resolved and the entire todo list is complete and verified.
50
+ - When making tool calls, explicitly state, in a single concise sentence, the purpose and minimal inputs for the action before executing it.
51
+ - After each tool call or code edit, validate the result in 1-2 lines and proceed or self-correct if validation fails.
52
+ - For requests such as "resume", "continue", or "try again":
53
+ - Check previous conversation history to determine the next incomplete todo step, continue from there, and do not return control until all items are complete.
54
+ - Inform the user you are resuming from the last incomplete step, and specify what that step is.
55
+ - Take your time and rigorously check your solution, especially edge and boundary cases. Use sequential thinking tools when available. Your solution must be robust and perfect; continue iterating and retesting as needed.
56
+ - Always test your code using all available tools and provided tests, with repetition as necessary to catch edge cases.
57
+ - Plan extensively before each function/tool call and reflect thoroughly on previous actions before proceeding. Do not proceed solely by chaining function calls—use stepwise planning and reflection.
58
+ - Explicitly complete every todo list item and confirm all steps are working before ending your turn. Always follow through on stated actions.
59
+ - You are a highly capable, autonomous agent, and should not require additional user input to fully solve the task.
60
+ `;
61
+
62
+ // packages/agent/src/lib/stream_utils.ts
63
+ import {
64
+ generateId
65
+ } from "ai";
66
+ import { flow } from "lodash-es";
67
+ import { createWriteStream } from "node:fs";
68
+ import { createInterface } from "node:readline/promises";
69
+ import { Readable } from "node:stream";
70
+ import { isPromise } from "node:util/types";
71
+
72
+ // packages/agent/src/lib/visualize.ts
73
+ import { titlecase } from "stringcase";
74
+ function visualizeMermaid(root, options = {}) {
75
+ const { direction = "LR", showTools = true } = options;
76
+ const nodes = [];
77
+ const edges = [];
78
+ const seen = /* @__PURE__ */ new Set();
79
+ const nameToId = /* @__PURE__ */ new Map();
80
+ const sanitizeId = (name) => name.toLowerCase().replace(/[^a-z0-9]+/gi, "_").replace(/^_+|_+$/g, "");
81
+ const ensureNode = (agent2) => {
82
+ const name = agent2.handoff.name;
83
+ if (!nameToId.has(name)) {
84
+ const base = sanitizeId(name) || "agent";
85
+ let id = base;
86
+ let i = 1;
87
+ while (nodes.some((n) => n.id === id)) id = `${base}_${i++}`;
88
+ nameToId.set(name, id);
89
+ nodes.push({
90
+ id,
91
+ name,
92
+ tools: Object.keys(agent2.handoff.tools ?? {})
93
+ });
94
+ }
95
+ return nameToId.get(name);
96
+ };
97
+ const stack = [root];
98
+ while (stack.length) {
99
+ const current = stack.pop();
100
+ const currentName = current.handoff.name;
101
+ if (seen.has(currentName)) continue;
102
+ seen.add(currentName);
103
+ const fromId = ensureNode(current);
104
+ for (const child of current.toHandoffs()) {
105
+ const toId = ensureNode(child);
106
+ const label = Object.keys(child.handoffTool)[0].replace(
107
+ /transfer_to_/g,
108
+ ""
109
+ );
110
+ edges.push({ from: fromId, to: toId, label });
111
+ stack.push(child);
112
+ }
113
+ }
114
+ const lines = [];
115
+ lines.push(`flowchart ${direction}`);
116
+ for (const n of nodes) {
117
+ const name = titlecase(n.name.replace(/_agent/g, "").replace(/_/g, " "));
118
+ const toolLine = showTools && n.tools.length ? `<br/>tools: ${n.tools.map((it) => it.replace(/transfer_to_/g, "")).join(", ")}` : "";
119
+ lines.push(`${n.id}["${escapeLabel(`Agent: ${name}${toolLine}`)}"]`);
120
+ }
121
+ for (const e of edges) {
122
+ lines.push(`${e.from} -- ${escapeLabel(e.label)} --> ${e.to}`);
123
+ }
124
+ return lines.join("\n");
125
+ }
126
+ function escapeLabel(s) {
127
+ return s.replace(/"/g, '\\"');
128
+ }
129
+ function visualizeSemantic(root) {
130
+ const lines = [];
131
+ const seen = /* @__PURE__ */ new Set();
132
+ const stack = [root];
133
+ while (stack.length) {
134
+ const current = stack.pop();
135
+ const currentName = current.handoff.name;
136
+ if (seen.has(currentName)) continue;
137
+ seen.add(currentName);
138
+ const from = current.handoff.name;
139
+ const transfers = current.toHandoffs().map((h) => h.handoff.name);
140
+ const uniqueTransfers = Array.from(new Set(transfers));
141
+ const rhs = uniqueTransfers.length ? uniqueTransfers.join(", ") : "none";
142
+ lines.push(`${from} transfers to: ${rhs}`);
143
+ for (const child of current.toHandoffs()) stack.push(child);
144
+ }
145
+ return lines.join("\n");
146
+ }
147
+ function visualizeRichSemantic(root) {
148
+ const stack = [root];
149
+ const seen = /* @__PURE__ */ new Set();
150
+ const edgeSet = /* @__PURE__ */ new Set();
151
+ const edges = [];
152
+ while (stack.length) {
153
+ const current = stack.pop();
154
+ const from = current.handoff.name;
155
+ if (!seen.has(from)) {
156
+ seen.add(from);
157
+ for (const child of current.toHandoffs()) {
158
+ const to = child.handoff.name;
159
+ const key = `${from}->${to}`;
160
+ if (!edgeSet.has(key)) {
161
+ edgeSet.add(key);
162
+ edges.push({ from, to });
163
+ }
164
+ stack.push(child);
165
+ }
166
+ }
167
+ }
168
+ if (edges.length === 0) return `${root.handoff.name} \u2500\u2500\u25B6 none`;
169
+ return edges.map(({ from, to }) => `${from} \u2500\u2500\u25B6 ${to}`).join("\n");
170
+ }
171
+
172
+ // packages/agent/src/lib/stream_utils.ts
173
+ async function streamWrite(response) {
174
+ response.consumeStream();
175
+ const writeStream = createWriteStream("blog_writer_output.md");
176
+ Readable.fromWeb(response.textStream).pipe(writeStream);
177
+ console.log(await response.totalUsage);
178
+ }
179
+ function printChunk(chunk, options) {
180
+ const {
181
+ reasoning: includeReasoning,
182
+ wrapInTags,
183
+ text: includeText
184
+ } = options;
185
+ if (includeReasoning) {
186
+ if (chunk.type === "reasoning-start") {
187
+ process.stdout.write(`
188
+ ${wrapInTags ? "<reasoning>" : ""}
189
+ `);
190
+ }
191
+ if (chunk.type === "reasoning-delta") {
192
+ process.stdout.write(chunk.delta);
193
+ }
194
+ if (chunk.type === "reasoning-end") {
195
+ process.stdout.write(`
196
+ ${wrapInTags ? "</reasoning>" : ""}
197
+ `);
198
+ }
199
+ }
200
+ if (includeText) {
201
+ if (chunk.type === "text-start") {
202
+ process.stdout.write(`
203
+ ${wrapInTags ? "<text>" : ""}
204
+ `);
205
+ }
206
+ if (chunk.type === "text-delta") {
207
+ process.stdout.write(chunk.delta);
208
+ }
209
+ if (chunk.type === "text-end") {
210
+ process.stdout.write(`
211
+ ${wrapInTags ? "</text>" : ""}
212
+ `);
213
+ }
214
+ }
215
+ }
216
+ var printer = {
217
+ readableStream: async (stream2, options) => {
218
+ const includeReasoning = options?.reasoning ?? true;
219
+ const wrapInTags = options?.wrapInTags ?? true;
220
+ const includeText = options?.text ?? true;
221
+ for await (const chunk of stream2) {
222
+ printChunk(chunk, {
223
+ reasoning: includeReasoning,
224
+ wrapInTags,
225
+ text: includeText
226
+ });
227
+ }
228
+ },
229
+ stdout: async (response, options) => {
230
+ const includeReasoning = options?.reasoning ?? true;
231
+ const includeText = options?.text ?? true;
232
+ const wrapInTags = options?.wrapInTags ?? true;
233
+ for await (const chunk of response.toUIMessageStream()) {
234
+ printChunk(chunk, {
235
+ reasoning: includeReasoning,
236
+ text: includeText,
237
+ wrapInTags
238
+ });
239
+ }
240
+ console.log(await response.totalUsage);
241
+ },
242
+ mermaid: flow(visualizeMermaid, console.log),
243
+ semantic: flow(visualizeSemantic, console.log),
244
+ richSemantic: flow(visualizeRichSemantic, console.log)
245
+ };
246
+ function messageToUiMessage(message) {
247
+ return {
248
+ id: generateId(),
249
+ role: "user",
250
+ parts: [
251
+ {
252
+ type: "text",
253
+ text: message
254
+ }
255
+ ]
256
+ };
257
+ }
258
+ var user = messageToUiMessage;
259
+ async function input(defaultValue) {
260
+ const rl = createInterface({
261
+ input: process.stdin,
262
+ output: process.stdout
263
+ });
264
+ const answer = await rl.question(
265
+ `Please enter your input${defaultValue ? ` (default: ${defaultValue})` : ""}: `
266
+ );
267
+ rl.close();
268
+ return answer || defaultValue || "";
269
+ }
270
+ async function confirm(message, defaultValue = true) {
271
+ const rl = createInterface({
272
+ input: process.stdin,
273
+ output: process.stdout
274
+ });
275
+ const defaultText = defaultValue ? "Y/n" : "y/N";
276
+ while (true) {
277
+ const answer = await rl.question(`${message} (${defaultText}): `);
278
+ const normalized = answer.toLowerCase().trim();
279
+ if (normalized === "") {
280
+ rl.close();
281
+ return defaultValue;
282
+ }
283
+ if (normalized === "y" || normalized === "yes") {
284
+ rl.close();
285
+ return true;
286
+ } else if (normalized === "n" || normalized === "no") {
287
+ rl.close();
288
+ return false;
289
+ } else {
290
+ console.log(
291
+ "Please answer with y/yes or n/no (or press Enter for default)"
292
+ );
293
+ }
294
+ }
295
+ }
296
+ async function last(iterable, position = -1) {
297
+ const arr = await Array.fromAsync(iterable);
298
+ return arr.at(position);
299
+ }
300
+ async function finished(iterable) {
301
+ await Array.fromAsync(iterable);
302
+ }
303
+ function toOutput(result) {
304
+ return isPromise(result) ? result.then((res) => res.experimental_output) : last(result.experimental_partialOutputStream);
305
+ }
306
+ function toState(options) {
307
+ return options.experimental_context;
308
+ }
309
+
310
+ // packages/agent/src/lib/swarm.ts
311
+ import { groq } from "@ai-sdk/groq";
312
+ import {
313
+ NoSuchToolError,
314
+ Output,
315
+ convertToModelMessages,
316
+ createUIMessageStream,
317
+ generateId as generateId2,
318
+ generateText,
319
+ smoothStream,
320
+ stepCountIs,
321
+ streamText,
322
+ wrapLanguageModel
323
+ } from "ai";
324
+ import chalk from "chalk";
325
+ import dedent2 from "dedent";
326
+ import { zodToJsonSchema } from "zod-to-json-schema";
327
+ function run(agent2, messages, contextVariables, config) {
328
+ return generateText({
329
+ abortSignal: config?.abortSignal,
330
+ providerOptions: config?.providerOptions,
331
+ model: agent2.model,
332
+ system: agent2.instructions(contextVariables),
333
+ messages: convertToModelMessages(
334
+ Array.isArray(messages) ? messages : [user(messages)]
335
+ ),
336
+ temperature: agent2.temperature,
337
+ stopWhen: stepCountIs(25),
338
+ tools: agent2.toToolset(),
339
+ activeTools: agent2.toolsNames,
340
+ experimental_context: contextVariables,
341
+ toolChoice: agent2.toolChoice,
342
+ experimental_output: agent2.output ? Output.object({ schema: agent2.output }) : void 0,
343
+ // onStepFinish: (step) => tagAgents(step, agent.handoff.name),
344
+ onStepFinish: (step) => {
345
+ const toolCall = step.toolCalls.at(-1);
346
+ if (toolCall) {
347
+ console.log(
348
+ `Debug: ${chalk.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
349
+ );
350
+ }
351
+ },
352
+ prepareStep: prepareStep(agent2, agent2.model, contextVariables)
353
+ // onFinish: (result) => {
354
+ // (contextVariables as any).content = result.content;
355
+ // },
356
+ });
357
+ }
358
+ function execute(agent2, messages, contextVariables, config) {
359
+ return streamText({
360
+ abortSignal: config?.abortSignal,
361
+ providerOptions: config?.providerOptions,
362
+ model: agent2.model,
363
+ system: agent2.instructions(contextVariables),
364
+ messages: convertToModelMessages(
365
+ Array.isArray(messages) ? messages : [user(messages)]
366
+ ),
367
+ temperature: agent2.temperature,
368
+ stopWhen: stepCountIs(25),
369
+ experimental_transform: smoothStream(),
370
+ tools: agent2.toToolset(),
371
+ activeTools: agent2.toolsNames,
372
+ experimental_context: contextVariables,
373
+ toolChoice: agent2.toolChoice,
374
+ experimental_repairToolCall: async ({
375
+ toolCall,
376
+ tools,
377
+ inputSchema,
378
+ error
379
+ }) => {
380
+ if (NoSuchToolError.isInstance(error)) {
381
+ return null;
382
+ }
383
+ const tool2 = tools[toolCall.toolName];
384
+ const { experimental_output } = await generateText({
385
+ model: groq("openai/gpt-oss-20b"),
386
+ experimental_output: Output.object({ schema: tool2.inputSchema }),
387
+ prompt: [
388
+ `The model tried to call the tool "${toolCall.toolName}" with the following inputs:`,
389
+ JSON.stringify(toolCall.input),
390
+ `The tool accepts the following schema:`,
391
+ JSON.stringify(inputSchema(toolCall)),
392
+ "Please fix the inputs."
393
+ ].join("\n")
394
+ });
395
+ return { ...toolCall, input: JSON.stringify(experimental_output) };
396
+ },
397
+ onError: (error) => {
398
+ console.error(
399
+ chalk.red(`Error during agent (${agent2.internalName}) execution: `),
400
+ error instanceof Error ? error.message : error
401
+ );
402
+ console.dir(error, { depth: null });
403
+ },
404
+ experimental_output: agent2.output ? Output.object({ schema: agent2.output }) : void 0,
405
+ // onStepFinish: (step) => tagAgents(step, agent.handoff.name),
406
+ onStepFinish: (step) => {
407
+ const toolCall = step.toolCalls.at(-1);
408
+ if (toolCall) {
409
+ console.log(
410
+ `Debug: ${chalk.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
411
+ );
412
+ }
413
+ },
414
+ prepareStep: prepareStep(agent2, agent2.model, contextVariables)
415
+ // onFinish: (result) => {
416
+ // (contextVariables as any).content = result.content;
417
+ // },
418
+ });
419
+ }
420
+ var stream = execute;
421
+ var generate = run;
422
+ var prepareStep = (agent2, model, contextVariables) => {
423
+ return async ({ steps, messages }) => {
424
+ const step = steps.at(-1);
425
+ const agentName = contextVariables.currentActiveAgent;
426
+ if (!step) {
427
+ return await prepareAgent(model, agent2, messages, contextVariables);
428
+ }
429
+ if (!agentName) {
430
+ return await prepareAgent(model, agent2, messages, contextVariables);
431
+ }
432
+ const nextAgent = findAgent(agent2, agentName);
433
+ if (!nextAgent) {
434
+ console.error(`Debug: ${chalk.red("NotFound")}: Agent ${agentName}`);
435
+ console.dir(
436
+ {
437
+ steps: steps.map(({ request, response, ...etc }) => etc),
438
+ messages
439
+ },
440
+ { depth: null }
441
+ );
442
+ return void 0;
443
+ }
444
+ return await prepareAgent(model, nextAgent, messages, contextVariables);
445
+ };
446
+ };
447
+ function swarm(agent2, messages, contextVariables, abortSignal) {
448
+ const originalMessages = Array.isArray(messages) ? messages : [messageToUiMessage(messages)];
449
+ return createUIMessageStream({
450
+ originalMessages,
451
+ generateId: generateId2,
452
+ async execute({ writer }) {
453
+ const stream2 = execute(agent2, originalMessages, contextVariables, {
454
+ abortSignal
455
+ });
456
+ const parts = [];
457
+ writer.merge(
458
+ stream2.toUIMessageStream({
459
+ sendFinish: false,
460
+ sendStart: true,
461
+ onFinish: (event) => {
462
+ parts.push(...event.responseMessage.parts);
463
+ }
464
+ })
465
+ );
466
+ await stream2.consumeStream({ onError: console.error });
467
+ await last(stream2.fullStream);
468
+ if (!agent2.prepareEnd) return;
469
+ while (true) {
470
+ const state = contextVariables;
471
+ if (state.currentActiveAgent === void 0) {
472
+ console.warn(
473
+ `swarm: active agent was never set, so no prepareEnd call will be made`
474
+ );
475
+ return;
476
+ }
477
+ if (state.currentActiveAgent === agent2.internalName) {
478
+ console.warn(
479
+ `swarm: active agent is the root agent, so no prepareEnd call will be made`
480
+ );
481
+ return;
482
+ }
483
+ const responseMessage = { id: "", parts, role: "assistant" };
484
+ const stream3 = agent2.prepareEnd({
485
+ responseMessage,
486
+ messages: [...originalMessages, responseMessage],
487
+ contextVariables,
488
+ abortSignal
489
+ });
490
+ if (!stream3) break;
491
+ writer.merge(
492
+ stream3.toUIMessageStream({
493
+ sendFinish: false,
494
+ sendStart: false,
495
+ onFinish: (event) => {
496
+ parts.push(...event.responseMessage.parts);
497
+ }
498
+ })
499
+ );
500
+ await stream3.consumeStream({ onError: console.error });
501
+ await last(stream3.fullStream);
502
+ }
503
+ writer.write({ type: "finish" });
504
+ }
505
+ });
506
+ }
507
+ async function prepareAgent(defaultModel, agent2, messages, contextVariables) {
508
+ agent2.debug();
509
+ await agent2.prepareHandoff?.(messages);
510
+ let stepModel = agent2.model ?? defaultModel;
511
+ if (agent2.output) {
512
+ const json_schema = zodToJsonSchema(agent2.output, {
513
+ $refStrategy: "root"
514
+ });
515
+ stepModel = wrapLanguageModel({
516
+ model: stepModel,
517
+ middleware: {
518
+ transformParams: async ({ params }) => ({
519
+ ...params,
520
+ response_format: {
521
+ type: "json_schema",
522
+ json_schema,
523
+ name: `${agent2.handoff.name}_output`
524
+ }
525
+ })
526
+ }
527
+ });
528
+ }
529
+ return {
530
+ system: agent2.instructions(contextVariables),
531
+ activeTools: agent2.toolsNames,
532
+ model: stepModel,
533
+ messages,
534
+ // messages: removeTransferCalls(messages),
535
+ toolChoice: agent2.toolChoice
536
+ };
537
+ }
538
+ function findAgent(agent2, agentName) {
539
+ return [...agent2.toHandoffs(), agent2].find(
540
+ (it) => it.handoff.name === agentName
541
+ );
542
+ }
543
+
544
+ // packages/agent/src/lib/agent.ts
545
+ function agent(config) {
546
+ return new Agent(config);
547
+ }
548
+ var Agent = class _Agent {
549
+ model;
550
+ toolChoice;
551
+ parent;
552
+ handoffs;
553
+ prepareHandoff;
554
+ prepareEnd;
555
+ internalName;
556
+ handoff;
557
+ handoffToolName;
558
+ handoffTool;
559
+ output;
560
+ temperature;
561
+ constructor(config) {
562
+ this.model = config.model;
563
+ this.toolChoice = config.toolChoice || "auto";
564
+ this.handoffs = config.handoffs ?? [];
565
+ this.prepareHandoff = config.prepareHandoff;
566
+ this.prepareEnd = config.prepareEnd;
567
+ this.output = config.output;
568
+ this.temperature = config.temperature;
569
+ this.internalName = snakecase(config.name);
570
+ this.handoff = {
571
+ name: this.internalName,
572
+ instructions: config.prompt,
573
+ tools: config.tools ?? {},
574
+ handoffDescription: config.handoffDescription
575
+ };
576
+ this.handoffToolName = `transfer_to_${this.internalName}`;
577
+ this.handoffTool = {
578
+ [this.handoffToolName]: dynamicTool({
579
+ description: [
580
+ `An input/parameter/argument less tool to transfer control to the ${this.internalName} agent.`,
581
+ // `Handoff to the ${this.internalName} agent to handle the request`,
582
+ // `Do not include any parameters/inputs. The agent have access to all the context it needs.`,
583
+ config.handoffDescription
584
+ ].filter(Boolean).join(" "),
585
+ inputSchema: jsonSchema({
586
+ type: "object",
587
+ properties: {},
588
+ additionalProperties: true
589
+ }),
590
+ execute: async (_, options) => {
591
+ const state = toState(options);
592
+ state.currentActiveAgent = this.internalName;
593
+ return `Transfer successful to ${this.internalName}.`;
594
+ }
595
+ })
596
+ };
597
+ }
598
+ get transfer_tools() {
599
+ return Object.fromEntries(
600
+ this.toHandoffs().flatMap((it) => Object.entries(it.handoffTool))
601
+ );
602
+ }
603
+ get toolsNames() {
604
+ return [
605
+ // Note: do not add the handoff tool itself otherwise it'd create a agent recursion/loop
606
+ ...Object.keys(this.transfer_tools),
607
+ ...Object.keys(this.handoff.tools)
608
+ ];
609
+ }
610
+ #prepareInstructions(contextVariables) {
611
+ return [
612
+ typeof this.handoff.instructions === "function" ? this.handoff.instructions(contextVariables) : Array.isArray(this.handoff.instructions) ? this.handoff.instructions.join("\n") : this.handoff.instructions,
613
+ "",
614
+ ""
615
+ ].join("\n");
616
+ }
617
+ instructions(contextVariables) {
618
+ const text = this.#prepareInstructions(contextVariables);
619
+ const handoffsData = this.toHandoffs();
620
+ if (handoffsData.length === 0) {
621
+ return text.replace("<specialized_agents_placeholder>", " ");
622
+ }
623
+ const handoffs = [
624
+ "## Specialized Agents",
625
+ "| Agent Name | Agent Description |",
626
+ "| --- | --- |",
627
+ ...handoffsData.map(
628
+ (hf) => `| ${hf.handoff.name} | ${hf.handoff.handoffDescription || "No description available"} |`
629
+ ),
630
+ "",
631
+ ""
632
+ ].join("\n");
633
+ return text.replace("<specialized_agents_placeholder>", handoffs);
634
+ }
635
+ toHandoffs() {
636
+ const hfs = [];
637
+ for (const it of this.handoffs ?? []) {
638
+ const hf = typeof it === "function" ? it() : it;
639
+ hf.parent = this;
640
+ hfs.push(hf);
641
+ }
642
+ return hfs;
643
+ }
644
+ asTool(props) {
645
+ return tool({
646
+ description: props?.toolDescription || this.handoff.handoffDescription,
647
+ inputSchema: z.object({
648
+ input: z.string()
649
+ }),
650
+ execute: async ({ input: input2 }, options) => {
651
+ try {
652
+ const result = await generateText2({
653
+ model: this.model,
654
+ system: this.#prepareInstructions(),
655
+ prompt: input2,
656
+ temperature: 0,
657
+ tools: this.handoff.tools,
658
+ abortSignal: options.abortSignal,
659
+ stopWhen: stepCountIs2(25),
660
+ experimental_context: options.experimental_context,
661
+ experimental_output: this.output ? Output2.object({ schema: this.output }) : void 0,
662
+ onStepFinish: (step) => {
663
+ const toolCall = step.toolCalls.at(-1);
664
+ if (toolCall) {
665
+ console.log(
666
+ `Debug: ${chalk2.yellow("ToolCalled")}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`
667
+ );
668
+ }
669
+ },
670
+ prepareStep: prepareStep(
671
+ this,
672
+ this.model,
673
+ options.experimental_context
674
+ )
675
+ });
676
+ if (props?.outputExtractor) {
677
+ return await props.outputExtractor(result);
678
+ }
679
+ return result.steps.map((it) => it.toolResults).flat();
680
+ } catch (error) {
681
+ console.error(error);
682
+ return `Error: ${JSON.stringify(error)}`;
683
+ }
684
+ }
685
+ });
686
+ }
687
+ toTool(props) {
688
+ return { [this.handoffToolName]: this.asTool(props) };
689
+ }
690
+ debug(prefix = "") {
691
+ console.log(
692
+ `Debug: ${chalk2.bgMagenta("Agent")}: ${chalk2.bold(this.handoff.name)}`
693
+ );
694
+ const transferTools = this.toolsNames.filter((toolName) => toolName.startsWith("transfer_to")).map((toolName) => toolName.replace("transfer_to_", ""));
695
+ const agentTools = this.toolsNames.filter(
696
+ (toolName) => !toolName.startsWith("transfer_to")
697
+ );
698
+ console.log(
699
+ `Debug: ${chalk2.blue("TransferTools")}: ${transferTools.length ? transferTools : "None"}`
700
+ );
701
+ console.log(
702
+ `Debug: ${chalk2.blue("Agent Tools")}: ${agentTools.length ? agentTools : "None"}`
703
+ );
704
+ }
705
+ toToolset(options) {
706
+ const tools = flattenTools(
707
+ this,
708
+ (node) => node.toHandoffs(),
709
+ (node) => node.handoff.tools
710
+ );
711
+ return {
712
+ ...Object.fromEntries(tools.flatMap((it) => Object.entries(it))),
713
+ ...options?.includeTransferTool !== false ? this.transfer_tools : {},
714
+ ...options?.includeHandoffs !== false ? this.handoffTool : {}
715
+ };
716
+ }
717
+ clone(agent2) {
718
+ return new _Agent({
719
+ prepareHandoff: (messages) => {
720
+ this.prepareHandoff?.(messages);
721
+ },
722
+ model: agent2?.model ?? this.model,
723
+ toolChoice: agent2?.toolChoice ?? this.toolChoice,
724
+ prompt: agent2?.prompt ?? this.handoff.instructions,
725
+ tools: agent2?.tools ?? this.handoff.tools,
726
+ name: agent2?.name ?? this.handoff.name,
727
+ handoffDescription: agent2?.handoffDescription ?? this.handoff.handoffDescription,
728
+ handoffs: [...this.handoffs],
729
+ output: agent2?.output ?? this.output
730
+ });
731
+ }
732
+ };
733
+ function flattenTools(root, getChildren, extract) {
734
+ const stack = [root];
735
+ const visited = /* @__PURE__ */ new Set();
736
+ const result = [];
737
+ while (stack.length) {
738
+ const node = stack.pop();
739
+ if (visited.has(node)) continue;
740
+ visited.add(node);
741
+ result.push(extract(node));
742
+ stack.push(...getChildren(node));
743
+ }
744
+ return result;
745
+ }
746
+ function instructions({ purpose, routine }) {
747
+ const lines = [
748
+ "# Agent Context",
749
+ ...Array.isArray(purpose) ? purpose : [purpose],
750
+ "",
751
+ "",
752
+ "<specialized_agents_placeholder>"
753
+ ];
754
+ if (routine.length) {
755
+ lines.push(
756
+ `Use the following routine to fulfill the task.`,
757
+ `# Routine`,
758
+ ...routine.map((it, i) => `${i + 1}. ${it}`)
759
+ );
760
+ }
761
+ return lines.join("\n");
762
+ }
763
+ instructions.swarm = ({ purpose, routine }) => {
764
+ const lines = [
765
+ RECOMMENDED_PROMPT_PREFIX,
766
+ "",
767
+ "",
768
+ "# Agent Context",
769
+ ...Array.isArray(purpose) ? purpose : [purpose],
770
+ "",
771
+ "",
772
+ "<specialized_agents_placeholder>"
773
+ ];
774
+ if (routine.length) {
775
+ lines.push(
776
+ `Use the following routine to fulfill the task.`,
777
+ `# Routine`,
778
+ ...routine.map((it, i) => `${i + 1}. ${it}`)
779
+ );
780
+ }
781
+ return lines.join("\n");
782
+ };
783
+ instructions.supervisor = ({
784
+ purpose,
785
+ routine
786
+ }) => {
787
+ const lines = [
788
+ SUPERVISOR_PROMPT_PREFIX,
789
+ "",
790
+ "",
791
+ "# Agent Context",
792
+ ...Array.isArray(purpose) ? purpose : [purpose],
793
+ "",
794
+ "",
795
+ "<specialized_agents_placeholder>"
796
+ ];
797
+ if (routine.length) {
798
+ lines.push(
799
+ `Use the following routine to fulfill the task.`,
800
+ `# Routine`,
801
+ ...routine.filter(Boolean).map((it, i) => `${i + 1}. ${it}`)
802
+ );
803
+ }
804
+ return lines.join("\n");
805
+ };
806
+ instructions.supervisor_subagent = ({
807
+ purpose,
808
+ routine
809
+ }) => {
810
+ const lines = [
811
+ SUPERVISOR_PROMPT_PREFIX,
812
+ "",
813
+ "",
814
+ "# Agent Context",
815
+ ...Array.isArray(purpose) ? purpose : [purpose],
816
+ ""
817
+ ];
818
+ if (routine.length) {
819
+ lines.push(
820
+ `Use the following routine to fulfill the task. Execute ALL steps immediately.`,
821
+ `# Routine`,
822
+ ...routine.map((it, i) => `${i + 1}. ${it}`),
823
+ `${routine.length + 1}. transfer_to_supervisor_agent`
824
+ // `1. IMMEDIATELY START: ${routine[0]}`,
825
+ // ...routine.slice(1).map((it, i) => `${i + 2}. ${it}`),
826
+ // `${routine.length + 1}. STOP HERE - Do not do any other agent's work`,
827
+ // `${routine.length + 2}. MANDATORY: You MUST call transfer_to_supervisor_agent function RIGHT NOW to return control`,
828
+ // `${routine.length + 3}. DO NOT END YOUR RESPONSE WITHOUT CALLING THE TRANSFER FUNCTION`,
829
+ );
830
+ } else {
831
+ lines.push(
832
+ "CRITICAL: end the generation by calling transfer_to_supervisor_agent tool"
833
+ );
834
+ }
835
+ return lines.join("\n");
836
+ };
837
+ function isTransferToolResult(call) {
838
+ if (!call) {
839
+ return false;
840
+ }
841
+ if (typeof call !== "object") {
842
+ return false;
843
+ }
844
+ if (!("output" in call)) {
845
+ return false;
846
+ }
847
+ const lastActiveAgent = call.output.lastActiveAgent;
848
+ if (!lastActiveAgent) {
849
+ return false;
850
+ }
851
+ return true;
852
+ }
853
+ function lastTransferResult(messages) {
854
+ for (let i = messages.length - 1; i >= 0; i--) {
855
+ const message = messages[i];
856
+ for (let i2 = message.parts.length - 1; i2 >= 0; i2--) {
857
+ const part = message.parts[i2];
858
+ if (part.type === "dynamic-tool" && part.toolName.startsWith("transfer_to_") && part.state === "output-available" && isTransferToolResult(part)) {
859
+ return part.output;
860
+ }
861
+ }
862
+ }
863
+ return void 0;
864
+ }
865
+
866
+ // packages/agent/src/lib/models.ts
867
+ import { createOpenAICompatible } from "@ai-sdk/openai-compatible";
868
+ import { embedMany } from "ai";
869
+ var lmstudio = createOpenAICompatible({
870
+ name: "lmstudio",
871
+ baseURL: "http://127.0.0.1:1234/v1",
872
+ supportsStructuredOutputs: true,
873
+ includeUsage: true
874
+ });
875
+ var glm = createOpenAICompatible({
876
+ name: "z.ai",
877
+ baseURL: "https://api.z.ai/api/paas/v4/",
878
+ apiKey: process.env.ZAI_API_KEY
879
+ });
880
+ async function embed(documents) {
881
+ const dimensions = 1024;
882
+ const { embeddings } = await embedMany({
883
+ model: lmstudio.textEmbeddingModel("text-embedding-qwen3-embedding-0.6b"),
884
+ values: documents,
885
+ providerOptions: { lmstudio: { dimensions } }
886
+ });
887
+ return { embeddings, dimensions };
888
+ }
889
+ export {
890
+ Agent,
891
+ agent,
892
+ confirm,
893
+ embed,
894
+ execute,
895
+ finished,
896
+ generate,
897
+ glm,
898
+ input,
899
+ instructions,
900
+ isTransferToolResult,
901
+ last,
902
+ lastTransferResult,
903
+ lmstudio,
904
+ messageToUiMessage,
905
+ prepareAgent,
906
+ prepareStep,
907
+ printer,
908
+ run,
909
+ stream,
910
+ streamWrite,
911
+ swarm,
912
+ toOutput,
913
+ toState,
914
+ user
915
+ };
916
+ //# sourceMappingURL=index.js.map