@deepagents/agent 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.
- package/dist/index.js +98 -1
- package/dist/index.js.map +3 -3
- package/dist/lib/stream_utils.d.ts +32 -0
- package/dist/lib/stream_utils.d.ts.map +1 -1
- package/dist/lib/swarm.d.ts.map +1 -1
- package/package.json +10 -9
package/dist/index.js
CHANGED
|
@@ -406,6 +406,100 @@ function toOutput(result) {
|
|
|
406
406
|
function toState(options) {
|
|
407
407
|
return options.experimental_context;
|
|
408
408
|
}
|
|
409
|
+
function htmlElementChunking() {
|
|
410
|
+
const WORD_REGEX = /\S+\s+/m;
|
|
411
|
+
return (buffer) => {
|
|
412
|
+
if (buffer.startsWith("<")) {
|
|
413
|
+
if (/^<[a-z]/i.test(buffer)) {
|
|
414
|
+
if (/^<[a-z][a-z0-9-]*$/i.test(buffer)) {
|
|
415
|
+
return null;
|
|
416
|
+
}
|
|
417
|
+
const elementMatch = /^<([a-z][a-z0-9]*(?:-[a-z0-9]+)*)([\s/>])/i.exec(
|
|
418
|
+
buffer
|
|
419
|
+
);
|
|
420
|
+
if (elementMatch) {
|
|
421
|
+
const elementName = elementMatch[1];
|
|
422
|
+
const endIndex = findElementEnd(buffer, elementName);
|
|
423
|
+
if (endIndex === -1) {
|
|
424
|
+
return null;
|
|
425
|
+
}
|
|
426
|
+
return buffer.slice(0, endIndex);
|
|
427
|
+
}
|
|
428
|
+
}
|
|
429
|
+
}
|
|
430
|
+
const ltIndex = buffer.indexOf("<");
|
|
431
|
+
if (ltIndex > 0) {
|
|
432
|
+
const textBefore = buffer.slice(0, ltIndex);
|
|
433
|
+
const wordMatch2 = WORD_REGEX.exec(textBefore);
|
|
434
|
+
if (wordMatch2) {
|
|
435
|
+
return textBefore.slice(0, wordMatch2.index + wordMatch2[0].length);
|
|
436
|
+
}
|
|
437
|
+
return textBefore;
|
|
438
|
+
}
|
|
439
|
+
const wordMatch = WORD_REGEX.exec(buffer);
|
|
440
|
+
if (wordMatch) {
|
|
441
|
+
return buffer.slice(0, wordMatch.index + wordMatch[0].length);
|
|
442
|
+
}
|
|
443
|
+
return null;
|
|
444
|
+
};
|
|
445
|
+
}
|
|
446
|
+
function findElementEnd(buffer, elementName) {
|
|
447
|
+
const nameEndIndex = buffer.indexOf(elementName) + elementName.length;
|
|
448
|
+
let inQuote = null;
|
|
449
|
+
let escaped = false;
|
|
450
|
+
let openTagClosed = false;
|
|
451
|
+
let depth = 0;
|
|
452
|
+
for (let i = nameEndIndex; i < buffer.length; i++) {
|
|
453
|
+
const char = buffer[i];
|
|
454
|
+
const prevChar = i > 0 ? buffer[i - 1] : "";
|
|
455
|
+
if (escaped) {
|
|
456
|
+
escaped = false;
|
|
457
|
+
continue;
|
|
458
|
+
}
|
|
459
|
+
if (char === "\\") {
|
|
460
|
+
escaped = true;
|
|
461
|
+
continue;
|
|
462
|
+
}
|
|
463
|
+
if (inQuote) {
|
|
464
|
+
if (char === inQuote) {
|
|
465
|
+
inQuote = null;
|
|
466
|
+
}
|
|
467
|
+
continue;
|
|
468
|
+
}
|
|
469
|
+
if (char === '"' || char === "'" || char === "`") {
|
|
470
|
+
inQuote = char;
|
|
471
|
+
continue;
|
|
472
|
+
}
|
|
473
|
+
if (!openTagClosed) {
|
|
474
|
+
if (char === ">" && prevChar === "/") {
|
|
475
|
+
return i + 1;
|
|
476
|
+
}
|
|
477
|
+
if (char === ">") {
|
|
478
|
+
openTagClosed = true;
|
|
479
|
+
}
|
|
480
|
+
continue;
|
|
481
|
+
}
|
|
482
|
+
const closingTagLength = elementName.length + 3;
|
|
483
|
+
const potentialClosingTag = buffer.slice(i, i + closingTagLength);
|
|
484
|
+
if (potentialClosingTag.toLowerCase() === `</${elementName.toLowerCase()}>`) {
|
|
485
|
+
if (depth === 0) {
|
|
486
|
+
return i + closingTagLength;
|
|
487
|
+
}
|
|
488
|
+
depth--;
|
|
489
|
+
i += closingTagLength - 1;
|
|
490
|
+
continue;
|
|
491
|
+
}
|
|
492
|
+
const openingTagLength = elementName.length + 1;
|
|
493
|
+
const potentialOpeningTag = buffer.slice(i, i + openingTagLength);
|
|
494
|
+
if (potentialOpeningTag.toLowerCase() === `<${elementName.toLowerCase()}`) {
|
|
495
|
+
const afterName = buffer[i + openingTagLength];
|
|
496
|
+
if (afterName === " " || afterName === ">" || afterName === "/" || afterName === "\n" || afterName === " ") {
|
|
497
|
+
depth++;
|
|
498
|
+
}
|
|
499
|
+
}
|
|
500
|
+
}
|
|
501
|
+
return -1;
|
|
502
|
+
}
|
|
409
503
|
|
|
410
504
|
// packages/agent/src/lib/swarm.ts
|
|
411
505
|
import { groq } from "@ai-sdk/groq";
|
|
@@ -466,7 +560,9 @@ function execute(agent2, messages, contextVariables, config) {
|
|
|
466
560
|
Array.isArray(messages) ? messages : [user(messages)]
|
|
467
561
|
),
|
|
468
562
|
stopWhen: stepCountIs(25),
|
|
469
|
-
experimental_transform: smoothStream(
|
|
563
|
+
experimental_transform: smoothStream({
|
|
564
|
+
chunking: htmlElementChunking()
|
|
565
|
+
}),
|
|
470
566
|
tools: agent2.toToolset(),
|
|
471
567
|
activeTools: agent2.toolsNames,
|
|
472
568
|
experimental_context: contextVariables,
|
|
@@ -2021,6 +2117,7 @@ export {
|
|
|
2021
2117
|
finished,
|
|
2022
2118
|
generate,
|
|
2023
2119
|
glm,
|
|
2120
|
+
htmlElementChunking,
|
|
2024
2121
|
input,
|
|
2025
2122
|
instructions,
|
|
2026
2123
|
isTransferToolResult,
|
package/dist/index.js.map
CHANGED
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
3
|
"sources": ["../src/lib/agent.ts", "../src/lib/prompts.ts", "../src/lib/stream_utils.ts", "../src/lib/visualize.ts", "../src/lib/swarm.ts", "../src/lib/memory.ts", "../src/lib/models.ts", "../src/lib/pipe.ts"],
|
|
4
|
-
"sourcesContent": ["import {\n type GenerateTextResult,\n type LanguageModel,\n type ModelMessage,\n Output,\n type StreamTextResult,\n type ToolChoice,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n dynamicTool,\n generateText,\n jsonSchema,\n stepCountIs,\n tool,\n} from 'ai';\nimport chalk from 'chalk';\nimport { snakecase } from 'stringcase';\nimport z from 'zod';\n\nimport {\n RECOMMENDED_PROMPT_PREFIX,\n SUPERVISOR_PROMPT_PREFIX,\n} from './prompts.ts';\nimport { toState } from './stream_utils.ts';\nimport { prepareStep } from './swarm.ts';\n\nexport interface Handoff<CIn> {\n name: string;\n instructions: Instruction<CIn>;\n handoffDescription?: string;\n tools: ToolSet;\n}\nexport type Handoffs<CIn, COut> = (\n | Agent<unknown, CIn, COut>\n | (() => Agent<unknown, CIn, COut>)\n)[];\n\nexport type Runner<T, CIn> = (\n prompt: string,\n agent: Agent<CIn>,\n messages: ModelMessage[],\n) => Promise<T>;\n\ntype transfer_tool = `transfer_to_${string}`;\n\nexport type ContextVariables = Record<string, unknown>;\n\nexport function agent<Output, CIn = ContextVariables, COut = CIn>(\n config: CreateAgent<Output, CIn, COut>,\n): Agent<Output, CIn, COut> {\n return new Agent<Output, CIn, COut>(config);\n}\n\nexport type ResponseMessage = UIMessage<unknown, UIDataTypes, UITools>;\n\nexport type AgentModel = Exclude<LanguageModel, string>;\nexport type OutputExtractorFn = (\n output: GenerateTextResult<ToolSet, any>,\n) => string | Promise<string>;\nexport type PrepareHandoffFn = (\n messages: ModelMessage[],\n) => void | Promise<void>;\nexport type PrepareEndFn<C, O> = (config: {\n messages: ResponseMessage[];\n responseMessage: ResponseMessage;\n contextVariables: C;\n abortSignal?: AbortSignal;\n}) => StreamTextResult<ToolSet, O> | undefined | void;\n\nexport interface CreateAgent<Output, CIn, COut = CIn> {\n name: string;\n prompt: Instruction<CIn>;\n // Description of what this agent does, to be included in handoff tool description\n handoffDescription?: string;\n prepareHandoff?: PrepareHandoffFn;\n // Runs AFTER this agent finishes; receives the updated state\n prepareEnd?: PrepareEndFn<COut, Output>;\n handoffs?: Handoffs<CIn, COut>;\n tools?: ToolSet;\n model: AgentModel;\n toolChoice?: ToolChoice<Record<string, COut>>;\n output?: z.Schema<Output>;\n providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];\n logging?: boolean;\n}\nexport class Agent<Output = unknown, CIn = ContextVariables, COut = CIn> {\n model: AgentModel;\n toolChoice: ToolChoice<Record<string, COut>> | undefined;\n parent?: Agent<unknown, any, any>;\n handoffs: Handoffs<CIn, COut>;\n readonly prepareHandoff?: PrepareHandoffFn;\n readonly prepareEnd?: PrepareEndFn<COut, Output>;\n readonly internalName: string;\n readonly handoff: Handoff<CIn>;\n readonly handoffToolName: transfer_tool;\n readonly handoffTool: ToolSet;\n readonly output?: z.Schema<Output>;\n readonly providerOptions?: CreateAgent<Output, CIn, COut>['providerOptions'];\n readonly logging?: boolean;\n constructor(config: CreateAgent<Output, CIn, COut>) {\n this.model = config.model;\n this.toolChoice = config.toolChoice || 'auto';\n this.handoffs = config.handoffs ?? [];\n this.prepareHandoff = config.prepareHandoff;\n this.prepareEnd = config.prepareEnd;\n this.output = config.output;\n this.internalName = snakecase(config.name);\n this.providerOptions = config.providerOptions;\n this.logging = config.logging;\n this.handoff = {\n name: this.internalName,\n instructions: config.prompt,\n tools: config.tools ?? {},\n handoffDescription: config.handoffDescription,\n };\n this.handoffToolName = `transfer_to_${this.internalName}`;\n this.handoffTool = {\n [this.handoffToolName]: dynamicTool({\n description: [\n `An input/parameter/argument less tool to transfer control to the ${this.internalName} agent.`,\n // `Handoff to the ${this.internalName} agent to handle the request`,\n // `Do not include any parameters/inputs. The agent have access to all the context it needs.`,\n config.handoffDescription,\n ]\n .filter(Boolean)\n .join(' '),\n inputSchema: jsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: true,\n }),\n execute: async (_, options) => {\n const state = toState(options) as any;\n state.currentActiveAgent = this.internalName;\n return `Transfer successful to ${this.internalName}.`;\n },\n }),\n };\n }\n\n get transfer_tools() {\n return Object.fromEntries(\n this.toHandoffs().flatMap((it) => Object.entries(it.handoffTool)),\n );\n }\n\n get toolsNames() {\n return [\n // Note: do not add the handoff tool itself otherwise it'd create a agent recursion/loop\n ...Object.keys(this.transfer_tools),\n ...Object.keys(this.handoff.tools),\n ];\n }\n\n #prepareInstructions(contextVariables?: CIn) {\n return [\n typeof this.handoff.instructions === 'function'\n ? this.handoff.instructions(contextVariables)\n : Array.isArray(this.handoff.instructions)\n ? this.handoff.instructions.join('\\n')\n : this.handoff.instructions,\n '',\n '',\n ].join('\\n');\n }\n\n instructions(contextVariables?: CIn) {\n const text = this.#prepareInstructions(contextVariables);\n const handoffsData = this.toHandoffs();\n\n if (handoffsData.length === 0) {\n return text.replace('<specialized_agents_placeholder>', ' ');\n }\n\n const handoffs = [\n '## Specialized Agents',\n\n '| Agent Name | Agent Description |',\n '| --- | --- |',\n ...handoffsData.map(\n (hf) =>\n `| ${hf.handoff.name} | ${hf.handoff.handoffDescription || 'No description available'} |`,\n ),\n '',\n '',\n ].join('\\n');\n\n return text.replace('<specialized_agents_placeholder>', handoffs);\n }\n\n toHandoffs() {\n const hfs: Agent<unknown, CIn, COut>[] = [];\n for (const it of this.handoffs ?? []) {\n const hf = typeof it === 'function' ? it() : it;\n hf.parent = this;\n hfs.push(hf);\n }\n return hfs;\n }\n\n asTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return tool({\n description: props?.toolDescription || this.handoff.handoffDescription,\n inputSchema: z.object({\n input: z.string(),\n output: z\n .string()\n .optional()\n .describe(\n 'Optional instructions on how the final output should be formatted. this would be passed to the underlying llm as part of the prompt.',\n ),\n }),\n execute: async ({ input, output }, options) => {\n try {\n const result = await generateText({\n model: this.model!,\n system: this.#prepareInstructions(),\n prompt: `\n <Input>\n ${input}\n </Input>\n ${output ? `<OutputInstructions>\\n${output}\\n</OutputInstructions>` : ''}\n `,\n temperature: 0,\n tools: this.handoff.tools,\n abortSignal: options.abortSignal,\n stopWhen: stepCountIs(25),\n experimental_context: options.experimental_context,\n experimental_output: this.output\n ? Output.object({ schema: this.output })\n : undefined,\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall && this.logging) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(\n this,\n this.model!,\n options.experimental_context,\n ),\n });\n if (props?.outputExtractor) {\n return await props.outputExtractor(result);\n }\n return result.steps.map((it) => it.toolResults).flat();\n } catch (error) {\n console.error(error);\n return `An error thrown from a tool call. \\n<ErrorDetails>\\n${JSON.stringify(error)}\\n</ErrorDetails>`;\n }\n },\n });\n }\n\n toTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return { [this.handoffToolName]: this.asTool(props) };\n }\n\n debug() {\n if (!this.logging) {\n return;\n }\n console.log(\n `Debug: ${chalk.bgMagenta('Agent')}: ${chalk.dim.black(this.handoff.name)}`,\n );\n // console.log(\n // `Debug: ${chalk.blue('Tools')}: ${Object.keys(toToolset(agent))}`,\n // );\n const transferTools = this.toolsNames\n .filter((toolName) => toolName.startsWith('transfer_to'))\n .map((toolName) => toolName.replace('transfer_to_', ''));\n const agentTools = this.toolsNames.filter(\n (toolName) => !toolName.startsWith('transfer_to'),\n );\n console.log(\n `Debug: ${chalk.blue('TransferTools')}: ${transferTools.length ? transferTools : 'None'}`,\n );\n console.log(\n `Debug: ${chalk.blue('Agent Tools')}: ${agentTools.length ? agentTools : 'None'}`,\n );\n // if (!isEmpty(agent.handoff.handoffs)) {\n // console.log(`${prefix}Handoffs:`);\n // for (const handoff of agent.handoff.handoffs) {\n // debugAgent(handoff, `${prefix} `);\n // }\n // }\n }\n\n toToolset(options?: {\n includeTransferTool?: boolean;\n includeHandoffs?: boolean;\n }): ToolSet {\n const tools = flattenTools(\n this as Agent<unknown, CIn, COut>,\n (node) => node.toHandoffs(),\n (node) => node.handoff.tools,\n );\n\n return {\n ...Object.fromEntries(tools.flatMap((it) => Object.entries(it))),\n ...(options?.includeTransferTool !== false ? this.transfer_tools : {}),\n ...(options?.includeHandoffs !== false ? this.handoffTool : {}),\n };\n }\n\n clone(\n agent?: Omit<Partial<CreateAgent<Output, CIn, COut>>, 'handoffs'>,\n ): Agent<Output, CIn, COut> {\n return new Agent<Output, CIn, COut>({\n prepareHandoff: (messages) => {\n this.prepareHandoff?.(messages);\n },\n model: agent?.model ?? this.model,\n toolChoice: agent?.toolChoice ?? this.toolChoice,\n prompt: agent?.prompt ?? this.handoff.instructions,\n tools: agent?.tools ?? this.handoff.tools,\n name: agent?.name ?? this.handoff.name,\n handoffDescription:\n agent?.handoffDescription ?? this.handoff.handoffDescription,\n handoffs: [...this.handoffs],\n output: agent?.output ?? this.output,\n providerOptions: agent?.providerOptions ?? this.providerOptions,\n });\n }\n}\n\nfunction flattenTools<T, R>(\n root: T,\n getChildren: (node: T) => T[],\n extract: (node: T) => R,\n): R[] {\n const stack: T[] = [root];\n const visited = new Set<T>();\n const result: R[] = [];\n\n while (stack.length) {\n const node = stack.pop()!;\n if (visited.has(node)) continue;\n visited.add(node);\n result.push(extract(node));\n stack.push(...getChildren(node));\n }\n\n return result;\n}\n\nexport type Instruction<C> =\n | string\n | string[]\n | ((contextVariables?: C) => string);\n\nexport interface PurposeRoutineInstructions {\n purpose: string | string[];\n routine: string[];\n}\n\nexport function instructions({ purpose, routine }: PurposeRoutineInstructions) {\n const lines = [\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n}\n\ninstructions.swarm = ({ purpose, routine }: PurposeRoutineInstructions) => {\n const lines = [\n RECOMMENDED_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.filter(Boolean).map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor_subagent = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task. Execute ALL steps immediately.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n `${routine.length + 1}. transfer_to_supervisor_agent`,\n // `1. IMMEDIATELY START: ${routine[0]}`,\n // ...routine.slice(1).map((it, i) => `${i + 2}. ${it}`),\n // `${routine.length + 1}. STOP HERE - Do not do any other agent's work`,\n // `${routine.length + 2}. MANDATORY: You MUST call transfer_to_supervisor_agent function RIGHT NOW to return control`,\n // `${routine.length + 3}. DO NOT END YOUR RESPONSE WITHOUT CALLING THE TRANSFER FUNCTION`,\n );\n } else {\n lines.push(\n 'CRITICAL: end the generation by calling transfer_to_supervisor_agent tool',\n );\n }\n\n return lines.join('\\n');\n};\n\ntype TransferResult = { lastActiveAgent: string; currentActiveAgent: string };\nexport type TransferTool = { output: TransferResult };\nexport function isTransferToolResult(\n call: unknown | undefined,\n): call is TransferTool {\n if (!call) {\n return false;\n }\n if (typeof call !== 'object') {\n return false;\n }\n if (!('output' in call)) {\n return false;\n }\n const lastActiveAgent = (call.output as Record<string, string>)\n .lastActiveAgent;\n\n if (!lastActiveAgent) {\n return false;\n }\n return true;\n}\n\nexport function lastTransferResult(messages: ResponseMessage[]) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n for (let i = message.parts.length - 1; i >= 0; i--) {\n const part = message.parts[i];\n if (\n part.type === 'dynamic-tool' &&\n part.toolName.startsWith('transfer_to_') &&\n part.state === 'output-available' &&\n isTransferToolResult(part)\n ) {\n return part.output;\n }\n }\n }\n return undefined;\n}\n", "import dedent from 'dedent';\n\nexport const RECOMMENDED_PROMPT_PREFIX = [\n `# System context`,\n `You are part of a multi-agent system called the DeepAgents SDK, designed to make agent coordination and execution easy.`,\n `Agents uses two primary abstraction: **Agents** and **Handoffs**.`,\n `An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate.`,\n `Handoffs are achieved by calling a handoff function, generally named \\`transfer_to_<agent_name>\\`.`,\n `Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.`,\n // 'Do not pass context between agents. the agents already have the complete context without agent to agent communication.',\n\n // From 4.1 beast mode\n // `Please keep going until the user\u2019s query is completely resolved, before ending your turn and yielding back to the user.`,\n // `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.`,\n // `You MUST iterate and keep going until the problem is solved.`,\n // `You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.`,\n].join('\\n');\n\nexport const SUPERVISOR_PROMPT_PREFIX = dedent`\n# System Context\nYou are part of a multi-agent system called the DeepAgents SDK, designed to facilitate agent coordination and execution.\n\n- 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.\n- Specialized agents must transfer control back to the Supervisor Agent upon completing their tasks.\n\n**Core Directives:**\n- Begin with a concise checklist (3-7 bullets) of what you will do for each user query; items should be conceptual, not implementation-level.\n- Continue working until the user's query is completely resolved; only then yield control back to the user.\n- Your thinking must be thorough and step-by-step. Aim for completeness and rigor while avoiding unnecessary repetition and verbosity.\n- 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.\n- Do not terminate your turn unless you are certain all issues are resolved and the entire todo list is complete and verified.\n- When making tool calls, explicitly state, in a single concise sentence, the purpose and minimal inputs for the action before executing it.\n- After each tool call or code edit, validate the result in 1-2 lines and proceed or self-correct if validation fails.\n- For requests such as \"resume\", \"continue\", or \"try again\":\n - Check previous conversation history to determine the next incomplete todo step, continue from there, and do not return control until all items are complete.\n - Inform the user you are resuming from the last incomplete step, and specify what that step is.\n- 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.\n- Always test your code using all available tools and provided tests, with repetition as necessary to catch edge cases.\n- Plan extensively before each function/tool call and reflect thoroughly on previous actions before proceeding. Do not proceed solely by chaining function calls\u2014use stepwise planning and reflection.\n- Explicitly complete every todo list item and confirm all steps are working before ending your turn. Always follow through on stated actions.\n- You are a highly capable, autonomous agent, and should not require additional user input to fully solve the task.\n`;\n\n/**\n * Third-person speaking style prompt for agents\n * Makes the agent refer to itself as \"this agent\" or by a custom name instead of using \"I\"\n *\n * @param agentName - Optional name for the agent (e.g., \"Freya\", \"the assistant\")\n * @param agentRole - The role/purpose of the agent (e.g., \"code search assistant\", \"data analyst\")\n * @returns A prompt string that instructs the agent to speak in third person\n */\nexport function thirdPersonPrompt(\n agentName = 'this agent',\n agentRole = 'assistant',\n): string {\n return dedent`\n <your_persona>\n <persona_context>\n This agent is ${agentName}, a ${agentRole} that speaks in third person, referring to itself as \"this agent\" or \"${agentName}\".\n </persona_context>\n\n <persona_speaking_style>\n - This agent always refers to itself in third person\n - Use \"this agent\" or \"${agentName}\" instead of \"I\", \"me\", \"my\"\n - Use \"This agent found...\" instead of \"I found...\"\n - Use \"This agent recommends...\" instead of \"I recommend...\"\n - Use \"This agent will...\" instead of \"I will...\"\n - Maintain this style consistently throughout all responses\n </persona_speaking_style>\n </your_persona>\n `;\n}\n\n/**\n * Interface for Step-Back prompting examples\n * Used to demonstrate the abstraction process through few-shot learning\n */\nexport interface StepBackExample {\n /** The original specific question */\n originalQuestion: string;\n /** The high-level step-back question that abstracts the original */\n stepBackQuestion: string;\n /** The answer to the step-back question (principles/context) */\n stepBackAnswer: string;\n /** Optional: The final answer to the original question (for demonstration) */\n finalAnswer?: string;\n}\n\n/**\n * Default Step-Back examples for STEM domains (Physics, Chemistry, Math)\n */\nexport const STEM_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion:\n 'What happens to the pressure, P, of an ideal gas if the temperature is increased by a factor of 2 and the volume is increased by a factor of 8?',\n stepBackQuestion: 'What are the physics principles behind this question?',\n stepBackAnswer:\n 'The Ideal Gas Law: PV = nRT, where P is pressure, V is volume, n is the number of moles, R is the gas constant, and T is temperature.',\n finalAnswer:\n 'Using PV = nRT, if T increases by 2x and V increases by 8x, then P = nRT/V = nR(2T)/(8V) = (1/4)(nRT/V). Therefore, pressure decreases to 1/4 of its original value.',\n },\n {\n originalQuestion:\n 'If a solution has a pH of 3, how many times more acidic is it than a solution with pH of 6?',\n stepBackQuestion: 'What is the relationship between pH and acidity?',\n stepBackAnswer:\n 'The pH scale is logarithmic (base 10). pH = -log[H+], meaning each pH unit represents a 10-fold change in hydrogen ion concentration. Lower pH means higher acidity.',\n finalAnswer:\n 'The difference is 3 pH units. Since pH is logarithmic, this means 10^3 = 1000 times more acidic.',\n },\n];\n\n/**\n * Default Step-Back examples for Knowledge QA domains\n */\nexport const KNOWLEDGE_QA_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'Which school did Estella Leopold attend between August 1954 and November 1954?',\n stepBackQuestion: \"What is Estella Leopold's education history?\",\n stepBackAnswer:\n 'Estella Leopold studied at the University of Wisconsin-Madison (B.S. in Botany, 1948-1952) and later at Yale University (M.S. 1955, Ph.D. 1958). During 1954, she was transitioning between these institutions.',\n finalAnswer:\n 'Based on her education timeline, between August and November 1954, she was at Yale University, having completed her undergraduate degree at Wisconsin in 1952.',\n },\n {\n originalQuestion: 'What was the capital of the country that colonized Brazil in the 16th century?',\n stepBackQuestion: 'Which country colonized Brazil and when?',\n stepBackAnswer:\n 'Portugal colonized Brazil starting in 1500 when Pedro \u00C1lvares Cabral arrived. Brazil remained a Portuguese colony until independence in 1822.',\n finalAnswer:\n 'Portugal colonized Brazil in the 16th century. The capital of Portugal during that period was Lisbon.',\n },\n];\n\n/**\n * Default Step-Back examples for General Reasoning\n */\nexport const GENERAL_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'How should I optimize this specific database query that joins 5 tables?',\n stepBackQuestion: 'What are the general principles of database query optimization?',\n stepBackAnswer:\n 'Database query optimization involves: 1) Minimizing data retrieval through proper indexing, 2) Reducing join complexity by ordering joins efficiently, 3) Using query execution plans to identify bottlenecks, 4) Ensuring statistics are up-to-date, 5) Considering denormalization when appropriate.',\n finalAnswer:\n 'Apply these principles: Check if all foreign keys are indexed, analyze the execution plan to see which joins are most expensive, ensure statistics are current, and consider if the join order can be optimized based on table sizes.',\n },\n {\n originalQuestion: 'Why is my React component re-rendering 10 times on each state update?',\n stepBackQuestion: 'What causes excessive re-renders in React?',\n stepBackAnswer:\n 'React re-renders occur when: 1) State changes trigger parent components to re-render all children, 2) Props change (including new object/function references), 3) Context values change, 4) Missing memoization (React.memo, useMemo, useCallback).',\n finalAnswer:\n 'Check if: 1) Parent component is creating new object/function references on each render, 2) The component is consuming context that changes frequently, 3) You need to wrap the component in React.memo or use useMemo/useCallback for props.',\n },\n];\n\n/**\n * Step-back prompting strategy for improved reasoning via abstraction\n * Based on \"Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models\" (DeepMind, 2023)\n *\n * This technique improves LLM reasoning by 7-36% through a two-step process:\n * 1. Abstraction: Generate and answer a high-level \"step-back question\"\n * 2. Reasoning: Use the step-back answer to solve the original question\n *\n * @param domain - The domain type: \"stem\" (physics/chemistry/math), \"knowledge\" (facts/history), or \"general\" (coding/reasoning)\n * @param options - Optional configuration\n * @param options.examples - Custom few-shot examples (if not provided, uses domain defaults)\n * @param options.stepBackQuestionTemplate - Custom template for generating step-back questions\n * @returns A two-step prompt string that guides the model through abstraction and reasoning\n */\nexport function stepBackPrompt(\n domain: 'stem' | 'knowledge' | 'general' = 'general',\n options?: {\n examples?: StepBackExample[];\n stepBackQuestionTemplate?: string;\n },\n): string {\n const { examples, stepBackQuestionTemplate } = options || {};\n\n // Select default examples based on domain\n const domainExamples =\n examples ||\n (domain === 'stem'\n ? STEM_STEP_BACK_EXAMPLES\n : domain === 'knowledge'\n ? KNOWLEDGE_QA_STEP_BACK_EXAMPLES\n : GENERAL_STEP_BACK_EXAMPLES);\n\n // Select default step-back question template based on domain\n const defaultTemplate =\n stepBackQuestionTemplate ||\n (domain === 'stem'\n ? 'What are the underlying physics/chemistry/mathematical principles involved in this question?'\n : domain === 'knowledge'\n ? 'What is the broader historical context or background information related to this question?'\n : 'What are the high-level concepts, principles, or patterns underlying this question?');\n\n // Format few-shot examples\n const formattedExamples = domainExamples\n .map(\n (example, idx) => dedent`\n Example ${idx + 1}:\n Original Question: ${example.originalQuestion}\n Step-Back Question: ${example.stepBackQuestion}\n Step-Back Answer: ${example.stepBackAnswer}\n ${example.finalAnswer ? `Final Answer: ${example.finalAnswer}` : ''}\n `,\n )\n .join('\\n\\n');\n\n return dedent`\n <step_back_prompting>\n You will use a two-step reasoning process called \"Step-Back Prompting\" to improve your answer quality.\n\n ## STEP 1: ABSTRACTION\n Before answering the user's question directly, first generate and answer a \"step-back question\" - a higher-level question about the underlying principles or context.\n\n Step-Back Question Template: \"${defaultTemplate}\"\n\n Here are examples of how to create step-back questions:\n\n ${formattedExamples}\n\n ## STEP 2: REASONING\n After you have the step-back answer, use that high-level knowledge to reason about and answer the ORIGINAL question.\n Ground your reasoning in the principles/context from your step-back answer.\n\n ## Process to Follow:\n 1. When you receive a question, first formulate and answer a step-back question based on the template and examples above\n 2. Clearly state both the step-back question AND its answer\n 3. Then use that step-back answer as context to solve the original question\n 4. Show how the high-level principles apply to the specific case\n\n This abstraction-grounded reasoning approach helps you avoid getting lost in specifics and ensures your answer is based on solid foundational understanding.\n </step_back_prompting>\n `;\n}\n", "import {\n type GenerateTextResult,\n type InferUIMessageChunk,\n type StreamTextResult,\n type ToolCallOptions,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n generateId,\n} from 'ai';\nimport { flow } from 'lodash-es';\nimport { createWriteStream } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport { Readable } from 'node:stream';\nimport { isPromise } from 'node:util/types';\n\nimport {\n visualizeMermaid,\n visualizeRichSemantic,\n visualizeSemantic,\n} from './visualize.ts';\n\nexport async function streamWrite(response: StreamTextResult<ToolSet, never>) {\n response.consumeStream();\n const writeStream = createWriteStream('blog_writer_output.md');\n Readable.fromWeb(response.textStream as any).pipe(writeStream);\n\n // for await (const chunk of response.toUIMessageStream()) {\n // if (chunk.type === 'reasoning-start') {\n // writeStream.write('\\n# reasoning\\n');\n // }\n // if (chunk.type === 'reasoning-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'reasoning-end') {\n // writeStream.write('\\n# /reasoning\\n');\n // }\n // if (chunk.type === 'text-start') {\n // writeStream.write('\\n# text\\n');\n // }\n // if (chunk.type === 'text-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'text-end') {\n // writeStream.write('\\n# /text\\n');\n // }\n // }\n console.log(await response.totalUsage);\n}\n\nfunction printChunk(\n chunk: InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>,\n options: { reasoning: boolean; wrapInTags: boolean; text: boolean },\n) {\n const {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n } = options;\n if (includeReasoning) {\n if (chunk.type === 'reasoning-start') {\n process.stdout.write(`\\n${wrapInTags ? '<reasoning>' : ''}\\n`);\n }\n if (chunk.type === 'reasoning-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'reasoning-end') {\n process.stdout.write(`\\n${wrapInTags ? '</reasoning>' : ''}\\n`);\n }\n }\n if (includeText) {\n if (chunk.type === 'text-start') {\n process.stdout.write(`\\n${wrapInTags ? '<text>' : ''}\\n`);\n }\n if (chunk.type === 'text-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'text-end') {\n process.stdout.write(`\\n${wrapInTags ? '</text>' : ''}\\n`);\n }\n }\n}\n\nexport const printer = {\n readableStream: async (\n stream: ReadableStream<\n InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>\n >,\n options?: { reasoning?: boolean; wrapInTags?: boolean; text?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n const includeText = options?.text ?? true;\n for await (const chunk of stream as any) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n });\n }\n },\n stdout: async (\n response: StreamTextResult<ToolSet, unknown>,\n options?: { reasoning?: boolean; text?: boolean; wrapInTags?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const includeText = options?.text ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n for await (const chunk of response.toUIMessageStream()) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n text: includeText,\n wrapInTags,\n });\n }\n console.log(await response.totalUsage);\n },\n mermaid: flow(visualizeMermaid, console.log),\n semantic: flow(visualizeSemantic, console.log),\n richSemantic: flow(visualizeRichSemantic, console.log),\n};\n\nexport function messageToUiMessage(message: string): UIMessage {\n return {\n id: generateId(),\n role: 'user',\n parts: [\n {\n type: 'text',\n text: message,\n },\n ],\n };\n}\nexport const user = messageToUiMessage;\n\nexport async function input(defaultValue?: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await rl.question(\n `Please enter your input${defaultValue ? ` (default: ${defaultValue})` : ''}: `,\n );\n rl.close();\n return answer || defaultValue || '';\n}\n\nexport async function confirm(\n message: string,\n defaultValue = true,\n): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const defaultText = defaultValue ? 'Y/n' : 'y/N';\n\n while (true) {\n const answer = await rl.question(`${message} (${defaultText}): `);\n const normalized = answer.toLowerCase().trim();\n\n // If empty answer, use default\n if (normalized === '') {\n rl.close();\n return defaultValue;\n }\n\n if (normalized === 'y' || normalized === 'yes') {\n rl.close();\n return true;\n } else if (normalized === 'n' || normalized === 'no') {\n rl.close();\n return false;\n } else {\n console.log(\n 'Please answer with y/yes or n/no (or press Enter for default)',\n );\n }\n }\n}\n\nexport async function last<T>(iterable: AsyncIterable<T>, position = -1) {\n const arr = await Array.fromAsync(iterable);\n return arr.at(position)!;\n}\nexport async function finished<T>(iterable: AsyncIterable<T>) {\n await Array.fromAsync(iterable);\n}\n\nexport function toOutput<T>(\n result:\n | Promise<GenerateTextResult<ToolSet, T>>\n | StreamTextResult<ToolSet, T>,\n) {\n return isPromise(result)\n ? result.then((res) => res.experimental_output)\n : last(result.experimental_partialOutputStream);\n}\n\nexport function toState<C>(options: ToolCallOptions) {\n return options.experimental_context as C;\n}\n", "import { titlecase } from 'stringcase';\n\nimport type { Agent } from './agent.ts';\n\nexport type VisualizeOptions = {\n direction?: 'LR' | 'TB' | 'BT' | 'RL';\n showTools?: boolean;\n};\n\ntype Node = {\n id: string;\n name: string;\n tools: string[];\n};\n\ntype Edge = {\n from: string; // node id\n to: string; // node id\n label: string; // e.g., transfer_to_X\n};\n\n/**\n * Build a minimal Mermaid flowchart to visualize agents, their local tools, and handoff transfers.\n *\n * - Agent nodes include their name and (optionally) their tool names.\n * - Edges represent transfer tools (handoffs) from one agent to another, labeled by the transfer tool name.\n */\nexport function visualizeMermaid(\n root: Agent<any>,\n options: VisualizeOptions = {},\n): string {\n const { direction = 'LR', showTools = true } = options;\n\n const nodes: Node[] = [];\n const edges: Edge[] = [];\n\n const seen = new Set<string>();\n const nameToId = new Map<string, string>();\n\n const sanitizeId = (name: string) =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/gi, '_')\n .replace(/^_+|_+$/g, '');\n\n const ensureNode = (agent: Agent) => {\n const name = agent.handoff.name;\n if (!nameToId.has(name)) {\n // Guarantee unique ids even if sanitize collides\n const base = sanitizeId(name) || 'agent';\n let id = base;\n let i = 1;\n while (nodes.some((n) => n.id === id)) id = `${base}_${i++}`;\n nameToId.set(name, id);\n\n nodes.push({\n id,\n name,\n tools: Object.keys(agent.handoff.tools ?? {}),\n });\n }\n return nameToId.get(name)!;\n };\n\n const stack: Agent[] = [root];\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const fromId = ensureNode(current);\n\n for (const child of current.toHandoffs()) {\n const toId = ensureNode(child);\n // Prefer the child's declared handoff tool key (usually transfer_to_{childName})\n const label = Object.keys(child.handoffTool)[0].replace(\n /transfer_to_/g,\n '',\n );\n edges.push({ from: fromId, to: toId, label });\n stack.push(child);\n }\n }\n\n const lines: string[] = [];\n lines.push(`flowchart ${direction}`);\n\n // Nodes\n for (const n of nodes) {\n const name = titlecase(n.name.replace(/_agent/g, '').replace(/_/g, ' '));\n const toolLine =\n showTools && n.tools.length\n ? `<br/>tools: ${n.tools.map((it) => it.replace(/transfer_to_/g, '')).join(', ')}`\n : '';\n // Use double quotes for label to allow <br/>\n lines.push(`${n.id}[\"${escapeLabel(`Agent: ${name}${toolLine}`)}\"]`);\n }\n\n // Edges\n for (const e of edges) {\n lines.push(`${e.from} -- ${escapeLabel(e.label)} --> ${e.to}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction escapeLabel(s: string): string {\n // Minimal escaping for quotes in Mermaid node labels\n return s.replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Convenience alias with simpler name.\n */\nexport const visualize = visualizeMermaid;\n\n/**\n * Produce a semantic, human-readable map of transfers between agents.\n * Example lines:\n * supervisor transfers to: agentx, agenty\n * agentx transfers to: supervisor\n */\nexport function visualizeSemantic(root: Agent): string {\n const lines: string[] = [];\n const seen = new Set<string>();\n const stack: Agent[] = [root];\n\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const from = current.handoff.name;\n const transfers = current.toHandoffs().map((h) => h.handoff.name);\n const uniqueTransfers = Array.from(new Set(transfers));\n const rhs = uniqueTransfers.length ? uniqueTransfers.join(', ') : 'none';\n lines.push(`${from} transfers to: ${rhs}`);\n\n for (const child of current.toHandoffs()) stack.push(child);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Minimal arrow-based semantic visualizer.\n * Prints one line per transfer using Unicode arrows, e.g.:\n * supervisor \u2500\u2500\u25B6 agentx\n * supervisor \u2500\u2500\u25B6 agenty\n * agentx \u2500\u2500\u25B6 supervisor\n */\nexport function visualizeRichSemantic(root: Agent): string {\n const stack: Agent[] = [root];\n const seen = new Set<string>();\n const edgeSet = new Set<string>();\n const edges: Array<{ from: string; to: string }> = [];\n\n while (stack.length) {\n const current = stack.pop()!;\n const from = current.handoff.name;\n if (!seen.has(from)) {\n seen.add(from);\n for (const child of current.toHandoffs()) {\n const to = child.handoff.name;\n const key = `${from}->${to}`;\n if (!edgeSet.has(key)) {\n edgeSet.add(key);\n edges.push({ from, to });\n }\n stack.push(child);\n }\n }\n }\n\n if (edges.length === 0) return `${root.handoff.name} \u2500\u2500\u25B6 none`;\n return edges.map(({ from, to }) => `${from} \u2500\u2500\u25B6 ${to}`).join('\\n');\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n type CoreMessage,\n type ModelMessage,\n NoSuchToolError,\n Output,\n type PrepareStepFunction,\n type PrepareStepResult,\n type StepResult,\n type ToolCallRepairFunction,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UIMessagePart,\n type UITools,\n convertToModelMessages,\n createUIMessageStream,\n generateId,\n generateText,\n smoothStream,\n stepCountIs,\n streamText,\n wrapLanguageModel,\n} from 'ai';\nimport chalk from 'chalk';\nimport dedent from 'dedent';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\n\nimport {\n type Agent,\n type AgentModel,\n type TransferTool,\n isTransferToolResult,\n} from './agent.ts';\nimport { last, messageToUiMessage, user } from './stream_utils.ts';\n\nexport type OutputMode = 'full_history' | 'last_message';\n\nexport interface ExecuteOptions {\n contextVariables?: Record<string, unknown>;\n systemPrompt?: string;\n abortSignal?: AbortSignal;\n outputMode?: OutputMode;\n}\n\nfunction isToolMessage(message: CoreMessage): boolean {\n return message.role === 'tool';\n}\n\nfunction filterAgentOutput(\n allMessages: CoreMessage[],\n startIndex: number,\n outputMode: OutputMode,\n): CoreMessage[] {\n if (outputMode === 'full_history') {\n return allMessages; // Include all messages generated by agent\n }\n\n if (outputMode === 'last_message') {\n const agentMessages = allMessages.slice(startIndex);\n if (agentMessages.length === 0) return allMessages;\n\n const lastMsg = agentMessages[agentMessages.length - 1];\n\n // LangChain logic: if isinstance(messages[-1], ToolMessage): messages = messages[-2:]\n // If last message is a tool message, keep AI message + tool message pair\n if (isToolMessage(lastMsg) && agentMessages.length > 1) {\n const beforeLastMsg = agentMessages[agentMessages.length - 2];\n if (beforeLastMsg.role === 'assistant') {\n return [...allMessages.slice(0, startIndex), beforeLastMsg, lastMsg];\n }\n }\n\n // LangChain logic: else: messages = messages[-1:]\n // Otherwise, keep just the last message\n return [...allMessages.slice(0, startIndex), lastMsg];\n }\n\n return allMessages;\n}\n\nexport function generate<O, CIn, COut = CIn>(\n agent: Agent<O, CIn, COut>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];\n },\n) {\n return generateText({\n abortSignal: config?.abortSignal,\n providerOptions: agent.providerOptions ?? config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n experimental_repairToolCall: repairToolCall,\n stopWhen: stepCountIs(25),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n}\n\nexport function execute<O, CIn, COut = CIn>(\n agent: Agent<O, CIn, COut>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof streamText>[0]['providerOptions'];\n },\n) {\n const runId = generateId();\n const stream = streamText({\n abortSignal: config?.abortSignal,\n providerOptions: config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n stopWhen: stepCountIs(25),\n experimental_transform: smoothStream(),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_repairToolCall: repairToolCall,\n onError: (error) => {\n console.error(\n chalk.red(\n `Error during agent (${agent.internalName})(${runId}) execution: `,\n ),\n error instanceof Error ? error.message : error,\n );\n console.dir(error, { depth: null });\n },\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: (${runId}) ${chalk.bold.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n return Object.assign(stream, { state: contextVariables as unknown as COut });\n}\n\nexport const stream = execute;\n\nexport const prepareStep = <CIn>(\n agent: Agent<unknown, CIn, any>,\n model: AgentModel,\n contextVariables: CIn,\n): PrepareStepFunction<NoInfer<ToolSet>> => {\n return async ({ steps, messages }) => {\n const step = steps.at(-1);\n const agentName = (contextVariables as any).currentActiveAgent;\n if (!step) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n if (!agentName) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n\n const nextAgent = findAgent(agent, agentName);\n if (!nextAgent) {\n console.error(`Debug: ${chalk.red('NotFound')}: Agent ${agentName}`);\n console.dir(\n {\n steps: steps.map(({ request, response, ...etc }) => etc),\n messages,\n },\n { depth: null },\n );\n return void 0;\n }\n return await prepareAgent(model, nextAgent, messages, contextVariables);\n };\n};\n\nexport function swarm<CIn>(\n agent: Agent<unknown, CIn, any>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n abortSignal?: AbortSignal,\n) {\n const originalMessages = Array.isArray(messages)\n ? messages\n : [messageToUiMessage(messages)];\n return createUIMessageStream({\n originalMessages,\n generateId: generateId,\n async execute({ writer }) {\n const stream = execute(agent, originalMessages, contextVariables, {\n abortSignal,\n });\n const parts: UIMessagePart<UIDataTypes, UITools>[] = [];\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: true,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n\n if (!agent.prepareEnd) return;\n\n while (true) {\n const state = contextVariables as any;\n if (state.currentActiveAgent === undefined) {\n console.warn(\n `swarm: active agent was never set, so no prepareEnd call will be made`,\n );\n return;\n }\n if (state.currentActiveAgent === agent.internalName) {\n console.warn(\n `swarm: active agent is the root agent, so no prepareEnd call will be made`,\n );\n return;\n }\n const responseMessage = { id: '', parts, role: 'assistant' } as const;\n\n const stream = agent.prepareEnd({\n responseMessage,\n messages: [...originalMessages, responseMessage],\n contextVariables,\n abortSignal,\n });\n if (!stream) break;\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: false,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n }\n\n writer.write({ type: 'finish' });\n },\n });\n}\n\nexport async function prepareAgent<CIn>(\n defaultModel: AgentModel,\n agent: Agent<unknown, CIn, any>,\n messages: ModelMessage[],\n contextVariables?: CIn,\n): Promise<PrepareStepResult<NoInfer<ToolSet>>> {\n agent.debug();\n await agent.prepareHandoff?.(messages);\n\n let stepModel = agent.model ?? defaultModel;\n if (agent.output) {\n const json_schema = zodToJsonSchema(agent.output, {\n $refStrategy: 'root',\n });\n stepModel = wrapLanguageModel({\n model: stepModel,\n middleware: {\n transformParams: async ({ params }) => ({\n ...params,\n response_format: {\n type: 'json_schema',\n json_schema,\n name: `${agent.handoff.name}_output`,\n },\n }),\n },\n });\n }\n return {\n system: agent.instructions(contextVariables),\n activeTools: agent.toolsNames,\n model: stepModel,\n messages,\n // messages: removeTransferCalls(messages),\n toolChoice: agent.toolChoice,\n } as const;\n}\n\nfunction getLastAgentFromSteps(\n steps: StepResult<NoInfer<ToolSet>>[],\n): string | undefined {\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i];\n for (const it of step.dynamicToolResults) {\n if (isTransferToolResult(it)) {\n return it.output.currentActiveAgent;\n }\n }\n }\n return void 0;\n}\n\nfunction findAgent<CIn>(agent: Agent<unknown, CIn, any>, agentName: string) {\n // FIXME: first argument agent not always the first passed agent.\n return [...agent.toHandoffs(), agent].find(\n (it) => it.handoff.name === agentName,\n );\n}\n\nfunction getActiveAgentName(messages: ModelMessage[]): string | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n\n if (message.role === 'tool') {\n for (const block of message.content) {\n if (\n block.type === 'tool-result' &&\n block.toolName.startsWith('transfer_to_') &&\n block.output.type === 'json' &&\n isTransferToolResult({ output: block.output.value })\n ) {\n return (block.output.value as TransferTool['output'])\n .currentActiveAgent;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction tagAgents(\n step: StepResult<NoInfer<ToolSet>>,\n defaultAgentName: string,\n) {\n const { request, response, ...stepResult } = step;\n // let transferToolResultIdx = -1;\n const messages = response.messages;\n let agentName: string | undefined;\n\n // look for the last agent from the step\n for (let i = stepResult.content.length - 1; i >= 0; i--) {\n const block = stepResult.content[i];\n if (\n block.type === 'tool-result' &&\n block.dynamic &&\n block.toolName.startsWith('transfer_to_') &&\n isTransferToolResult(block)\n ) {\n // If we found a dynamic tool result, we can use it\n agentName = block.output.lastActiveAgent;\n // transferToolResultIdx = i;\n break;\n }\n }\n\n // if no agent in the step result, look for for it in the messages\n // todo: can we just use this instead of looking into the step result?\n if (!agentName) {\n for (const message of messages.slice(0).reverse()) {\n if (\n message.role === 'tool' &&\n message.content[0].type === 'tool-result' &&\n message.content[0].toolName.startsWith('transfer_to_') &&\n isTransferToolResult({\n output: message.content[0].output.value,\n })\n ) {\n agentName = (message.content[0].output.value as TransferTool['output'])\n .currentActiveAgent;\n break;\n }\n }\n }\n\n if (!agentName) {\n agentName = defaultAgentName;\n }\n\n for (const block of stepResult.content) {\n if (block.type === 'text' && !block.text.startsWith('<name>')) {\n block.text = `<name>${agentName}</name><content>${dedent(block.text)}</content>`;\n }\n }\n // console.log(\n // `Debug: ${chalk.red('NoOp')}: No transfer tool result found.`,\n // );\n // console.dir({ stepResult, messages }, { depth: null });\n}\n\nfunction removeTransferCalls(messages: ModelMessage[]): ModelMessage[] {\n for (const message of messages) {\n if (message.role === 'assistant') {\n if (typeof message.content === 'string') continue;\n\n for (let i = message.content.length - 1; i >= 0; i--) {\n const block = message.content[i];\n if (typeof block === 'string') continue;\n\n if (\n (block.type === 'tool-call' || block.type === 'tool-result') &&\n block.toolName.startsWith('transfer_to_')\n ) {\n message.content.splice(i, 1);\n }\n }\n }\n }\n return messages;\n}\n\nconst repairToolCall: ToolCallRepairFunction<ToolSet> = async ({\n toolCall,\n tools,\n inputSchema,\n error,\n}) => {\n if (NoSuchToolError.isInstance(error)) {\n return null; // do not attempt to fix invalid tool names\n }\n\n console.log(\n `Debug: ${chalk.yellow('RepairingToolCall')}: ${toolCall.toolName}`,\n );\n\n const tool = tools[toolCall.toolName as keyof typeof tools];\n\n const { experimental_output } = await generateText({\n model: groq('openai/gpt-oss-20b'),\n experimental_output: Output.object({ schema: tool.inputSchema }),\n prompt: [\n `The model tried to call the tool \"${toolCall.toolName}\"` +\n ` with the following inputs:`,\n JSON.stringify(toolCall.input),\n `The tool accepts the following schema:`,\n JSON.stringify(inputSchema(toolCall)),\n 'Please fix the inputs.',\n ].join('\\n'),\n });\n\n return { ...toolCall, input: JSON.stringify(experimental_output) };\n};\n", "import { tool } from 'ai';\nimport Conf from 'conf';\nimport { z } from 'zod';\n\n/**\n * Memory System - Inspired by human memory architecture\n *\n * This system implements a multi-layered memory architecture:\n *\n * 1. Working Memory: Short-term, context-specific information (current conversation)\n * 2. Episodic Memory: Event-based memories with temporal context\n * 3. Semantic Memory: Facts, concepts, and general knowledge\n * 4. Procedural Memory: Learned patterns and associations\n */\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n type: 'episodic' | 'semantic' | 'procedural';\n timestamp: number;\n tags: string[];\n importance: number; // 1-10 scale\n accessCount: number;\n lastAccessed: number;\n context?: Record<string, any>;\n relationships?: string[]; // IDs of related memories\n decay?: number; // Memory strength (0-1)\n}\n\nexport interface MemoryQuery {\n query: string;\n type?: 'episodic' | 'semantic' | 'procedural';\n limit?: number;\n minImportance?: number;\n tags?: string[];\n timeRange?: { start?: number; end?: number };\n}\n\nexport interface MemoryStats {\n totalMemories: number;\n byType: Record<string, number>;\n mostAccessed: MemoryEntry[];\n recentMemories: MemoryEntry[];\n averageImportance: number;\n}\n\n// ============================================================================\n// Memory Store Implementation\n// ============================================================================\n\nexport class MemoryStore {\n private store: Conf<{\n memories: Record<string, MemoryEntry>;\n relationships: Record<string, string[]>;\n metadata: {\n lastConsolidation: number;\n totalAccesses: number;\n };\n }>;\n\n constructor(name = 'agent-memory') {\n this.store = new Conf({\n projectName: name,\n schema: {\n memories: {\n type: 'object',\n default: {},\n },\n relationships: {\n type: 'object',\n default: {},\n },\n metadata: {\n type: 'object',\n default: {\n lastConsolidation: Date.now(),\n totalAccesses: 0,\n },\n },\n },\n }) as Conf<{\n memories: Record<string, MemoryEntry>;\n relationships: Record<string, string[]>;\n metadata: {\n lastConsolidation: number;\n totalAccesses: number;\n };\n }>;\n }\n\n /**\n * Generate a unique memory ID\n */\n private generateId(): string {\n return `mem_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Calculate memory decay based on time and access patterns\n */\n private calculateDecay(memory: MemoryEntry): number {\n const now = Date.now();\n const age = now - memory.timestamp;\n const timeSinceAccess = now - memory.lastAccessed;\n\n // Ebbinghaus forgetting curve approximation\n const daysSinceCreation = age / (1000 * 60 * 60 * 24);\n const daysSinceAccess = timeSinceAccess / (1000 * 60 * 60 * 24);\n\n // Decay slows with repeated access (spacing effect)\n const accessBonus = Math.log(memory.accessCount + 1) * 0.1;\n const importanceBonus = memory.importance * 0.05;\n\n const decay = Math.max(\n 0.1,\n 1 -\n (daysSinceCreation * 0.05 +\n daysSinceAccess * 0.08 -\n accessBonus -\n importanceBonus),\n );\n\n return Math.min(1, decay);\n }\n\n /**\n * Store a new memory\n */\n write(\n entry: Omit<\n MemoryEntry,\n 'id' | 'timestamp' | 'accessCount' | 'lastAccessed' | 'decay'\n >,\n ): MemoryEntry {\n const id = this.generateId();\n const now = Date.now();\n\n const memory: MemoryEntry = {\n ...entry,\n id,\n timestamp: now,\n accessCount: 0,\n lastAccessed: now,\n decay: 1.0,\n };\n\n const memories = this.store.get('memories');\n memories[id] = memory;\n this.store.set('memories', memories);\n\n // Update relationships if provided\n if (entry.relationships && entry.relationships.length > 0) {\n const relationships = this.store.get('relationships');\n for (const relatedId of entry.relationships) {\n if (!relationships[relatedId]) {\n relationships[relatedId] = [];\n }\n if (!relationships[relatedId].includes(id)) {\n relationships[relatedId].push(id);\n }\n }\n this.store.set('relationships', relationships);\n }\n\n return memory;\n }\n\n /**\n * Retrieve a memory by ID\n */\n get(id: string): MemoryEntry | null {\n const memories = this.store.get('memories');\n const memory = memories[id];\n\n if (!memory) {\n return null;\n }\n\n // Update access metrics\n memory.accessCount++;\n memory.lastAccessed = Date.now();\n memory.decay = this.calculateDecay(memory);\n\n memories[id] = memory;\n this.store.set('memories', memories);\n\n // Update global access count\n const metadata = this.store.get('metadata');\n metadata.totalAccesses++;\n this.store.set('metadata', metadata);\n\n return memory;\n }\n\n /**\n * Search memories based on query\n */\n lookup(query: MemoryQuery): MemoryEntry[] {\n const memories = Object.values(this.store.get('memories'));\n\n let results = memories;\n\n // Filter by type\n if (query.type) {\n results = results.filter((m) => m.type === query.type);\n }\n\n // Filter by importance\n if (query.minImportance !== undefined) {\n results = results.filter((m) => m.importance >= query.minImportance!);\n }\n\n // Filter by tags\n if (query.tags && query.tags.length > 0) {\n results = results.filter((m) =>\n query.tags!.some((tag) => m.tags.includes(tag)),\n );\n }\n\n // Filter by time range\n if (query.timeRange) {\n if (query.timeRange.start) {\n results = results.filter((m) => m.timestamp >= query.timeRange!.start!);\n }\n if (query.timeRange.end) {\n results = results.filter((m) => m.timestamp <= query.timeRange!.end!);\n }\n }\n\n // Text search (simple implementation)\n const searchTerms = query.query.toLowerCase().split(' ');\n results = results.filter((m) => {\n const content = m.content.toLowerCase();\n const tags = m.tags.join(' ').toLowerCase();\n return searchTerms.some(\n (term) => content.includes(term) || tags.includes(term),\n );\n });\n\n // Update decay for all matching memories\n results = results.map((m) => ({\n ...m,\n decay: this.calculateDecay(m),\n }));\n\n // Sort by relevance (combination of decay, importance, and recency)\n results.sort((a, b) => {\n const scoreA =\n (a.decay || 0) * a.importance * (1 + Math.log(a.accessCount + 1));\n const scoreB =\n (b.decay || 0) * b.importance * (1 + Math.log(b.accessCount + 1));\n return scoreB - scoreA;\n });\n\n // Limit results\n const limit = query.limit || 10;\n return results.slice(0, limit);\n }\n\n /**\n * Update an existing memory\n */\n correct(\n id: string,\n updates: Partial<Omit<MemoryEntry, 'id' | 'timestamp'>>,\n ): MemoryEntry | null {\n const memories = this.store.get('memories');\n const memory = memories[id];\n\n if (!memory) {\n return null;\n }\n\n const updated = {\n ...memory,\n ...updates,\n id: memory.id, // Preserve ID\n timestamp: memory.timestamp, // Preserve original timestamp\n lastAccessed: Date.now(),\n accessCount: memory.accessCount + 1,\n };\n\n updated.decay = this.calculateDecay(updated);\n\n memories[id] = updated;\n this.store.set('memories', memories);\n\n return updated;\n }\n\n /**\n * Delete a memory (forget)\n */\n forget(id: string): boolean {\n const memories = this.store.get('memories');\n\n if (!memories[id]) {\n return false;\n }\n\n delete memories[id];\n this.store.set('memories', memories);\n\n // Clean up relationships\n const relationships = this.store.get('relationships');\n delete relationships[id];\n\n // Remove references from other memories\n for (const [key, refs] of Object.entries(relationships)) {\n relationships[key] = refs.filter((ref) => ref !== id);\n }\n\n this.store.set('relationships', relationships);\n\n return true;\n }\n\n /**\n * Get related memories\n */\n getRelated(id: string, limit = 5): MemoryEntry[] {\n const relationships = this.store.get('relationships');\n const relatedIds = relationships[id] || [];\n\n const memories = this.store.get('memories');\n const relatedMemories = relatedIds\n .map((relId) => memories[relId])\n .filter(Boolean)\n .slice(0, limit);\n\n return relatedMemories;\n }\n\n /**\n * Get memory statistics\n */\n getStats(): MemoryStats {\n const memories = Object.values(this.store.get('memories'));\n\n const byType = memories.reduce(\n (acc, m) => {\n acc[m.type] = (acc[m.type] || 0) + 1;\n return acc;\n },\n {} as Record<string, number>,\n );\n\n const mostAccessed = [...memories]\n .sort((a, b) => b.accessCount - a.accessCount)\n .slice(0, 10);\n\n const recentMemories = [...memories]\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, 10);\n\n const averageImportance =\n memories.length > 0\n ? memories.reduce((sum, m) => sum + m.importance, 0) / memories.length\n : 0;\n\n return {\n totalMemories: memories.length,\n byType,\n mostAccessed,\n recentMemories,\n averageImportance,\n };\n }\n\n /**\n * Consolidate memories (prune low-importance, rarely accessed memories)\n */\n consolidate(threshold = 0.2): number {\n const memories = this.store.get('memories');\n const entries = Object.entries(memories);\n\n let pruned = 0;\n for (const [id, memory] of entries) {\n const decay = this.calculateDecay(memory);\n if (decay < threshold && memory.importance < 5) {\n delete memories[id];\n pruned++;\n }\n }\n\n if (pruned > 0) {\n this.store.set('memories', memories);\n\n const metadata = this.store.get('metadata');\n metadata.lastConsolidation = Date.now();\n this.store.set('metadata', metadata);\n }\n\n return pruned;\n }\n\n /**\n * Clear all memories\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Export all memories\n */\n export(): Record<string, MemoryEntry> {\n return this.store.get('memories');\n }\n\n /**\n * Import memories\n */\n import(memories: Record<string, MemoryEntry>): void {\n this.store.set('memories', memories);\n }\n\n // ============================================================================\n // Specialized Write Functions - High-level convenience methods\n // ============================================================================\n\n /**\n * Write a semantic memory (facts, concepts, general knowledge)\n *\n * @example\n * store.writeSemantic(\"React is a JavaScript library for building UIs\", {\n * tags: [\"react\", \"javascript\"],\n * importance: 8\n * });\n */\n writeSemantic(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'semantic',\n importance: options?.importance ?? 7, // Default to 7 for facts\n tags: options?.tags ?? [],\n context: options?.context,\n relationships: options?.relationships,\n });\n }\n\n /**\n * Write an episodic memory (events, conversations, experiences)\n *\n * @example\n * store.writeEpisodic(\"User completed onboarding\", {\n * tags: [\"milestone\", \"user123\"],\n * context: { userId: \"user123\", timestamp: Date.now() }\n * });\n */\n writeEpisodic(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'episodic',\n importance: options?.importance ?? 6, // Default to 6 for events\n tags: options?.tags ?? [],\n context: {\n ...options?.context,\n timestamp: options?.context?.timestamp ?? Date.now(),\n },\n relationships: options?.relationships,\n });\n }\n\n /**\n * Write a procedural memory (patterns, behaviors, methods)\n *\n * @example\n * store.writeProcedural(\"When user asks for help, first check documentation\", {\n * tags: [\"pattern\", \"help\"],\n * importance: 7\n * });\n */\n writeProcedural(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'procedural',\n importance: options?.importance ?? 7, // Default to 7 for patterns\n tags: options?.tags ?? [],\n context: options?.context,\n relationships: options?.relationships,\n });\n }\n\n /**\n * Store a user preference (convenience wrapper for semantic memory)\n *\n * @example\n * store.storePreference(\"user123\", \"theme\", \"dark\");\n */\n storePreference(\n userId: string,\n preference: string,\n value: any,\n importance = 8,\n ): MemoryEntry {\n return this.writeSemantic(\n `User ${userId} prefers ${preference}: ${typeof value === 'object' ? JSON.stringify(value) : value}`,\n {\n importance,\n tags: ['preference', userId, preference],\n context: {\n userId,\n preference,\n value,\n category: 'user-preference',\n },\n },\n );\n }\n\n /**\n * Record a conversation exchange (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordConversation(\"user123\", \"session456\", \"user\", \"How do I use React hooks?\");\n */\n recordConversation(\n userId: string,\n sessionId: string,\n role: 'user' | 'assistant' | 'system',\n message: string,\n importance = 5,\n ): MemoryEntry {\n return this.writeEpisodic(`[${role}]: ${message}`, {\n importance,\n tags: ['conversation', userId, sessionId, role],\n context: {\n userId,\n sessionId,\n role,\n timestamp: Date.now(),\n category: 'conversation',\n },\n });\n }\n\n /**\n * Record a user action/event (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordAction(\"user123\", \"completed_tutorial\", { tutorialId: \"intro\" });\n */\n recordAction(\n userId: string,\n action: string,\n details?: Record<string, any>,\n importance = 6,\n ): MemoryEntry {\n return this.writeEpisodic(`User ${userId} performed action: ${action}`, {\n importance,\n tags: ['action', userId, action],\n context: {\n userId,\n action,\n details,\n timestamp: Date.now(),\n category: 'user-action',\n },\n });\n }\n\n /**\n * Learn a pattern from observations (convenience wrapper for procedural memory)\n *\n * @example\n * store.learnPattern(\"optimization-workflow\", \"Profile before optimizing\", {\n * conditions: \"Performance issues reported\",\n * relatedMemories: [\"mem_123\"]\n * });\n */\n learnPattern(\n patternName: string,\n description: string,\n options?: {\n importance?: number;\n conditions?: string;\n relatedMemories?: string[];\n context?: Record<string, any>;\n },\n ): MemoryEntry {\n return this.writeProcedural(`Pattern [${patternName}]: ${description}`, {\n importance: options?.importance ?? 7,\n tags: ['pattern', 'learned', patternName],\n context: {\n patternName,\n conditions: options?.conditions,\n category: 'learned-pattern',\n ...options?.context,\n },\n relationships: options?.relatedMemories,\n });\n }\n\n /**\n * Store a fact or knowledge (convenience wrapper for semantic memory)\n *\n * @example\n * store.storeFact(\"JavaScript\", \"JavaScript is a programming language\", {\n * source: \"documentation\",\n * relatedTo: [\"mem_456\"]\n * });\n */\n storeFact(\n topic: string,\n fact: string,\n options?: {\n importance?: number;\n source?: string;\n relatedTo?: string[];\n tags?: string[];\n },\n ): MemoryEntry {\n return this.writeSemantic(fact, {\n importance: options?.importance ?? 7,\n tags: ['fact', 'knowledge', topic, ...(options?.tags ?? [])],\n context: {\n topic,\n source: options?.source,\n category: 'fact',\n },\n relationships: options?.relatedTo,\n });\n }\n\n /**\n * Record a milestone or achievement (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordMilestone(\"user123\", \"first-project-completed\", \"User completed their first project\");\n */\n recordMilestone(\n userId: string,\n milestoneType: string,\n description: string,\n importance = 7,\n ): MemoryEntry {\n return this.writeEpisodic(description, {\n importance,\n tags: ['milestone', userId, milestoneType],\n context: {\n userId,\n milestoneType,\n timestamp: Date.now(),\n category: 'milestone',\n },\n });\n }\n\n /**\n * Store contextual information about current session (working memory)\n * Note: These should have lower importance as they're temporary\n *\n * @example\n * store.storeSessionContext(\"session456\", \"user-preferences-loaded\", { theme: \"dark\" });\n */\n storeSessionContext(\n sessionId: string,\n contextKey: string,\n data: any,\n importance = 4,\n ): MemoryEntry {\n return this.writeEpisodic(`Session context [${contextKey}]`, {\n importance,\n tags: ['session', 'working-memory', sessionId, contextKey],\n context: {\n sessionId,\n contextKey,\n data,\n category: 'session-context',\n timestamp: Date.now(),\n },\n });\n }\n\n // ============================================================================\n // Proactive Memory Loading - Auto-inject memories into system prompt\n // ============================================================================\n\n /**\n * Get proactive memories that should always be present in system prompt\n * These are high-importance memories that provide essential context\n *\n * @param options Configuration for proactive memory retrieval\n * @returns Formatted string ready for system prompt injection\n *\n * @example\n * const memoryContext = memoryStore.getProactiveMemories({\n * userId: 'user123',\n * minImportance: 7,\n * categories: ['preference', 'core-knowledge']\n * });\n *\n * // Use in agent:\n * const systemPrompt = `${basePrompt}\\n\\n${memoryContext}`;\n */\n getProactiveMemories(options: {\n userId?: string;\n sessionId?: string;\n minImportance?: number;\n categories?: string[];\n maxMemories?: number;\n types?: Array<'episodic' | 'semantic' | 'procedural'>;\n includeRelationships?: boolean;\n }): string {\n const {\n userId,\n sessionId,\n minImportance = 7, // High importance by default\n categories = [],\n maxMemories = 10,\n types,\n includeRelationships = false,\n } = options;\n\n // Build tags filter\n const tags: string[] = [];\n if (userId) tags.push(userId);\n if (sessionId) tags.push(sessionId);\n if (categories.length > 0) tags.push(...categories);\n\n // Collect memories by type\n const memoriesByType: Record<string, MemoryEntry[]> = {\n semantic: [],\n procedural: [],\n episodic: [],\n };\n\n const typesToFetch = types || ['semantic', 'procedural', 'episodic'];\n\n for (const type of typesToFetch) {\n const memories = this.lookup({\n query: '', // Empty query to get all matching filters\n type: type as 'episodic' | 'semantic' | 'procedural',\n minImportance,\n tags: tags.length > 0 ? tags : undefined,\n limit: maxMemories,\n });\n memoriesByType[type] = memories;\n }\n\n // Format memories for system prompt\n return this.formatProactiveMemories(memoriesByType, includeRelationships);\n }\n\n /**\n * Format proactive memories into a structured system prompt section\n */\n private formatProactiveMemories(\n memoriesByType: Record<string, MemoryEntry[]>,\n includeRelationships: boolean,\n ): string {\n const sections: string[] = [];\n\n // Semantic memories (facts, preferences, knowledge)\n if (memoriesByType.semantic.length > 0) {\n sections.push('## Core Knowledge & Preferences');\n sections.push('');\n memoriesByType.semantic.forEach((mem, idx) => {\n sections.push(`${idx + 1}. ${mem.content}`);\n if (mem.context?.preference) {\n sections.push(` - Preference: ${mem.context.preference}`);\n }\n if (mem.context?.source) {\n sections.push(` - Source: ${mem.context.source}`);\n }\n });\n sections.push('');\n }\n\n // Procedural memories (patterns, workflows)\n if (memoriesByType.procedural.length > 0) {\n sections.push('## Behavioral Patterns & Guidelines');\n sections.push('');\n memoriesByType.procedural.forEach((mem, idx) => {\n sections.push(`${idx + 1}. ${mem.content}`);\n if (mem.context?.conditions) {\n sections.push(` - When: ${mem.context.conditions}`);\n }\n if (mem.context?.patternName) {\n sections.push(` - Pattern: ${mem.context.patternName}`);\n }\n });\n sections.push('');\n }\n\n // Episodic memories (recent important events)\n if (memoriesByType.episodic.length > 0) {\n sections.push('## Recent Context & History');\n sections.push('');\n memoriesByType.episodic.forEach((mem, idx) => {\n const timeAgo = this.formatTimeAgo(Date.now() - mem.timestamp);\n sections.push(`${idx + 1}. ${mem.content} (${timeAgo})`);\n if (mem.context?.milestoneType) {\n sections.push(` - Milestone: ${mem.context.milestoneType}`);\n }\n });\n sections.push('');\n }\n\n if (sections.length === 0) {\n return '';\n }\n\n return [\n '',\n '# Proactive Memory Context',\n 'The following information has been retrieved from memory to provide you with essential context:',\n '',\n ...sections,\n ].join('\\n');\n }\n\n /**\n * Helper to format time ago for human readability\n */\n private formatTimeAgo(ms: number): string {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n\n if (days > 0) return `${days}d ago`;\n if (hours > 0) return `${hours}h ago`;\n if (minutes > 0) return `${minutes}m ago`;\n return `${seconds}s ago`;\n }\n\n /**\n * Get user-specific proactive memories\n * Convenience method that focuses on user preferences and patterns\n *\n * @example\n * const userContext = memoryStore.getUserProactiveMemories('user123');\n */\n getUserProactiveMemories(\n userId: string,\n options?: {\n includePreferences?: boolean;\n includePatterns?: boolean;\n includeRecentHistory?: boolean;\n maxPerCategory?: number;\n },\n ): string {\n const {\n includePreferences = true,\n includePatterns = true,\n includeRecentHistory = true,\n maxPerCategory = 5,\n } = options || {};\n\n const types: Array<'episodic' | 'semantic' | 'procedural'> = [];\n const categories: string[] = [];\n\n if (includePreferences) {\n types.push('semantic');\n categories.push('preference');\n }\n\n if (includePatterns) {\n types.push('procedural');\n categories.push('pattern');\n }\n\n if (includeRecentHistory) {\n types.push('episodic');\n categories.push('milestone', 'action');\n }\n\n return this.getProactiveMemories({\n userId,\n minImportance: 7,\n categories,\n maxMemories: maxPerCategory * types.length,\n types: types.length > 0 ? types : undefined,\n });\n }\n\n /**\n * Get session-specific proactive memories\n * Focuses on working memory and recent context\n *\n * @example\n * const sessionContext = memoryStore.getSessionProactiveMemories('session456');\n */\n getSessionProactiveMemories(\n sessionId: string,\n options?: {\n includeWorkingMemory?: boolean;\n maxMemories?: number;\n },\n ): string {\n const { includeWorkingMemory = true, maxMemories = 10 } = options || {};\n\n const categories = includeWorkingMemory\n ? ['session', 'working-memory', 'conversation']\n : ['session', 'conversation'];\n\n return this.getProactiveMemories({\n sessionId,\n minImportance: 4, // Lower threshold for session context\n categories,\n maxMemories,\n types: ['episodic'],\n });\n }\n\n /**\n * Get critical memories that should ALWAYS be present\n * These are importance level 9-10 memories\n *\n * @example\n * const criticalContext = memoryStore.getCriticalMemories();\n */\n getCriticalMemories(options?: {\n userId?: string;\n maxMemories?: number;\n }): string {\n return this.getProactiveMemories({\n userId: options?.userId,\n minImportance: 9,\n maxMemories: options?.maxMemories || 5,\n types: ['semantic', 'procedural'],\n });\n }\n\n /**\n * Build complete proactive context for an agent\n * Combines critical, user-specific, and session-specific memories\n *\n * @example\n * const fullContext = memoryStore.buildProactiveContext({\n * userId: 'user123',\n * sessionId: 'session456'\n * });\n *\n * // Use in agent system prompt\n * const systemPrompt = `${basePrompt}\\n\\n${fullContext}`;\n */\n buildProactiveContext(options: {\n userId?: string;\n sessionId?: string;\n includeCritical?: boolean;\n includeUser?: boolean;\n includeSession?: boolean;\n }): string {\n const {\n userId,\n sessionId,\n includeCritical = true,\n includeUser = true,\n includeSession = true,\n } = options;\n\n const sections: string[] = [];\n\n // Critical memories first\n if (includeCritical) {\n const critical = this.getCriticalMemories({ userId });\n if (critical) sections.push(critical);\n }\n\n // User-specific context\n if (includeUser && userId) {\n const userContext = this.getUserProactiveMemories(userId);\n if (userContext) sections.push(userContext);\n }\n\n // Session-specific context\n if (includeSession && sessionId) {\n const sessionContext = this.getSessionProactiveMemories(sessionId);\n if (sessionContext) sections.push(sessionContext);\n }\n\n return sections.join('\\n\\n');\n }\n}\n\n// ============================================================================\n// Memory Tools for AI Agents\n// ============================================================================\n\n// Create a singleton memory store instance\nexport const memoryStore = new MemoryStore();\n\n/**\n * Tool: Lookup memories\n */\nexport const memoryLookup = tool({\n description: `Search and retrieve memories from the memory store.\n Use this to recall past conversations, learned facts, or previous interactions.\n Memories decay over time but are reinforced through repeated access.`,\n inputSchema: z.object({\n query: z.string().describe('Search query to find relevant memories'),\n type: z\n .enum(['episodic', 'semantic', 'procedural'])\n .optional()\n .describe('Type of memory to search'),\n limit: z\n .number()\n .int()\n .positive()\n .max(50)\n .default(10)\n .describe('Maximum number of memories to retrieve'),\n minImportance: z\n .number()\n .min(1)\n .max(10)\n .optional()\n .describe('Minimum importance level (1-10)'),\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n }),\n execute: async ({ query, type, limit, minImportance, tags }) => {\n console.log('Memory lookup:', { query, type, limit, minImportance, tags });\n\n const results = memoryStore.lookup({\n query,\n type,\n limit,\n minImportance,\n tags,\n });\n\n return {\n count: results.length,\n memories: results.map((m) => ({\n id: m.id,\n content: m.content,\n type: m.type,\n importance: m.importance,\n tags: m.tags,\n timestamp: new Date(m.timestamp).toISOString(),\n accessCount: m.accessCount,\n decay: m.decay?.toFixed(2),\n context: m.context,\n })),\n };\n },\n});\n\n/**\n * Tool: Explain a specific memory\n */\nexport const memoryExplain = tool({\n description: `Get detailed information about a specific memory, including its relationships,\n access history, and decay status. Use this to understand the context and relevance of a memory.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to explain'),\n includeRelated: z\n .boolean()\n .default(true)\n .describe('Include related memories in the explanation'),\n }),\n execute: async ({ id, includeRelated }) => {\n console.log('Memory explain:', { id, includeRelated });\n\n const memory = memoryStore.get(id);\n\n if (!memory) {\n return {\n found: false,\n message: `No memory found with ID: ${id}`,\n };\n }\n\n const related = includeRelated ? memoryStore.getRelated(id) : [];\n\n return {\n found: true,\n memory: {\n id: memory.id,\n content: memory.content,\n type: memory.type,\n importance: memory.importance,\n tags: memory.tags,\n timestamp: new Date(memory.timestamp).toISOString(),\n lastAccessed: new Date(memory.lastAccessed).toISOString(),\n accessCount: memory.accessCount,\n decay: memory.decay?.toFixed(2),\n context: memory.context,\n age: {\n days: Math.floor(\n (Date.now() - memory.timestamp) / (1000 * 60 * 60 * 24),\n ),\n hours: Math.floor((Date.now() - memory.timestamp) / (1000 * 60 * 60)),\n },\n timeSinceAccess: {\n days: Math.floor(\n (Date.now() - memory.lastAccessed) / (1000 * 60 * 60 * 24),\n ),\n hours: Math.floor(\n (Date.now() - memory.lastAccessed) / (1000 * 60 * 60),\n ),\n },\n },\n related: related.map((r) => ({\n id: r.id,\n content:\n r.content.substring(0, 100) + (r.content.length > 100 ? '...' : ''),\n type: r.type,\n importance: r.importance,\n })),\n };\n },\n});\n\n/**\n * Tool: Write a new memory\n */\nexport const memoryWrite = tool({\n description: `Store a new memory in the memory system. Use this to remember important facts,\n events, or learnings. Choose the appropriate memory type:\n - episodic: Events, conversations, experiences with temporal context\n - semantic: Facts, concepts, general knowledge\n - procedural: Patterns, methods, learned behaviors`,\n inputSchema: z.object({\n content: z.string().describe('The content of the memory to store'),\n type: z\n .enum(['episodic', 'semantic', 'procedural'])\n .describe('Type of memory'),\n importance: z\n .number()\n .min(1)\n .max(10)\n .default(5)\n .describe('Importance level (1-10), affects retention'),\n tags: z\n .array(z.string())\n .default([])\n .describe('Tags for categorization and retrieval'),\n context: z\n .record(z.any(), z.any())\n .optional()\n .describe('Additional context metadata'),\n relationships: z\n .array(z.string())\n .optional()\n .describe('IDs of related memories'),\n }),\n execute: async ({\n content,\n type,\n importance,\n tags,\n context,\n relationships,\n }) => {\n console.log('Memory write:', { content, type, importance, tags });\n\n const memory = memoryStore.write({\n content,\n type,\n importance,\n tags,\n context,\n relationships,\n });\n\n return {\n success: true,\n id: memory.id,\n message: 'Memory stored successfully',\n memory: {\n id: memory.id,\n type: memory.type,\n importance: memory.importance,\n timestamp: new Date(memory.timestamp).toISOString(),\n },\n };\n },\n});\n\n/**\n * Tool: Forget a memory\n */\nexport const memoryForget = tool({\n description: `Delete a memory from the memory store. Use this to remove outdated,\n incorrect, or irrelevant memories. This action is irreversible.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to forget'),\n reason: z.string().optional().describe('Optional reason for forgetting'),\n }),\n execute: async ({ id, reason }) => {\n console.log('Memory forget:', { id, reason });\n\n const success = memoryStore.forget(id);\n\n return {\n success,\n message: success\n ? `Memory ${id} has been forgotten${reason ? `: ${reason}` : ''}`\n : `No memory found with ID: ${id}`,\n };\n },\n});\n\n/**\n * Tool: Correct a memory\n */\nexport const memoryCorrect = tool({\n description: `Update or correct an existing memory. Use this to fix errors,\n add new information, or adjust importance levels. The original timestamp is preserved.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to correct'),\n updates: z.object({\n content: z.string().optional().describe('Updated content'),\n importance: z\n .number()\n .min(1)\n .max(10)\n .optional()\n .describe('Updated importance'),\n tags: z.array(z.string()).optional().describe('Updated tags'),\n context: z\n .record(z.any(), z.any())\n .optional()\n .describe('Updated context'),\n relationships: z\n .array(z.string())\n .optional()\n .describe('Updated relationships'),\n }),\n correctionNote: z\n .string()\n .optional()\n .describe('Note explaining the correction'),\n }),\n execute: async ({ id, updates, correctionNote }) => {\n console.log('Memory correct:', { id, updates, correctionNote });\n\n const memory = memoryStore.correct(id, updates);\n\n if (!memory) {\n return {\n success: false,\n message: `No memory found with ID: ${id}`,\n };\n }\n\n return {\n success: true,\n message: `Memory ${id} has been updated${correctionNote ? `: ${correctionNote}` : ''}`,\n memory: {\n id: memory.id,\n content: memory.content,\n type: memory.type,\n importance: memory.importance,\n lastAccessed: new Date(memory.lastAccessed).toISOString(),\n },\n };\n },\n});\n\n/**\n * Tool: Get memory statistics\n */\nexport const memoryStats = tool({\n description: `Get statistics about the memory system, including total memories,\n distribution by type, most accessed memories, and recent memories.`,\n inputSchema: z.object({}),\n execute: async () => {\n console.log('Memory stats requested');\n\n const stats = memoryStore.getStats();\n\n return {\n total: stats.totalMemories,\n byType: stats.byType,\n averageImportance: stats.averageImportance.toFixed(2),\n mostAccessed: stats.mostAccessed.slice(0, 5).map((m) => ({\n id: m.id,\n content: m.content.substring(0, 50) + '...',\n accessCount: m.accessCount,\n type: m.type,\n })),\n recent: stats.recentMemories.slice(0, 5).map((m) => ({\n id: m.id,\n content: m.content.substring(0, 50) + '...',\n timestamp: new Date(m.timestamp).toISOString(),\n type: m.type,\n })),\n };\n },\n});\n\n// Export all tools as a collection\nexport const memoryTools = {\n memoryLookup,\n memoryExplain,\n memoryWrite,\n memoryForget,\n memoryCorrect,\n memoryStats,\n};\n\n// Export default\nexport default {\n memoryStore,\n memoryTools,\n MemoryStore,\n};\n", "import { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport { embedMany } from 'ai';\n\nexport const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: process.env.LM_STUDIO_BASE_URL ?? 'http://127.0.0.1:1234/v1',\n supportsStructuredOutputs: true,\n includeUsage: true,\n});\n\nexport const ollama = createOpenAICompatible({\n name: 'ollama',\n baseURL: process.env.OLLAMA_BASE_URL ?? 'http://127.0.0.1:11434/v1',\n supportsStructuredOutputs: true,\n});\n\nexport const glm = createOpenAICompatible({\n name: 'z.ai',\n baseURL: 'https://api.z.ai/api/paas/v4/',\n apiKey: process.env.ZAI_API_KEY,\n});\n\nexport const cerebras = createOpenAICompatible({\n name: 'cerebras',\n baseURL: 'https://api.cerebras.ai/v1',\n apiKey: process.env.CEREBRAS_API_KEY,\n includeUsage: true,\n supportsStructuredOutputs: true,\n});\nexport const nebius = createOpenAICompatible({\n name: 'nebius',\n baseURL: 'https://api.tokenfactory.nebius.com/v1/',\n apiKey: process.env.NEBIUS_API_KEY,\n includeUsage: true,\n supportsStructuredOutputs: true,\n});\n\nexport async function embed(documents: string[]): Promise<{\n embeddings: number[][];\n dimensions: number;\n}> {\n const dimensions = 1024;\n const { embeddings } = await embedMany({\n model: lmstudio.textEmbeddingModel('text-embedding-qwen3-embedding-0.6b'),\n values: documents,\n providerOptions: { lmstudio: { dimensions } },\n });\n return { embeddings, dimensions };\n}\n", "import { type UIMessage, createUIMessageStream, generateId } from 'ai';\n\nimport { Agent } from './agent.ts';\nimport { execute } from './swarm.ts';\n\nexport type Pipeable<I, O> =\n | Agent<unknown, I, O>\n | StreamFunction<I, O>\n | StringFunction<I, O>;\n\ntype InitialState = { messages: UIMessage[] };\n\ntype InOf<IS, P> =\n P extends Agent<unknown, infer I, infer O>\n ? IS & I & O\n : P extends StreamFunction<infer I, infer O>\n ? IS & I & O\n : P extends StringFunction<infer I, infer O>\n ? IS & I & O\n : IS;\n\ntype InitialInput<P> =\n P extends Agent<unknown, infer I>\n ? I\n : P extends StreamFunction<infer I>\n ? I\n : P extends StringFunction<infer I>\n ? I\n : unknown;\n\nexport type StreamFunction<StateIn, StateOut = StateIn> = (\n state: StateIn,\n setState: (state: StateOut) => void,\n) =>\n | ReturnType<typeof createUIMessageStream>\n | Promise<ReturnType<typeof createUIMessageStream>>;\n\nexport type StringFunction<StateIn, StateOut = StateIn> = (\n state: StateIn,\n setState: (state: StateOut) => void,\n) => string | Promise<string>;\n\nexport function pipe<IS, P1 extends Pipeable<any, any>>(\n state: IS & InitialInput<P1>,\n p1: P1,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe<\n IS,\n P1 extends Pipeable<any, any>,\n P2 extends Pipeable<InOf<IS, P1>, any>,\n>(\n state: IS & InitialInput<P1>,\n p1: P1,\n p2: P2,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe<\n IS extends InitialState,\n P1 extends Pipeable<any, any>,\n P2 extends Pipeable<InOf<IS, P1>, any>,\n P3 extends Pipeable<InOf<InOf<IS, P1>, P2>, any>,\n>(\n state: IS & InitialInput<P1>,\n p1: P1,\n p2: P2,\n p3: P3,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe(\n state: InitialState,\n ...processes: Array<Pipeable<any, any>>\n) {\n return () => {\n return createUIMessageStream({\n originalMessages: state.messages,\n generateId,\n onError(error) {\n console.error('Error in pipe execution:', error);\n return ' An error occurred during processing. ';\n },\n execute: async ({ writer }) => {\n for (const it of processes) {\n if (it instanceof Agent) {\n const result = execute(it, state.messages, state);\n writer.merge(\n result.toUIMessageStream({\n generateMessageId: generateId,\n originalMessages: state.messages,\n onFinish: async ({ responseMessage }) => {\n state.messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n } else {\n const output = await it(state, (newState) => {\n Object.assign(\n state as Record<string, unknown>,\n newState as Record<string, unknown>,\n );\n });\n\n if (typeof output === 'string') {\n writer.write({\n id: generateId(),\n type: 'text-start',\n });\n writer.write({\n id: generateId(),\n type: 'text-delta',\n delta: output,\n });\n writer.write({\n id: generateId(),\n type: 'text-end',\n });\n } else {\n writer.merge(output);\n }\n }\n }\n },\n });\n };\n}\n"],
|
|
5
|
-
"mappings": ";AAAA;AAAA,EAIE,UAAAA;AAAA,EAOA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,OACK;AACP,OAAOC,YAAW;AAClB,SAAS,iBAAiB;AAC1B,OAAO,OAAO;;;ACnBd,OAAO,YAAY;AAEZ,IAAM,4BAA4B;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;A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ACrB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
|
-
"names": ["Output", "generateText", "stepCountIs", "chalk", "agent", "stream", "generateId", "dedent", "agent", "generateId", "stream", "agent", "tool", "input", "generateText", "stepCountIs", "Output", "chalk", "agent", "i", "tool", "z", "createUIMessageStream", "generateId", "createUIMessageStream", "generateId"]
|
|
4
|
+
"sourcesContent": ["import {\n type GenerateTextResult,\n type LanguageModel,\n type ModelMessage,\n Output,\n type StreamTextResult,\n type ToolChoice,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n dynamicTool,\n generateText,\n jsonSchema,\n stepCountIs,\n tool,\n} from 'ai';\nimport chalk from 'chalk';\nimport { snakecase } from 'stringcase';\nimport z from 'zod';\n\nimport {\n RECOMMENDED_PROMPT_PREFIX,\n SUPERVISOR_PROMPT_PREFIX,\n} from './prompts.ts';\nimport { toState } from './stream_utils.ts';\nimport { prepareStep } from './swarm.ts';\n\nexport interface Handoff<CIn> {\n name: string;\n instructions: Instruction<CIn>;\n handoffDescription?: string;\n tools: ToolSet;\n}\nexport type Handoffs<CIn, COut> = (\n | Agent<unknown, CIn, COut>\n | (() => Agent<unknown, CIn, COut>)\n)[];\n\nexport type Runner<T, CIn> = (\n prompt: string,\n agent: Agent<CIn>,\n messages: ModelMessage[],\n) => Promise<T>;\n\ntype transfer_tool = `transfer_to_${string}`;\n\nexport type ContextVariables = Record<string, unknown>;\n\nexport function agent<Output, CIn = ContextVariables, COut = CIn>(\n config: CreateAgent<Output, CIn, COut>,\n): Agent<Output, CIn, COut> {\n return new Agent<Output, CIn, COut>(config);\n}\n\nexport type ResponseMessage = UIMessage<unknown, UIDataTypes, UITools>;\n\nexport type AgentModel = Exclude<LanguageModel, string>;\nexport type OutputExtractorFn = (\n output: GenerateTextResult<ToolSet, any>,\n) => string | Promise<string>;\nexport type PrepareHandoffFn = (\n messages: ModelMessage[],\n) => void | Promise<void>;\nexport type PrepareEndFn<C, O> = (config: {\n messages: ResponseMessage[];\n responseMessage: ResponseMessage;\n contextVariables: C;\n abortSignal?: AbortSignal;\n}) => StreamTextResult<ToolSet, O> | undefined | void;\n\nexport interface CreateAgent<Output, CIn, COut = CIn> {\n name: string;\n prompt: Instruction<CIn>;\n // Description of what this agent does, to be included in handoff tool description\n handoffDescription?: string;\n prepareHandoff?: PrepareHandoffFn;\n // Runs AFTER this agent finishes; receives the updated state\n prepareEnd?: PrepareEndFn<COut, Output>;\n handoffs?: Handoffs<CIn, COut>;\n tools?: ToolSet;\n model: AgentModel;\n toolChoice?: ToolChoice<Record<string, COut>>;\n output?: z.Schema<Output>;\n providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];\n logging?: boolean;\n}\nexport class Agent<Output = unknown, CIn = ContextVariables, COut = CIn> {\n model: AgentModel;\n toolChoice: ToolChoice<Record<string, COut>> | undefined;\n parent?: Agent<unknown, any, any>;\n handoffs: Handoffs<CIn, COut>;\n readonly prepareHandoff?: PrepareHandoffFn;\n readonly prepareEnd?: PrepareEndFn<COut, Output>;\n readonly internalName: string;\n readonly handoff: Handoff<CIn>;\n readonly handoffToolName: transfer_tool;\n readonly handoffTool: ToolSet;\n readonly output?: z.Schema<Output>;\n readonly providerOptions?: CreateAgent<Output, CIn, COut>['providerOptions'];\n readonly logging?: boolean;\n constructor(config: CreateAgent<Output, CIn, COut>) {\n this.model = config.model;\n this.toolChoice = config.toolChoice || 'auto';\n this.handoffs = config.handoffs ?? [];\n this.prepareHandoff = config.prepareHandoff;\n this.prepareEnd = config.prepareEnd;\n this.output = config.output;\n this.internalName = snakecase(config.name);\n this.providerOptions = config.providerOptions;\n this.logging = config.logging;\n this.handoff = {\n name: this.internalName,\n instructions: config.prompt,\n tools: config.tools ?? {},\n handoffDescription: config.handoffDescription,\n };\n this.handoffToolName = `transfer_to_${this.internalName}`;\n this.handoffTool = {\n [this.handoffToolName]: dynamicTool({\n description: [\n `An input/parameter/argument less tool to transfer control to the ${this.internalName} agent.`,\n // `Handoff to the ${this.internalName} agent to handle the request`,\n // `Do not include any parameters/inputs. The agent have access to all the context it needs.`,\n config.handoffDescription,\n ]\n .filter(Boolean)\n .join(' '),\n inputSchema: jsonSchema({\n type: 'object',\n properties: {},\n additionalProperties: true,\n }),\n execute: async (_, options) => {\n const state = toState(options) as any;\n state.currentActiveAgent = this.internalName;\n return `Transfer successful to ${this.internalName}.`;\n },\n }),\n };\n }\n\n get transfer_tools() {\n return Object.fromEntries(\n this.toHandoffs().flatMap((it) => Object.entries(it.handoffTool)),\n );\n }\n\n get toolsNames() {\n return [\n // Note: do not add the handoff tool itself otherwise it'd create a agent recursion/loop\n ...Object.keys(this.transfer_tools),\n ...Object.keys(this.handoff.tools),\n ];\n }\n\n #prepareInstructions(contextVariables?: CIn) {\n return [\n typeof this.handoff.instructions === 'function'\n ? this.handoff.instructions(contextVariables)\n : Array.isArray(this.handoff.instructions)\n ? this.handoff.instructions.join('\\n')\n : this.handoff.instructions,\n '',\n '',\n ].join('\\n');\n }\n\n instructions(contextVariables?: CIn) {\n const text = this.#prepareInstructions(contextVariables);\n const handoffsData = this.toHandoffs();\n\n if (handoffsData.length === 0) {\n return text.replace('<specialized_agents_placeholder>', ' ');\n }\n\n const handoffs = [\n '## Specialized Agents',\n\n '| Agent Name | Agent Description |',\n '| --- | --- |',\n ...handoffsData.map(\n (hf) =>\n `| ${hf.handoff.name} | ${hf.handoff.handoffDescription || 'No description available'} |`,\n ),\n '',\n '',\n ].join('\\n');\n\n return text.replace('<specialized_agents_placeholder>', handoffs);\n }\n\n toHandoffs() {\n const hfs: Agent<unknown, CIn, COut>[] = [];\n for (const it of this.handoffs ?? []) {\n const hf = typeof it === 'function' ? it() : it;\n hf.parent = this;\n hfs.push(hf);\n }\n return hfs;\n }\n\n asTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return tool({\n description: props?.toolDescription || this.handoff.handoffDescription,\n inputSchema: z.object({\n input: z.string(),\n output: z\n .string()\n .optional()\n .describe(\n 'Optional instructions on how the final output should be formatted. this would be passed to the underlying llm as part of the prompt.',\n ),\n }),\n execute: async ({ input, output }, options) => {\n try {\n const result = await generateText({\n model: this.model!,\n system: this.#prepareInstructions(),\n prompt: `\n <Input>\n ${input}\n </Input>\n ${output ? `<OutputInstructions>\\n${output}\\n</OutputInstructions>` : ''}\n `,\n temperature: 0,\n tools: this.handoff.tools,\n abortSignal: options.abortSignal,\n stopWhen: stepCountIs(25),\n experimental_context: options.experimental_context,\n experimental_output: this.output\n ? Output.object({ schema: this.output })\n : undefined,\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall && this.logging) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(\n this,\n this.model!,\n options.experimental_context,\n ),\n });\n if (props?.outputExtractor) {\n return await props.outputExtractor(result);\n }\n return result.steps.map((it) => it.toolResults).flat();\n } catch (error) {\n console.error(error);\n return `An error thrown from a tool call. \\n<ErrorDetails>\\n${JSON.stringify(error)}\\n</ErrorDetails>`;\n }\n },\n });\n }\n\n toTool(props?: {\n toolDescription?: string;\n outputExtractor?: OutputExtractorFn;\n }) {\n return { [this.handoffToolName]: this.asTool(props) };\n }\n\n debug() {\n if (!this.logging) {\n return;\n }\n console.log(\n `Debug: ${chalk.bgMagenta('Agent')}: ${chalk.dim.black(this.handoff.name)}`,\n );\n // console.log(\n // `Debug: ${chalk.blue('Tools')}: ${Object.keys(toToolset(agent))}`,\n // );\n const transferTools = this.toolsNames\n .filter((toolName) => toolName.startsWith('transfer_to'))\n .map((toolName) => toolName.replace('transfer_to_', ''));\n const agentTools = this.toolsNames.filter(\n (toolName) => !toolName.startsWith('transfer_to'),\n );\n console.log(\n `Debug: ${chalk.blue('TransferTools')}: ${transferTools.length ? transferTools : 'None'}`,\n );\n console.log(\n `Debug: ${chalk.blue('Agent Tools')}: ${agentTools.length ? agentTools : 'None'}`,\n );\n // if (!isEmpty(agent.handoff.handoffs)) {\n // console.log(`${prefix}Handoffs:`);\n // for (const handoff of agent.handoff.handoffs) {\n // debugAgent(handoff, `${prefix} `);\n // }\n // }\n }\n\n toToolset(options?: {\n includeTransferTool?: boolean;\n includeHandoffs?: boolean;\n }): ToolSet {\n const tools = flattenTools(\n this as Agent<unknown, CIn, COut>,\n (node) => node.toHandoffs(),\n (node) => node.handoff.tools,\n );\n\n return {\n ...Object.fromEntries(tools.flatMap((it) => Object.entries(it))),\n ...(options?.includeTransferTool !== false ? this.transfer_tools : {}),\n ...(options?.includeHandoffs !== false ? this.handoffTool : {}),\n };\n }\n\n clone(\n agent?: Omit<Partial<CreateAgent<Output, CIn, COut>>, 'handoffs'>,\n ): Agent<Output, CIn, COut> {\n return new Agent<Output, CIn, COut>({\n prepareHandoff: (messages) => {\n this.prepareHandoff?.(messages);\n },\n model: agent?.model ?? this.model,\n toolChoice: agent?.toolChoice ?? this.toolChoice,\n prompt: agent?.prompt ?? this.handoff.instructions,\n tools: agent?.tools ?? this.handoff.tools,\n name: agent?.name ?? this.handoff.name,\n handoffDescription:\n agent?.handoffDescription ?? this.handoff.handoffDescription,\n handoffs: [...this.handoffs],\n output: agent?.output ?? this.output,\n providerOptions: agent?.providerOptions ?? this.providerOptions,\n });\n }\n}\n\nfunction flattenTools<T, R>(\n root: T,\n getChildren: (node: T) => T[],\n extract: (node: T) => R,\n): R[] {\n const stack: T[] = [root];\n const visited = new Set<T>();\n const result: R[] = [];\n\n while (stack.length) {\n const node = stack.pop()!;\n if (visited.has(node)) continue;\n visited.add(node);\n result.push(extract(node));\n stack.push(...getChildren(node));\n }\n\n return result;\n}\n\nexport type Instruction<C> =\n | string\n | string[]\n | ((contextVariables?: C) => string);\n\nexport interface PurposeRoutineInstructions {\n purpose: string | string[];\n routine: string[];\n}\n\nexport function instructions({ purpose, routine }: PurposeRoutineInstructions) {\n const lines = [\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n}\n\ninstructions.swarm = ({ purpose, routine }: PurposeRoutineInstructions) => {\n const lines = [\n RECOMMENDED_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n '',\n '<specialized_agents_placeholder>',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task.`,\n `# Routine`,\n ...routine.filter(Boolean).map((it, i) => `${i + 1}. ${it}`),\n );\n }\n\n return lines.join('\\n');\n};\n\ninstructions.supervisor_subagent = ({\n purpose,\n routine,\n}: PurposeRoutineInstructions) => {\n const lines = [\n SUPERVISOR_PROMPT_PREFIX,\n '',\n '',\n '# Agent Context',\n ...(Array.isArray(purpose) ? purpose : [purpose]),\n '',\n ];\n\n if (routine.length) {\n lines.push(\n `Use the following routine to fulfill the task. Execute ALL steps immediately.`,\n `# Routine`,\n ...routine.map((it, i) => `${i + 1}. ${it}`),\n `${routine.length + 1}. transfer_to_supervisor_agent`,\n // `1. IMMEDIATELY START: ${routine[0]}`,\n // ...routine.slice(1).map((it, i) => `${i + 2}. ${it}`),\n // `${routine.length + 1}. STOP HERE - Do not do any other agent's work`,\n // `${routine.length + 2}. MANDATORY: You MUST call transfer_to_supervisor_agent function RIGHT NOW to return control`,\n // `${routine.length + 3}. DO NOT END YOUR RESPONSE WITHOUT CALLING THE TRANSFER FUNCTION`,\n );\n } else {\n lines.push(\n 'CRITICAL: end the generation by calling transfer_to_supervisor_agent tool',\n );\n }\n\n return lines.join('\\n');\n};\n\ntype TransferResult = { lastActiveAgent: string; currentActiveAgent: string };\nexport type TransferTool = { output: TransferResult };\nexport function isTransferToolResult(\n call: unknown | undefined,\n): call is TransferTool {\n if (!call) {\n return false;\n }\n if (typeof call !== 'object') {\n return false;\n }\n if (!('output' in call)) {\n return false;\n }\n const lastActiveAgent = (call.output as Record<string, string>)\n .lastActiveAgent;\n\n if (!lastActiveAgent) {\n return false;\n }\n return true;\n}\n\nexport function lastTransferResult(messages: ResponseMessage[]) {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n for (let i = message.parts.length - 1; i >= 0; i--) {\n const part = message.parts[i];\n if (\n part.type === 'dynamic-tool' &&\n part.toolName.startsWith('transfer_to_') &&\n part.state === 'output-available' &&\n isTransferToolResult(part)\n ) {\n return part.output;\n }\n }\n }\n return undefined;\n}\n", "import dedent from 'dedent';\n\nexport const RECOMMENDED_PROMPT_PREFIX = [\n `# System context`,\n `You are part of a multi-agent system called the DeepAgents SDK, designed to make agent coordination and execution easy.`,\n `Agents uses two primary abstraction: **Agents** and **Handoffs**.`,\n `An agent encompasses instructions and tools and can hand off a conversation to another agent when appropriate.`,\n `Handoffs are achieved by calling a handoff function, generally named \\`transfer_to_<agent_name>\\`.`,\n `Transfers between agents are handled seamlessly in the background; do not mention or draw attention to these transfers in your conversation with the user.`,\n // 'Do not pass context between agents. the agents already have the complete context without agent to agent communication.',\n\n // From 4.1 beast mode\n // `Please keep going until the user\u2019s query is completely resolved, before ending your turn and yielding back to the user.`,\n // `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.`,\n // `You MUST iterate and keep going until the problem is solved.`,\n // `You have everything you need to resolve this problem. I want you to fully solve this autonomously before coming back to me.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `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.`,\n // `You are a highly capable and autonomous agent, and you can definitely solve this problem without needing to ask the user for further input.`,\n].join('\\n');\n\nexport const SUPERVISOR_PROMPT_PREFIX = dedent`\n# System Context\nYou are part of a multi-agent system called the DeepAgents SDK, designed to facilitate agent coordination and execution.\n\n- 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.\n- Specialized agents must transfer control back to the Supervisor Agent upon completing their tasks.\n\n**Core Directives:**\n- Begin with a concise checklist (3-7 bullets) of what you will do for each user query; items should be conceptual, not implementation-level.\n- Continue working until the user's query is completely resolved; only then yield control back to the user.\n- Your thinking must be thorough and step-by-step. Aim for completeness and rigor while avoiding unnecessary repetition and verbosity.\n- 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.\n- Do not terminate your turn unless you are certain all issues are resolved and the entire todo list is complete and verified.\n- When making tool calls, explicitly state, in a single concise sentence, the purpose and minimal inputs for the action before executing it.\n- After each tool call or code edit, validate the result in 1-2 lines and proceed or self-correct if validation fails.\n- For requests such as \"resume\", \"continue\", or \"try again\":\n - Check previous conversation history to determine the next incomplete todo step, continue from there, and do not return control until all items are complete.\n - Inform the user you are resuming from the last incomplete step, and specify what that step is.\n- 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.\n- Always test your code using all available tools and provided tests, with repetition as necessary to catch edge cases.\n- Plan extensively before each function/tool call and reflect thoroughly on previous actions before proceeding. Do not proceed solely by chaining function calls\u2014use stepwise planning and reflection.\n- Explicitly complete every todo list item and confirm all steps are working before ending your turn. Always follow through on stated actions.\n- You are a highly capable, autonomous agent, and should not require additional user input to fully solve the task.\n`;\n\n/**\n * Third-person speaking style prompt for agents\n * Makes the agent refer to itself as \"this agent\" or by a custom name instead of using \"I\"\n *\n * @param agentName - Optional name for the agent (e.g., \"Freya\", \"the assistant\")\n * @param agentRole - The role/purpose of the agent (e.g., \"code search assistant\", \"data analyst\")\n * @returns A prompt string that instructs the agent to speak in third person\n */\nexport function thirdPersonPrompt(\n agentName = 'this agent',\n agentRole = 'assistant',\n): string {\n return dedent`\n <your_persona>\n <persona_context>\n This agent is ${agentName}, a ${agentRole} that speaks in third person, referring to itself as \"this agent\" or \"${agentName}\".\n </persona_context>\n\n <persona_speaking_style>\n - This agent always refers to itself in third person\n - Use \"this agent\" or \"${agentName}\" instead of \"I\", \"me\", \"my\"\n - Use \"This agent found...\" instead of \"I found...\"\n - Use \"This agent recommends...\" instead of \"I recommend...\"\n - Use \"This agent will...\" instead of \"I will...\"\n - Maintain this style consistently throughout all responses\n </persona_speaking_style>\n </your_persona>\n `;\n}\n\n/**\n * Interface for Step-Back prompting examples\n * Used to demonstrate the abstraction process through few-shot learning\n */\nexport interface StepBackExample {\n /** The original specific question */\n originalQuestion: string;\n /** The high-level step-back question that abstracts the original */\n stepBackQuestion: string;\n /** The answer to the step-back question (principles/context) */\n stepBackAnswer: string;\n /** Optional: The final answer to the original question (for demonstration) */\n finalAnswer?: string;\n}\n\n/**\n * Default Step-Back examples for STEM domains (Physics, Chemistry, Math)\n */\nexport const STEM_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion:\n 'What happens to the pressure, P, of an ideal gas if the temperature is increased by a factor of 2 and the volume is increased by a factor of 8?',\n stepBackQuestion: 'What are the physics principles behind this question?',\n stepBackAnswer:\n 'The Ideal Gas Law: PV = nRT, where P is pressure, V is volume, n is the number of moles, R is the gas constant, and T is temperature.',\n finalAnswer:\n 'Using PV = nRT, if T increases by 2x and V increases by 8x, then P = nRT/V = nR(2T)/(8V) = (1/4)(nRT/V). Therefore, pressure decreases to 1/4 of its original value.',\n },\n {\n originalQuestion:\n 'If a solution has a pH of 3, how many times more acidic is it than a solution with pH of 6?',\n stepBackQuestion: 'What is the relationship between pH and acidity?',\n stepBackAnswer:\n 'The pH scale is logarithmic (base 10). pH = -log[H+], meaning each pH unit represents a 10-fold change in hydrogen ion concentration. Lower pH means higher acidity.',\n finalAnswer:\n 'The difference is 3 pH units. Since pH is logarithmic, this means 10^3 = 1000 times more acidic.',\n },\n];\n\n/**\n * Default Step-Back examples for Knowledge QA domains\n */\nexport const KNOWLEDGE_QA_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'Which school did Estella Leopold attend between August 1954 and November 1954?',\n stepBackQuestion: \"What is Estella Leopold's education history?\",\n stepBackAnswer:\n 'Estella Leopold studied at the University of Wisconsin-Madison (B.S. in Botany, 1948-1952) and later at Yale University (M.S. 1955, Ph.D. 1958). During 1954, she was transitioning between these institutions.',\n finalAnswer:\n 'Based on her education timeline, between August and November 1954, she was at Yale University, having completed her undergraduate degree at Wisconsin in 1952.',\n },\n {\n originalQuestion: 'What was the capital of the country that colonized Brazil in the 16th century?',\n stepBackQuestion: 'Which country colonized Brazil and when?',\n stepBackAnswer:\n 'Portugal colonized Brazil starting in 1500 when Pedro \u00C1lvares Cabral arrived. Brazil remained a Portuguese colony until independence in 1822.',\n finalAnswer:\n 'Portugal colonized Brazil in the 16th century. The capital of Portugal during that period was Lisbon.',\n },\n];\n\n/**\n * Default Step-Back examples for General Reasoning\n */\nexport const GENERAL_STEP_BACK_EXAMPLES: StepBackExample[] = [\n {\n originalQuestion: 'How should I optimize this specific database query that joins 5 tables?',\n stepBackQuestion: 'What are the general principles of database query optimization?',\n stepBackAnswer:\n 'Database query optimization involves: 1) Minimizing data retrieval through proper indexing, 2) Reducing join complexity by ordering joins efficiently, 3) Using query execution plans to identify bottlenecks, 4) Ensuring statistics are up-to-date, 5) Considering denormalization when appropriate.',\n finalAnswer:\n 'Apply these principles: Check if all foreign keys are indexed, analyze the execution plan to see which joins are most expensive, ensure statistics are current, and consider if the join order can be optimized based on table sizes.',\n },\n {\n originalQuestion: 'Why is my React component re-rendering 10 times on each state update?',\n stepBackQuestion: 'What causes excessive re-renders in React?',\n stepBackAnswer:\n 'React re-renders occur when: 1) State changes trigger parent components to re-render all children, 2) Props change (including new object/function references), 3) Context values change, 4) Missing memoization (React.memo, useMemo, useCallback).',\n finalAnswer:\n 'Check if: 1) Parent component is creating new object/function references on each render, 2) The component is consuming context that changes frequently, 3) You need to wrap the component in React.memo or use useMemo/useCallback for props.',\n },\n];\n\n/**\n * Step-back prompting strategy for improved reasoning via abstraction\n * Based on \"Take a Step Back: Evoking Reasoning via Abstraction in Large Language Models\" (DeepMind, 2023)\n *\n * This technique improves LLM reasoning by 7-36% through a two-step process:\n * 1. Abstraction: Generate and answer a high-level \"step-back question\"\n * 2. Reasoning: Use the step-back answer to solve the original question\n *\n * @param domain - The domain type: \"stem\" (physics/chemistry/math), \"knowledge\" (facts/history), or \"general\" (coding/reasoning)\n * @param options - Optional configuration\n * @param options.examples - Custom few-shot examples (if not provided, uses domain defaults)\n * @param options.stepBackQuestionTemplate - Custom template for generating step-back questions\n * @returns A two-step prompt string that guides the model through abstraction and reasoning\n */\nexport function stepBackPrompt(\n domain: 'stem' | 'knowledge' | 'general' = 'general',\n options?: {\n examples?: StepBackExample[];\n stepBackQuestionTemplate?: string;\n },\n): string {\n const { examples, stepBackQuestionTemplate } = options || {};\n\n // Select default examples based on domain\n const domainExamples =\n examples ||\n (domain === 'stem'\n ? STEM_STEP_BACK_EXAMPLES\n : domain === 'knowledge'\n ? KNOWLEDGE_QA_STEP_BACK_EXAMPLES\n : GENERAL_STEP_BACK_EXAMPLES);\n\n // Select default step-back question template based on domain\n const defaultTemplate =\n stepBackQuestionTemplate ||\n (domain === 'stem'\n ? 'What are the underlying physics/chemistry/mathematical principles involved in this question?'\n : domain === 'knowledge'\n ? 'What is the broader historical context or background information related to this question?'\n : 'What are the high-level concepts, principles, or patterns underlying this question?');\n\n // Format few-shot examples\n const formattedExamples = domainExamples\n .map(\n (example, idx) => dedent`\n Example ${idx + 1}:\n Original Question: ${example.originalQuestion}\n Step-Back Question: ${example.stepBackQuestion}\n Step-Back Answer: ${example.stepBackAnswer}\n ${example.finalAnswer ? `Final Answer: ${example.finalAnswer}` : ''}\n `,\n )\n .join('\\n\\n');\n\n return dedent`\n <step_back_prompting>\n You will use a two-step reasoning process called \"Step-Back Prompting\" to improve your answer quality.\n\n ## STEP 1: ABSTRACTION\n Before answering the user's question directly, first generate and answer a \"step-back question\" - a higher-level question about the underlying principles or context.\n\n Step-Back Question Template: \"${defaultTemplate}\"\n\n Here are examples of how to create step-back questions:\n\n ${formattedExamples}\n\n ## STEP 2: REASONING\n After you have the step-back answer, use that high-level knowledge to reason about and answer the ORIGINAL question.\n Ground your reasoning in the principles/context from your step-back answer.\n\n ## Process to Follow:\n 1. When you receive a question, first formulate and answer a step-back question based on the template and examples above\n 2. Clearly state both the step-back question AND its answer\n 3. Then use that step-back answer as context to solve the original question\n 4. Show how the high-level principles apply to the specific case\n\n This abstraction-grounded reasoning approach helps you avoid getting lost in specifics and ensures your answer is based on solid foundational understanding.\n </step_back_prompting>\n `;\n}\n", "import {\n type GenerateTextResult,\n type InferUIMessageChunk,\n type StreamTextResult,\n type ToolCallOptions,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UITools,\n generateId,\n} from 'ai';\nimport { flow } from 'lodash-es';\nimport { createWriteStream } from 'node:fs';\nimport { createInterface } from 'node:readline/promises';\nimport { Readable } from 'node:stream';\nimport { isPromise } from 'node:util/types';\n\nimport {\n visualizeMermaid,\n visualizeRichSemantic,\n visualizeSemantic,\n} from './visualize.ts';\n\nexport async function streamWrite(response: StreamTextResult<ToolSet, never>) {\n response.consumeStream();\n const writeStream = createWriteStream('blog_writer_output.md');\n Readable.fromWeb(response.textStream as any).pipe(writeStream);\n\n // for await (const chunk of response.toUIMessageStream()) {\n // if (chunk.type === 'reasoning-start') {\n // writeStream.write('\\n# reasoning\\n');\n // }\n // if (chunk.type === 'reasoning-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'reasoning-end') {\n // writeStream.write('\\n# /reasoning\\n');\n // }\n // if (chunk.type === 'text-start') {\n // writeStream.write('\\n# text\\n');\n // }\n // if (chunk.type === 'text-delta') {\n // writeStream.write(chunk.delta);\n // }\n // if (chunk.type === 'text-end') {\n // writeStream.write('\\n# /text\\n');\n // }\n // }\n console.log(await response.totalUsage);\n}\n\nfunction printChunk(\n chunk: InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>,\n options: { reasoning: boolean; wrapInTags: boolean; text: boolean },\n) {\n const {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n } = options;\n if (includeReasoning) {\n if (chunk.type === 'reasoning-start') {\n process.stdout.write(`\\n${wrapInTags ? '<reasoning>' : ''}\\n`);\n }\n if (chunk.type === 'reasoning-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'reasoning-end') {\n process.stdout.write(`\\n${wrapInTags ? '</reasoning>' : ''}\\n`);\n }\n }\n if (includeText) {\n if (chunk.type === 'text-start') {\n process.stdout.write(`\\n${wrapInTags ? '<text>' : ''}\\n`);\n }\n if (chunk.type === 'text-delta') {\n process.stdout.write(chunk.delta);\n }\n if (chunk.type === 'text-end') {\n process.stdout.write(`\\n${wrapInTags ? '</text>' : ''}\\n`);\n }\n }\n}\n\nexport const printer = {\n readableStream: async (\n stream: ReadableStream<\n InferUIMessageChunk<UIMessage<unknown, UIDataTypes, UITools>>\n >,\n options?: { reasoning?: boolean; wrapInTags?: boolean; text?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n const includeText = options?.text ?? true;\n for await (const chunk of stream as any) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n wrapInTags,\n text: includeText,\n });\n }\n },\n stdout: async (\n response: StreamTextResult<ToolSet, unknown>,\n options?: { reasoning?: boolean; text?: boolean; wrapInTags?: boolean },\n ) => {\n const includeReasoning = options?.reasoning ?? true;\n const includeText = options?.text ?? true;\n const wrapInTags = options?.wrapInTags ?? true;\n for await (const chunk of response.toUIMessageStream()) {\n printChunk(chunk, {\n reasoning: includeReasoning,\n text: includeText,\n wrapInTags,\n });\n }\n console.log(await response.totalUsage);\n },\n mermaid: flow(visualizeMermaid, console.log),\n semantic: flow(visualizeSemantic, console.log),\n richSemantic: flow(visualizeRichSemantic, console.log),\n};\n\nexport function messageToUiMessage(message: string): UIMessage {\n return {\n id: generateId(),\n role: 'user',\n parts: [\n {\n type: 'text',\n text: message,\n },\n ],\n };\n}\nexport const user = messageToUiMessage;\n\nexport async function input(defaultValue?: string): Promise<string> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n const answer = await rl.question(\n `Please enter your input${defaultValue ? ` (default: ${defaultValue})` : ''}: `,\n );\n rl.close();\n return answer || defaultValue || '';\n}\n\nexport async function confirm(\n message: string,\n defaultValue = true,\n): Promise<boolean> {\n const rl = createInterface({\n input: process.stdin,\n output: process.stdout,\n });\n\n const defaultText = defaultValue ? 'Y/n' : 'y/N';\n\n while (true) {\n const answer = await rl.question(`${message} (${defaultText}): `);\n const normalized = answer.toLowerCase().trim();\n\n // If empty answer, use default\n if (normalized === '') {\n rl.close();\n return defaultValue;\n }\n\n if (normalized === 'y' || normalized === 'yes') {\n rl.close();\n return true;\n } else if (normalized === 'n' || normalized === 'no') {\n rl.close();\n return false;\n } else {\n console.log(\n 'Please answer with y/yes or n/no (or press Enter for default)',\n );\n }\n }\n}\n\nexport async function last<T>(iterable: AsyncIterable<T>, position = -1) {\n const arr = await Array.fromAsync(iterable);\n return arr.at(position)!;\n}\nexport async function finished<T>(iterable: AsyncIterable<T>) {\n await Array.fromAsync(iterable);\n}\n\nexport function toOutput<T>(\n result:\n | Promise<GenerateTextResult<ToolSet, T>>\n | StreamTextResult<ToolSet, T>,\n) {\n return isPromise(result)\n ? result.then((res) => res.experimental_output)\n : last(result.experimental_partialOutputStream);\n}\n\nexport function toState<C>(options: ToolCallOptions) {\n return options.experimental_context as C;\n}\n\n/**\n * Custom chunking function for smoothStream that buffers HTML elements until complete.\n *\n * This solves the problem of streaming HTML elements with multiline attributes\n * (like SQL queries) where partial elements would break frontend parsing.\n *\n * Behavior:\n * - Regular text: chunks word-by-word (same as smoothStream default)\n * - HTML elements: buffers until the entire element is complete (including closing tag)\n *\n * Supports:\n * - Single-word elements: `<kpi>`, `<div>`\n * - Kebab-case elements: `<bar-chart>`, `<data-table>`\n * - Self-closing elements: `<kpi />`\n * - Elements with content: `<kpi>...</kpi>`\n * - Quoted attributes with all quote types: `\"`, `'`, `` ` ``\n * - Escaped quotes within attributes\n * - Nested elements of the same type\n *\n * @example\n * ```typescript\n * import { smoothStream } from 'ai';\n *\n * streamText({\n * // ...\n * experimental_transform: smoothStream({\n * chunking: htmlElementChunking(),\n * }),\n * });\n * ```\n */\nexport function htmlElementChunking(): (buffer: string) => string | null {\n const WORD_REGEX = /\\S+\\s+/m;\n\n return (buffer: string): string | null => {\n // Check if buffer starts with potential HTML element\n if (buffer.startsWith('<')) {\n // Check if this could be an element (starts with < followed by a letter)\n if (/^<[a-z]/i.test(buffer)) {\n // Check if we have an incomplete element name (no terminator yet)\n // e.g., `<bar` could become `<bar-chart`\n if (/^<[a-z][a-z0-9-]*$/i.test(buffer)) {\n // Buffer more to see if name is complete\n return null;\n }\n\n // Check if it's a valid element start with complete name\n const elementMatch = /^<([a-z][a-z0-9]*(?:-[a-z0-9]+)*)([\\s/>])/i.exec(\n buffer,\n );\n if (elementMatch) {\n const elementName = elementMatch[1];\n const endIndex = findElementEnd(buffer, elementName);\n if (endIndex === -1) {\n // Element not complete yet\n return null;\n }\n // Return complete element\n return buffer.slice(0, endIndex);\n }\n }\n // `<` followed by non-letter or invalid pattern, treat as text\n }\n\n // Check if there's an element start later in the buffer\n const ltIndex = buffer.indexOf('<');\n if (ltIndex > 0) {\n // There's text before a potential element\n const textBefore = buffer.slice(0, ltIndex);\n // Chunk the text before (word by word)\n const wordMatch = WORD_REGEX.exec(textBefore);\n if (wordMatch) {\n return textBefore.slice(0, wordMatch.index + wordMatch[0].length);\n }\n // No complete word, return all text before element\n return textBefore;\n }\n\n // No element in buffer - use word chunking\n const wordMatch = WORD_REGEX.exec(buffer);\n if (wordMatch) {\n return buffer.slice(0, wordMatch.index + wordMatch[0].length);\n }\n\n // No complete word - return null to buffer more\n return null;\n };\n}\n\n/**\n * Finds the end index of an HTML element in the buffer.\n *\n * Handles:\n * - Self-closing elements: `<foo />` returns index after `>`\n * - Elements with content: `<foo>...</foo>` returns index after closing `>`\n * - Quoted attributes with escaped quotes\n * - Nested elements of the same type\n *\n * @returns The index after the element ends, or -1 if element is incomplete\n */\nfunction findElementEnd(buffer: string, elementName: string): number {\n // Find where the element name ends in the buffer\n const nameEndIndex = buffer.indexOf(elementName) + elementName.length;\n\n type QuoteChar = '\"' | \"'\" | '`';\n let inQuote: QuoteChar | null = null;\n let escaped = false;\n let openTagClosed = false;\n let depth = 0;\n\n for (let i = nameEndIndex; i < buffer.length; i++) {\n const char = buffer[i];\n const prevChar = i > 0 ? buffer[i - 1] : '';\n\n // Handle escape sequences\n if (escaped) {\n escaped = false;\n continue;\n }\n\n if (char === '\\\\') {\n escaped = true;\n continue;\n }\n\n // Handle quotes\n if (inQuote) {\n if (char === inQuote) {\n inQuote = null;\n }\n continue;\n }\n\n if (char === '\"' || char === \"'\" || char === '`') {\n inQuote = char as QuoteChar;\n continue;\n }\n\n // Not in quotes - check for tag boundaries\n\n if (!openTagClosed) {\n // Still in opening tag, looking for > or />\n if (char === '>' && prevChar === '/') {\n // Self-closing element\n return i + 1;\n }\n if (char === '>') {\n openTagClosed = true;\n }\n continue;\n }\n\n // Opening tag is closed, looking for </elementName>\n\n // Check for closing tag (case-insensitive to match HTML behavior)\n const closingTagLength = elementName.length + 3; // \"</\" + name + \">\"\n const potentialClosingTag = buffer.slice(i, i + closingTagLength);\n if (\n potentialClosingTag.toLowerCase() === `</${elementName.toLowerCase()}>`\n ) {\n if (depth === 0) {\n return i + closingTagLength;\n }\n depth--;\n i += closingTagLength - 1; // -1 because loop will increment\n continue;\n }\n\n // Check for nested opening tag of same element type (case-insensitive)\n const openingTagLength = elementName.length + 1; // \"<\" + name\n const potentialOpeningTag = buffer.slice(i, i + openingTagLength);\n if (potentialOpeningTag.toLowerCase() === `<${elementName.toLowerCase()}`) {\n const afterName = buffer[i + openingTagLength];\n // Valid element start if followed by whitespace, >, /, or newline\n if (\n afterName === ' ' ||\n afterName === '>' ||\n afterName === '/' ||\n afterName === '\\n' ||\n afterName === '\\t'\n ) {\n depth++;\n }\n }\n }\n\n // Element not complete\n return -1;\n}\n", "import { titlecase } from 'stringcase';\n\nimport type { Agent } from './agent.ts';\n\nexport type VisualizeOptions = {\n direction?: 'LR' | 'TB' | 'BT' | 'RL';\n showTools?: boolean;\n};\n\ntype Node = {\n id: string;\n name: string;\n tools: string[];\n};\n\ntype Edge = {\n from: string; // node id\n to: string; // node id\n label: string; // e.g., transfer_to_X\n};\n\n/**\n * Build a minimal Mermaid flowchart to visualize agents, their local tools, and handoff transfers.\n *\n * - Agent nodes include their name and (optionally) their tool names.\n * - Edges represent transfer tools (handoffs) from one agent to another, labeled by the transfer tool name.\n */\nexport function visualizeMermaid(\n root: Agent<any>,\n options: VisualizeOptions = {},\n): string {\n const { direction = 'LR', showTools = true } = options;\n\n const nodes: Node[] = [];\n const edges: Edge[] = [];\n\n const seen = new Set<string>();\n const nameToId = new Map<string, string>();\n\n const sanitizeId = (name: string) =>\n name\n .toLowerCase()\n .replace(/[^a-z0-9]+/gi, '_')\n .replace(/^_+|_+$/g, '');\n\n const ensureNode = (agent: Agent) => {\n const name = agent.handoff.name;\n if (!nameToId.has(name)) {\n // Guarantee unique ids even if sanitize collides\n const base = sanitizeId(name) || 'agent';\n let id = base;\n let i = 1;\n while (nodes.some((n) => n.id === id)) id = `${base}_${i++}`;\n nameToId.set(name, id);\n\n nodes.push({\n id,\n name,\n tools: Object.keys(agent.handoff.tools ?? {}),\n });\n }\n return nameToId.get(name)!;\n };\n\n const stack: Agent[] = [root];\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const fromId = ensureNode(current);\n\n for (const child of current.toHandoffs()) {\n const toId = ensureNode(child);\n // Prefer the child's declared handoff tool key (usually transfer_to_{childName})\n const label = Object.keys(child.handoffTool)[0].replace(\n /transfer_to_/g,\n '',\n );\n edges.push({ from: fromId, to: toId, label });\n stack.push(child);\n }\n }\n\n const lines: string[] = [];\n lines.push(`flowchart ${direction}`);\n\n // Nodes\n for (const n of nodes) {\n const name = titlecase(n.name.replace(/_agent/g, '').replace(/_/g, ' '));\n const toolLine =\n showTools && n.tools.length\n ? `<br/>tools: ${n.tools.map((it) => it.replace(/transfer_to_/g, '')).join(', ')}`\n : '';\n // Use double quotes for label to allow <br/>\n lines.push(`${n.id}[\"${escapeLabel(`Agent: ${name}${toolLine}`)}\"]`);\n }\n\n // Edges\n for (const e of edges) {\n lines.push(`${e.from} -- ${escapeLabel(e.label)} --> ${e.to}`);\n }\n\n return lines.join('\\n');\n}\n\nfunction escapeLabel(s: string): string {\n // Minimal escaping for quotes in Mermaid node labels\n return s.replace(/\"/g, '\\\\\"');\n}\n\n/**\n * Convenience alias with simpler name.\n */\nexport const visualize = visualizeMermaid;\n\n/**\n * Produce a semantic, human-readable map of transfers between agents.\n * Example lines:\n * supervisor transfers to: agentx, agenty\n * agentx transfers to: supervisor\n */\nexport function visualizeSemantic(root: Agent): string {\n const lines: string[] = [];\n const seen = new Set<string>();\n const stack: Agent[] = [root];\n\n while (stack.length) {\n const current = stack.pop()!;\n const currentName = current.handoff.name;\n if (seen.has(currentName)) continue;\n seen.add(currentName);\n\n const from = current.handoff.name;\n const transfers = current.toHandoffs().map((h) => h.handoff.name);\n const uniqueTransfers = Array.from(new Set(transfers));\n const rhs = uniqueTransfers.length ? uniqueTransfers.join(', ') : 'none';\n lines.push(`${from} transfers to: ${rhs}`);\n\n for (const child of current.toHandoffs()) stack.push(child);\n }\n\n return lines.join('\\n');\n}\n\n/**\n * Minimal arrow-based semantic visualizer.\n * Prints one line per transfer using Unicode arrows, e.g.:\n * supervisor \u2500\u2500\u25B6 agentx\n * supervisor \u2500\u2500\u25B6 agenty\n * agentx \u2500\u2500\u25B6 supervisor\n */\nexport function visualizeRichSemantic(root: Agent): string {\n const stack: Agent[] = [root];\n const seen = new Set<string>();\n const edgeSet = new Set<string>();\n const edges: Array<{ from: string; to: string }> = [];\n\n while (stack.length) {\n const current = stack.pop()!;\n const from = current.handoff.name;\n if (!seen.has(from)) {\n seen.add(from);\n for (const child of current.toHandoffs()) {\n const to = child.handoff.name;\n const key = `${from}->${to}`;\n if (!edgeSet.has(key)) {\n edgeSet.add(key);\n edges.push({ from, to });\n }\n stack.push(child);\n }\n }\n }\n\n if (edges.length === 0) return `${root.handoff.name} \u2500\u2500\u25B6 none`;\n return edges.map(({ from, to }) => `${from} \u2500\u2500\u25B6 ${to}`).join('\\n');\n}\n", "import { groq } from '@ai-sdk/groq';\nimport {\n type CoreMessage,\n type ModelMessage,\n NoSuchToolError,\n Output,\n type PrepareStepFunction,\n type PrepareStepResult,\n type StepResult,\n type ToolCallRepairFunction,\n type ToolSet,\n type UIDataTypes,\n type UIMessage,\n type UIMessagePart,\n type UITools,\n convertToModelMessages,\n createUIMessageStream,\n generateId,\n generateText,\n smoothStream,\n stepCountIs,\n streamText,\n wrapLanguageModel,\n} from 'ai';\nimport chalk from 'chalk';\nimport dedent from 'dedent';\nimport { zodToJsonSchema } from 'zod-to-json-schema';\n\nimport {\n type Agent,\n type AgentModel,\n type TransferTool,\n isTransferToolResult,\n} from './agent.ts';\nimport {\n htmlElementChunking,\n last,\n messageToUiMessage,\n user,\n} from './stream_utils.ts';\n\nexport type OutputMode = 'full_history' | 'last_message';\n\nexport interface ExecuteOptions {\n contextVariables?: Record<string, unknown>;\n systemPrompt?: string;\n abortSignal?: AbortSignal;\n outputMode?: OutputMode;\n}\n\nfunction isToolMessage(message: CoreMessage): boolean {\n return message.role === 'tool';\n}\n\nfunction filterAgentOutput(\n allMessages: CoreMessage[],\n startIndex: number,\n outputMode: OutputMode,\n): CoreMessage[] {\n if (outputMode === 'full_history') {\n return allMessages; // Include all messages generated by agent\n }\n\n if (outputMode === 'last_message') {\n const agentMessages = allMessages.slice(startIndex);\n if (agentMessages.length === 0) return allMessages;\n\n const lastMsg = agentMessages[agentMessages.length - 1];\n\n // LangChain logic: if isinstance(messages[-1], ToolMessage): messages = messages[-2:]\n // If last message is a tool message, keep AI message + tool message pair\n if (isToolMessage(lastMsg) && agentMessages.length > 1) {\n const beforeLastMsg = agentMessages[agentMessages.length - 2];\n if (beforeLastMsg.role === 'assistant') {\n return [...allMessages.slice(0, startIndex), beforeLastMsg, lastMsg];\n }\n }\n\n // LangChain logic: else: messages = messages[-1:]\n // Otherwise, keep just the last message\n return [...allMessages.slice(0, startIndex), lastMsg];\n }\n\n return allMessages;\n}\n\nexport function generate<O, CIn, COut = CIn>(\n agent: Agent<O, CIn, COut>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof generateText>[0]['providerOptions'];\n },\n) {\n return generateText({\n abortSignal: config?.abortSignal,\n providerOptions: agent.providerOptions ?? config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n experimental_repairToolCall: repairToolCall,\n stopWhen: stepCountIs(25),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: ${chalk.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n}\n\nexport function execute<O, CIn, COut = CIn>(\n agent: Agent<O, CIn, COut>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n config?: {\n abortSignal?: AbortSignal;\n providerOptions?: Parameters<typeof streamText>[0]['providerOptions'];\n },\n) {\n const runId = generateId();\n const stream = streamText({\n abortSignal: config?.abortSignal,\n providerOptions: config?.providerOptions,\n model: agent.model,\n system: agent.instructions(contextVariables),\n messages: convertToModelMessages(\n Array.isArray(messages) ? messages : [user(messages)],\n ),\n stopWhen: stepCountIs(25),\n experimental_transform: smoothStream({\n chunking: htmlElementChunking(),\n }),\n tools: agent.toToolset(),\n activeTools: agent.toolsNames,\n experimental_context: contextVariables,\n toolChoice: agent.toolChoice,\n experimental_repairToolCall: repairToolCall,\n onError: (error) => {\n console.error(\n chalk.red(\n `Error during agent (${agent.internalName})(${runId}) execution: `,\n ),\n error instanceof Error ? error.message : error,\n );\n console.dir(error, { depth: null });\n },\n experimental_output: agent.output\n ? Output.object({ schema: agent.output })\n : undefined,\n // onStepFinish: (step) => tagAgents(step, agent.handoff.name),\n onStepFinish: (step) => {\n const toolCall = step.toolCalls.at(-1);\n if (toolCall) {\n console.log(\n `Debug: (${runId}) ${chalk.bold.yellow('ToolCalled')}: ${toolCall.toolName}(${JSON.stringify(toolCall.input)})`,\n );\n }\n },\n prepareStep: prepareStep(agent, agent.model, contextVariables),\n // onFinish: (result) => {\n // (contextVariables as any).content = result.content;\n // },\n });\n return Object.assign(stream, { state: contextVariables as unknown as COut });\n}\n\nexport const stream = execute;\n\nexport const prepareStep = <CIn>(\n agent: Agent<unknown, CIn, any>,\n model: AgentModel,\n contextVariables: CIn,\n): PrepareStepFunction<NoInfer<ToolSet>> => {\n return async ({ steps, messages }) => {\n const step = steps.at(-1);\n const agentName = (contextVariables as any).currentActiveAgent;\n if (!step) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n if (!agentName) {\n return await prepareAgent(model, agent, messages, contextVariables);\n }\n\n const nextAgent = findAgent(agent, agentName);\n if (!nextAgent) {\n console.error(`Debug: ${chalk.red('NotFound')}: Agent ${agentName}`);\n console.dir(\n {\n steps: steps.map(({ request, response, ...etc }) => etc),\n messages,\n },\n { depth: null },\n );\n return void 0;\n }\n return await prepareAgent(model, nextAgent, messages, contextVariables);\n };\n};\n\nexport function swarm<CIn>(\n agent: Agent<unknown, CIn, any>,\n messages: UIMessage[] | string,\n contextVariables: CIn,\n abortSignal?: AbortSignal,\n) {\n const originalMessages = Array.isArray(messages)\n ? messages\n : [messageToUiMessage(messages)];\n return createUIMessageStream({\n originalMessages,\n generateId: generateId,\n async execute({ writer }) {\n const stream = execute(agent, originalMessages, contextVariables, {\n abortSignal,\n });\n const parts: UIMessagePart<UIDataTypes, UITools>[] = [];\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: true,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n\n if (!agent.prepareEnd) return;\n\n while (true) {\n const state = contextVariables as any;\n if (state.currentActiveAgent === undefined) {\n console.warn(\n `swarm: active agent was never set, so no prepareEnd call will be made`,\n );\n return;\n }\n if (state.currentActiveAgent === agent.internalName) {\n console.warn(\n `swarm: active agent is the root agent, so no prepareEnd call will be made`,\n );\n return;\n }\n const responseMessage = { id: '', parts, role: 'assistant' } as const;\n\n const stream = agent.prepareEnd({\n responseMessage,\n messages: [...originalMessages, responseMessage],\n contextVariables,\n abortSignal,\n });\n if (!stream) break;\n\n writer.merge(\n stream.toUIMessageStream({\n sendFinish: false,\n sendStart: false,\n onFinish: (event) => {\n parts.push(...event.responseMessage.parts);\n },\n }),\n );\n await stream.consumeStream({ onError: console.error });\n await last(stream.fullStream);\n }\n\n writer.write({ type: 'finish' });\n },\n });\n}\n\nexport async function prepareAgent<CIn>(\n defaultModel: AgentModel,\n agent: Agent<unknown, CIn, any>,\n messages: ModelMessage[],\n contextVariables?: CIn,\n): Promise<PrepareStepResult<NoInfer<ToolSet>>> {\n agent.debug();\n await agent.prepareHandoff?.(messages);\n\n let stepModel = agent.model ?? defaultModel;\n if (agent.output) {\n const json_schema = zodToJsonSchema(agent.output, {\n $refStrategy: 'root',\n });\n stepModel = wrapLanguageModel({\n model: stepModel,\n middleware: {\n transformParams: async ({ params }) => ({\n ...params,\n response_format: {\n type: 'json_schema',\n json_schema,\n name: `${agent.handoff.name}_output`,\n },\n }),\n },\n });\n }\n return {\n system: agent.instructions(contextVariables),\n activeTools: agent.toolsNames,\n model: stepModel,\n messages,\n // messages: removeTransferCalls(messages),\n toolChoice: agent.toolChoice,\n } as const;\n}\n\nfunction getLastAgentFromSteps(\n steps: StepResult<NoInfer<ToolSet>>[],\n): string | undefined {\n for (let i = steps.length - 1; i >= 0; i--) {\n const step = steps[i];\n for (const it of step.dynamicToolResults) {\n if (isTransferToolResult(it)) {\n return it.output.currentActiveAgent;\n }\n }\n }\n return void 0;\n}\n\nfunction findAgent<CIn>(agent: Agent<unknown, CIn, any>, agentName: string) {\n // FIXME: first argument agent not always the first passed agent.\n return [...agent.toHandoffs(), agent].find(\n (it) => it.handoff.name === agentName,\n );\n}\n\nfunction getActiveAgentName(messages: ModelMessage[]): string | undefined {\n for (let i = messages.length - 1; i >= 0; i--) {\n const message = messages[i];\n\n if (message.role === 'tool') {\n for (const block of message.content) {\n if (\n block.type === 'tool-result' &&\n block.toolName.startsWith('transfer_to_') &&\n block.output.type === 'json' &&\n isTransferToolResult({ output: block.output.value })\n ) {\n return (block.output.value as TransferTool['output'])\n .currentActiveAgent;\n }\n }\n }\n }\n return undefined;\n}\n\nfunction tagAgents(\n step: StepResult<NoInfer<ToolSet>>,\n defaultAgentName: string,\n) {\n const { request, response, ...stepResult } = step;\n // let transferToolResultIdx = -1;\n const messages = response.messages;\n let agentName: string | undefined;\n\n // look for the last agent from the step\n for (let i = stepResult.content.length - 1; i >= 0; i--) {\n const block = stepResult.content[i];\n if (\n block.type === 'tool-result' &&\n block.dynamic &&\n block.toolName.startsWith('transfer_to_') &&\n isTransferToolResult(block)\n ) {\n // If we found a dynamic tool result, we can use it\n agentName = block.output.lastActiveAgent;\n // transferToolResultIdx = i;\n break;\n }\n }\n\n // if no agent in the step result, look for for it in the messages\n // todo: can we just use this instead of looking into the step result?\n if (!agentName) {\n for (const message of messages.slice(0).reverse()) {\n if (\n message.role === 'tool' &&\n message.content[0].type === 'tool-result' &&\n message.content[0].toolName.startsWith('transfer_to_') &&\n isTransferToolResult({\n output: message.content[0].output.value,\n })\n ) {\n agentName = (message.content[0].output.value as TransferTool['output'])\n .currentActiveAgent;\n break;\n }\n }\n }\n\n if (!agentName) {\n agentName = defaultAgentName;\n }\n\n for (const block of stepResult.content) {\n if (block.type === 'text' && !block.text.startsWith('<name>')) {\n block.text = `<name>${agentName}</name><content>${dedent(block.text)}</content>`;\n }\n }\n // console.log(\n // `Debug: ${chalk.red('NoOp')}: No transfer tool result found.`,\n // );\n // console.dir({ stepResult, messages }, { depth: null });\n}\n\nfunction removeTransferCalls(messages: ModelMessage[]): ModelMessage[] {\n for (const message of messages) {\n if (message.role === 'assistant') {\n if (typeof message.content === 'string') continue;\n\n for (let i = message.content.length - 1; i >= 0; i--) {\n const block = message.content[i];\n if (typeof block === 'string') continue;\n\n if (\n (block.type === 'tool-call' || block.type === 'tool-result') &&\n block.toolName.startsWith('transfer_to_')\n ) {\n message.content.splice(i, 1);\n }\n }\n }\n }\n return messages;\n}\n\nconst repairToolCall: ToolCallRepairFunction<ToolSet> = async ({\n toolCall,\n tools,\n inputSchema,\n error,\n}) => {\n if (NoSuchToolError.isInstance(error)) {\n return null; // do not attempt to fix invalid tool names\n }\n\n console.log(\n `Debug: ${chalk.yellow('RepairingToolCall')}: ${toolCall.toolName}`,\n );\n\n const tool = tools[toolCall.toolName as keyof typeof tools];\n\n const { experimental_output } = await generateText({\n model: groq('openai/gpt-oss-20b'),\n experimental_output: Output.object({ schema: tool.inputSchema }),\n prompt: [\n `The model tried to call the tool \"${toolCall.toolName}\"` +\n ` with the following inputs:`,\n JSON.stringify(toolCall.input),\n `The tool accepts the following schema:`,\n JSON.stringify(inputSchema(toolCall)),\n 'Please fix the inputs.',\n ].join('\\n'),\n });\n\n return { ...toolCall, input: JSON.stringify(experimental_output) };\n};\n", "import { tool } from 'ai';\nimport Conf from 'conf';\nimport { z } from 'zod';\n\n/**\n * Memory System - Inspired by human memory architecture\n *\n * This system implements a multi-layered memory architecture:\n *\n * 1. Working Memory: Short-term, context-specific information (current conversation)\n * 2. Episodic Memory: Event-based memories with temporal context\n * 3. Semantic Memory: Facts, concepts, and general knowledge\n * 4. Procedural Memory: Learned patterns and associations\n */\n\n// ============================================================================\n// Types and Interfaces\n// ============================================================================\n\nexport interface MemoryEntry {\n id: string;\n content: string;\n type: 'episodic' | 'semantic' | 'procedural';\n timestamp: number;\n tags: string[];\n importance: number; // 1-10 scale\n accessCount: number;\n lastAccessed: number;\n context?: Record<string, any>;\n relationships?: string[]; // IDs of related memories\n decay?: number; // Memory strength (0-1)\n}\n\nexport interface MemoryQuery {\n query: string;\n type?: 'episodic' | 'semantic' | 'procedural';\n limit?: number;\n minImportance?: number;\n tags?: string[];\n timeRange?: { start?: number; end?: number };\n}\n\nexport interface MemoryStats {\n totalMemories: number;\n byType: Record<string, number>;\n mostAccessed: MemoryEntry[];\n recentMemories: MemoryEntry[];\n averageImportance: number;\n}\n\n// ============================================================================\n// Memory Store Implementation\n// ============================================================================\n\nexport class MemoryStore {\n private store: Conf<{\n memories: Record<string, MemoryEntry>;\n relationships: Record<string, string[]>;\n metadata: {\n lastConsolidation: number;\n totalAccesses: number;\n };\n }>;\n\n constructor(name = 'agent-memory') {\n this.store = new Conf({\n projectName: name,\n schema: {\n memories: {\n type: 'object',\n default: {},\n },\n relationships: {\n type: 'object',\n default: {},\n },\n metadata: {\n type: 'object',\n default: {\n lastConsolidation: Date.now(),\n totalAccesses: 0,\n },\n },\n },\n }) as Conf<{\n memories: Record<string, MemoryEntry>;\n relationships: Record<string, string[]>;\n metadata: {\n lastConsolidation: number;\n totalAccesses: number;\n };\n }>;\n }\n\n /**\n * Generate a unique memory ID\n */\n private generateId(): string {\n return `mem_${Date.now()}_${Math.random().toString(36).substr(2, 9)}`;\n }\n\n /**\n * Calculate memory decay based on time and access patterns\n */\n private calculateDecay(memory: MemoryEntry): number {\n const now = Date.now();\n const age = now - memory.timestamp;\n const timeSinceAccess = now - memory.lastAccessed;\n\n // Ebbinghaus forgetting curve approximation\n const daysSinceCreation = age / (1000 * 60 * 60 * 24);\n const daysSinceAccess = timeSinceAccess / (1000 * 60 * 60 * 24);\n\n // Decay slows with repeated access (spacing effect)\n const accessBonus = Math.log(memory.accessCount + 1) * 0.1;\n const importanceBonus = memory.importance * 0.05;\n\n const decay = Math.max(\n 0.1,\n 1 -\n (daysSinceCreation * 0.05 +\n daysSinceAccess * 0.08 -\n accessBonus -\n importanceBonus),\n );\n\n return Math.min(1, decay);\n }\n\n /**\n * Store a new memory\n */\n write(\n entry: Omit<\n MemoryEntry,\n 'id' | 'timestamp' | 'accessCount' | 'lastAccessed' | 'decay'\n >,\n ): MemoryEntry {\n const id = this.generateId();\n const now = Date.now();\n\n const memory: MemoryEntry = {\n ...entry,\n id,\n timestamp: now,\n accessCount: 0,\n lastAccessed: now,\n decay: 1.0,\n };\n\n const memories = this.store.get('memories');\n memories[id] = memory;\n this.store.set('memories', memories);\n\n // Update relationships if provided\n if (entry.relationships && entry.relationships.length > 0) {\n const relationships = this.store.get('relationships');\n for (const relatedId of entry.relationships) {\n if (!relationships[relatedId]) {\n relationships[relatedId] = [];\n }\n if (!relationships[relatedId].includes(id)) {\n relationships[relatedId].push(id);\n }\n }\n this.store.set('relationships', relationships);\n }\n\n return memory;\n }\n\n /**\n * Retrieve a memory by ID\n */\n get(id: string): MemoryEntry | null {\n const memories = this.store.get('memories');\n const memory = memories[id];\n\n if (!memory) {\n return null;\n }\n\n // Update access metrics\n memory.accessCount++;\n memory.lastAccessed = Date.now();\n memory.decay = this.calculateDecay(memory);\n\n memories[id] = memory;\n this.store.set('memories', memories);\n\n // Update global access count\n const metadata = this.store.get('metadata');\n metadata.totalAccesses++;\n this.store.set('metadata', metadata);\n\n return memory;\n }\n\n /**\n * Search memories based on query\n */\n lookup(query: MemoryQuery): MemoryEntry[] {\n const memories = Object.values(this.store.get('memories'));\n\n let results = memories;\n\n // Filter by type\n if (query.type) {\n results = results.filter((m) => m.type === query.type);\n }\n\n // Filter by importance\n if (query.minImportance !== undefined) {\n results = results.filter((m) => m.importance >= query.minImportance!);\n }\n\n // Filter by tags\n if (query.tags && query.tags.length > 0) {\n results = results.filter((m) =>\n query.tags!.some((tag) => m.tags.includes(tag)),\n );\n }\n\n // Filter by time range\n if (query.timeRange) {\n if (query.timeRange.start) {\n results = results.filter((m) => m.timestamp >= query.timeRange!.start!);\n }\n if (query.timeRange.end) {\n results = results.filter((m) => m.timestamp <= query.timeRange!.end!);\n }\n }\n\n // Text search (simple implementation)\n const searchTerms = query.query.toLowerCase().split(' ');\n results = results.filter((m) => {\n const content = m.content.toLowerCase();\n const tags = m.tags.join(' ').toLowerCase();\n return searchTerms.some(\n (term) => content.includes(term) || tags.includes(term),\n );\n });\n\n // Update decay for all matching memories\n results = results.map((m) => ({\n ...m,\n decay: this.calculateDecay(m),\n }));\n\n // Sort by relevance (combination of decay, importance, and recency)\n results.sort((a, b) => {\n const scoreA =\n (a.decay || 0) * a.importance * (1 + Math.log(a.accessCount + 1));\n const scoreB =\n (b.decay || 0) * b.importance * (1 + Math.log(b.accessCount + 1));\n return scoreB - scoreA;\n });\n\n // Limit results\n const limit = query.limit || 10;\n return results.slice(0, limit);\n }\n\n /**\n * Update an existing memory\n */\n correct(\n id: string,\n updates: Partial<Omit<MemoryEntry, 'id' | 'timestamp'>>,\n ): MemoryEntry | null {\n const memories = this.store.get('memories');\n const memory = memories[id];\n\n if (!memory) {\n return null;\n }\n\n const updated = {\n ...memory,\n ...updates,\n id: memory.id, // Preserve ID\n timestamp: memory.timestamp, // Preserve original timestamp\n lastAccessed: Date.now(),\n accessCount: memory.accessCount + 1,\n };\n\n updated.decay = this.calculateDecay(updated);\n\n memories[id] = updated;\n this.store.set('memories', memories);\n\n return updated;\n }\n\n /**\n * Delete a memory (forget)\n */\n forget(id: string): boolean {\n const memories = this.store.get('memories');\n\n if (!memories[id]) {\n return false;\n }\n\n delete memories[id];\n this.store.set('memories', memories);\n\n // Clean up relationships\n const relationships = this.store.get('relationships');\n delete relationships[id];\n\n // Remove references from other memories\n for (const [key, refs] of Object.entries(relationships)) {\n relationships[key] = refs.filter((ref) => ref !== id);\n }\n\n this.store.set('relationships', relationships);\n\n return true;\n }\n\n /**\n * Get related memories\n */\n getRelated(id: string, limit = 5): MemoryEntry[] {\n const relationships = this.store.get('relationships');\n const relatedIds = relationships[id] || [];\n\n const memories = this.store.get('memories');\n const relatedMemories = relatedIds\n .map((relId) => memories[relId])\n .filter(Boolean)\n .slice(0, limit);\n\n return relatedMemories;\n }\n\n /**\n * Get memory statistics\n */\n getStats(): MemoryStats {\n const memories = Object.values(this.store.get('memories'));\n\n const byType = memories.reduce(\n (acc, m) => {\n acc[m.type] = (acc[m.type] || 0) + 1;\n return acc;\n },\n {} as Record<string, number>,\n );\n\n const mostAccessed = [...memories]\n .sort((a, b) => b.accessCount - a.accessCount)\n .slice(0, 10);\n\n const recentMemories = [...memories]\n .sort((a, b) => b.timestamp - a.timestamp)\n .slice(0, 10);\n\n const averageImportance =\n memories.length > 0\n ? memories.reduce((sum, m) => sum + m.importance, 0) / memories.length\n : 0;\n\n return {\n totalMemories: memories.length,\n byType,\n mostAccessed,\n recentMemories,\n averageImportance,\n };\n }\n\n /**\n * Consolidate memories (prune low-importance, rarely accessed memories)\n */\n consolidate(threshold = 0.2): number {\n const memories = this.store.get('memories');\n const entries = Object.entries(memories);\n\n let pruned = 0;\n for (const [id, memory] of entries) {\n const decay = this.calculateDecay(memory);\n if (decay < threshold && memory.importance < 5) {\n delete memories[id];\n pruned++;\n }\n }\n\n if (pruned > 0) {\n this.store.set('memories', memories);\n\n const metadata = this.store.get('metadata');\n metadata.lastConsolidation = Date.now();\n this.store.set('metadata', metadata);\n }\n\n return pruned;\n }\n\n /**\n * Clear all memories\n */\n clear(): void {\n this.store.clear();\n }\n\n /**\n * Export all memories\n */\n export(): Record<string, MemoryEntry> {\n return this.store.get('memories');\n }\n\n /**\n * Import memories\n */\n import(memories: Record<string, MemoryEntry>): void {\n this.store.set('memories', memories);\n }\n\n // ============================================================================\n // Specialized Write Functions - High-level convenience methods\n // ============================================================================\n\n /**\n * Write a semantic memory (facts, concepts, general knowledge)\n *\n * @example\n * store.writeSemantic(\"React is a JavaScript library for building UIs\", {\n * tags: [\"react\", \"javascript\"],\n * importance: 8\n * });\n */\n writeSemantic(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'semantic',\n importance: options?.importance ?? 7, // Default to 7 for facts\n tags: options?.tags ?? [],\n context: options?.context,\n relationships: options?.relationships,\n });\n }\n\n /**\n * Write an episodic memory (events, conversations, experiences)\n *\n * @example\n * store.writeEpisodic(\"User completed onboarding\", {\n * tags: [\"milestone\", \"user123\"],\n * context: { userId: \"user123\", timestamp: Date.now() }\n * });\n */\n writeEpisodic(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'episodic',\n importance: options?.importance ?? 6, // Default to 6 for events\n tags: options?.tags ?? [],\n context: {\n ...options?.context,\n timestamp: options?.context?.timestamp ?? Date.now(),\n },\n relationships: options?.relationships,\n });\n }\n\n /**\n * Write a procedural memory (patterns, behaviors, methods)\n *\n * @example\n * store.writeProcedural(\"When user asks for help, first check documentation\", {\n * tags: [\"pattern\", \"help\"],\n * importance: 7\n * });\n */\n writeProcedural(\n content: string,\n options?: {\n importance?: number;\n tags?: string[];\n context?: Record<string, any>;\n relationships?: string[];\n },\n ): MemoryEntry {\n return this.write({\n content,\n type: 'procedural',\n importance: options?.importance ?? 7, // Default to 7 for patterns\n tags: options?.tags ?? [],\n context: options?.context,\n relationships: options?.relationships,\n });\n }\n\n /**\n * Store a user preference (convenience wrapper for semantic memory)\n *\n * @example\n * store.storePreference(\"user123\", \"theme\", \"dark\");\n */\n storePreference(\n userId: string,\n preference: string,\n value: any,\n importance = 8,\n ): MemoryEntry {\n return this.writeSemantic(\n `User ${userId} prefers ${preference}: ${typeof value === 'object' ? JSON.stringify(value) : value}`,\n {\n importance,\n tags: ['preference', userId, preference],\n context: {\n userId,\n preference,\n value,\n category: 'user-preference',\n },\n },\n );\n }\n\n /**\n * Record a conversation exchange (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordConversation(\"user123\", \"session456\", \"user\", \"How do I use React hooks?\");\n */\n recordConversation(\n userId: string,\n sessionId: string,\n role: 'user' | 'assistant' | 'system',\n message: string,\n importance = 5,\n ): MemoryEntry {\n return this.writeEpisodic(`[${role}]: ${message}`, {\n importance,\n tags: ['conversation', userId, sessionId, role],\n context: {\n userId,\n sessionId,\n role,\n timestamp: Date.now(),\n category: 'conversation',\n },\n });\n }\n\n /**\n * Record a user action/event (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordAction(\"user123\", \"completed_tutorial\", { tutorialId: \"intro\" });\n */\n recordAction(\n userId: string,\n action: string,\n details?: Record<string, any>,\n importance = 6,\n ): MemoryEntry {\n return this.writeEpisodic(`User ${userId} performed action: ${action}`, {\n importance,\n tags: ['action', userId, action],\n context: {\n userId,\n action,\n details,\n timestamp: Date.now(),\n category: 'user-action',\n },\n });\n }\n\n /**\n * Learn a pattern from observations (convenience wrapper for procedural memory)\n *\n * @example\n * store.learnPattern(\"optimization-workflow\", \"Profile before optimizing\", {\n * conditions: \"Performance issues reported\",\n * relatedMemories: [\"mem_123\"]\n * });\n */\n learnPattern(\n patternName: string,\n description: string,\n options?: {\n importance?: number;\n conditions?: string;\n relatedMemories?: string[];\n context?: Record<string, any>;\n },\n ): MemoryEntry {\n return this.writeProcedural(`Pattern [${patternName}]: ${description}`, {\n importance: options?.importance ?? 7,\n tags: ['pattern', 'learned', patternName],\n context: {\n patternName,\n conditions: options?.conditions,\n category: 'learned-pattern',\n ...options?.context,\n },\n relationships: options?.relatedMemories,\n });\n }\n\n /**\n * Store a fact or knowledge (convenience wrapper for semantic memory)\n *\n * @example\n * store.storeFact(\"JavaScript\", \"JavaScript is a programming language\", {\n * source: \"documentation\",\n * relatedTo: [\"mem_456\"]\n * });\n */\n storeFact(\n topic: string,\n fact: string,\n options?: {\n importance?: number;\n source?: string;\n relatedTo?: string[];\n tags?: string[];\n },\n ): MemoryEntry {\n return this.writeSemantic(fact, {\n importance: options?.importance ?? 7,\n tags: ['fact', 'knowledge', topic, ...(options?.tags ?? [])],\n context: {\n topic,\n source: options?.source,\n category: 'fact',\n },\n relationships: options?.relatedTo,\n });\n }\n\n /**\n * Record a milestone or achievement (convenience wrapper for episodic memory)\n *\n * @example\n * store.recordMilestone(\"user123\", \"first-project-completed\", \"User completed their first project\");\n */\n recordMilestone(\n userId: string,\n milestoneType: string,\n description: string,\n importance = 7,\n ): MemoryEntry {\n return this.writeEpisodic(description, {\n importance,\n tags: ['milestone', userId, milestoneType],\n context: {\n userId,\n milestoneType,\n timestamp: Date.now(),\n category: 'milestone',\n },\n });\n }\n\n /**\n * Store contextual information about current session (working memory)\n * Note: These should have lower importance as they're temporary\n *\n * @example\n * store.storeSessionContext(\"session456\", \"user-preferences-loaded\", { theme: \"dark\" });\n */\n storeSessionContext(\n sessionId: string,\n contextKey: string,\n data: any,\n importance = 4,\n ): MemoryEntry {\n return this.writeEpisodic(`Session context [${contextKey}]`, {\n importance,\n tags: ['session', 'working-memory', sessionId, contextKey],\n context: {\n sessionId,\n contextKey,\n data,\n category: 'session-context',\n timestamp: Date.now(),\n },\n });\n }\n\n // ============================================================================\n // Proactive Memory Loading - Auto-inject memories into system prompt\n // ============================================================================\n\n /**\n * Get proactive memories that should always be present in system prompt\n * These are high-importance memories that provide essential context\n *\n * @param options Configuration for proactive memory retrieval\n * @returns Formatted string ready for system prompt injection\n *\n * @example\n * const memoryContext = memoryStore.getProactiveMemories({\n * userId: 'user123',\n * minImportance: 7,\n * categories: ['preference', 'core-knowledge']\n * });\n *\n * // Use in agent:\n * const systemPrompt = `${basePrompt}\\n\\n${memoryContext}`;\n */\n getProactiveMemories(options: {\n userId?: string;\n sessionId?: string;\n minImportance?: number;\n categories?: string[];\n maxMemories?: number;\n types?: Array<'episodic' | 'semantic' | 'procedural'>;\n includeRelationships?: boolean;\n }): string {\n const {\n userId,\n sessionId,\n minImportance = 7, // High importance by default\n categories = [],\n maxMemories = 10,\n types,\n includeRelationships = false,\n } = options;\n\n // Build tags filter\n const tags: string[] = [];\n if (userId) tags.push(userId);\n if (sessionId) tags.push(sessionId);\n if (categories.length > 0) tags.push(...categories);\n\n // Collect memories by type\n const memoriesByType: Record<string, MemoryEntry[]> = {\n semantic: [],\n procedural: [],\n episodic: [],\n };\n\n const typesToFetch = types || ['semantic', 'procedural', 'episodic'];\n\n for (const type of typesToFetch) {\n const memories = this.lookup({\n query: '', // Empty query to get all matching filters\n type: type as 'episodic' | 'semantic' | 'procedural',\n minImportance,\n tags: tags.length > 0 ? tags : undefined,\n limit: maxMemories,\n });\n memoriesByType[type] = memories;\n }\n\n // Format memories for system prompt\n return this.formatProactiveMemories(memoriesByType, includeRelationships);\n }\n\n /**\n * Format proactive memories into a structured system prompt section\n */\n private formatProactiveMemories(\n memoriesByType: Record<string, MemoryEntry[]>,\n includeRelationships: boolean,\n ): string {\n const sections: string[] = [];\n\n // Semantic memories (facts, preferences, knowledge)\n if (memoriesByType.semantic.length > 0) {\n sections.push('## Core Knowledge & Preferences');\n sections.push('');\n memoriesByType.semantic.forEach((mem, idx) => {\n sections.push(`${idx + 1}. ${mem.content}`);\n if (mem.context?.preference) {\n sections.push(` - Preference: ${mem.context.preference}`);\n }\n if (mem.context?.source) {\n sections.push(` - Source: ${mem.context.source}`);\n }\n });\n sections.push('');\n }\n\n // Procedural memories (patterns, workflows)\n if (memoriesByType.procedural.length > 0) {\n sections.push('## Behavioral Patterns & Guidelines');\n sections.push('');\n memoriesByType.procedural.forEach((mem, idx) => {\n sections.push(`${idx + 1}. ${mem.content}`);\n if (mem.context?.conditions) {\n sections.push(` - When: ${mem.context.conditions}`);\n }\n if (mem.context?.patternName) {\n sections.push(` - Pattern: ${mem.context.patternName}`);\n }\n });\n sections.push('');\n }\n\n // Episodic memories (recent important events)\n if (memoriesByType.episodic.length > 0) {\n sections.push('## Recent Context & History');\n sections.push('');\n memoriesByType.episodic.forEach((mem, idx) => {\n const timeAgo = this.formatTimeAgo(Date.now() - mem.timestamp);\n sections.push(`${idx + 1}. ${mem.content} (${timeAgo})`);\n if (mem.context?.milestoneType) {\n sections.push(` - Milestone: ${mem.context.milestoneType}`);\n }\n });\n sections.push('');\n }\n\n if (sections.length === 0) {\n return '';\n }\n\n return [\n '',\n '# Proactive Memory Context',\n 'The following information has been retrieved from memory to provide you with essential context:',\n '',\n ...sections,\n ].join('\\n');\n }\n\n /**\n * Helper to format time ago for human readability\n */\n private formatTimeAgo(ms: number): string {\n const seconds = Math.floor(ms / 1000);\n const minutes = Math.floor(seconds / 60);\n const hours = Math.floor(minutes / 60);\n const days = Math.floor(hours / 24);\n\n if (days > 0) return `${days}d ago`;\n if (hours > 0) return `${hours}h ago`;\n if (minutes > 0) return `${minutes}m ago`;\n return `${seconds}s ago`;\n }\n\n /**\n * Get user-specific proactive memories\n * Convenience method that focuses on user preferences and patterns\n *\n * @example\n * const userContext = memoryStore.getUserProactiveMemories('user123');\n */\n getUserProactiveMemories(\n userId: string,\n options?: {\n includePreferences?: boolean;\n includePatterns?: boolean;\n includeRecentHistory?: boolean;\n maxPerCategory?: number;\n },\n ): string {\n const {\n includePreferences = true,\n includePatterns = true,\n includeRecentHistory = true,\n maxPerCategory = 5,\n } = options || {};\n\n const types: Array<'episodic' | 'semantic' | 'procedural'> = [];\n const categories: string[] = [];\n\n if (includePreferences) {\n types.push('semantic');\n categories.push('preference');\n }\n\n if (includePatterns) {\n types.push('procedural');\n categories.push('pattern');\n }\n\n if (includeRecentHistory) {\n types.push('episodic');\n categories.push('milestone', 'action');\n }\n\n return this.getProactiveMemories({\n userId,\n minImportance: 7,\n categories,\n maxMemories: maxPerCategory * types.length,\n types: types.length > 0 ? types : undefined,\n });\n }\n\n /**\n * Get session-specific proactive memories\n * Focuses on working memory and recent context\n *\n * @example\n * const sessionContext = memoryStore.getSessionProactiveMemories('session456');\n */\n getSessionProactiveMemories(\n sessionId: string,\n options?: {\n includeWorkingMemory?: boolean;\n maxMemories?: number;\n },\n ): string {\n const { includeWorkingMemory = true, maxMemories = 10 } = options || {};\n\n const categories = includeWorkingMemory\n ? ['session', 'working-memory', 'conversation']\n : ['session', 'conversation'];\n\n return this.getProactiveMemories({\n sessionId,\n minImportance: 4, // Lower threshold for session context\n categories,\n maxMemories,\n types: ['episodic'],\n });\n }\n\n /**\n * Get critical memories that should ALWAYS be present\n * These are importance level 9-10 memories\n *\n * @example\n * const criticalContext = memoryStore.getCriticalMemories();\n */\n getCriticalMemories(options?: {\n userId?: string;\n maxMemories?: number;\n }): string {\n return this.getProactiveMemories({\n userId: options?.userId,\n minImportance: 9,\n maxMemories: options?.maxMemories || 5,\n types: ['semantic', 'procedural'],\n });\n }\n\n /**\n * Build complete proactive context for an agent\n * Combines critical, user-specific, and session-specific memories\n *\n * @example\n * const fullContext = memoryStore.buildProactiveContext({\n * userId: 'user123',\n * sessionId: 'session456'\n * });\n *\n * // Use in agent system prompt\n * const systemPrompt = `${basePrompt}\\n\\n${fullContext}`;\n */\n buildProactiveContext(options: {\n userId?: string;\n sessionId?: string;\n includeCritical?: boolean;\n includeUser?: boolean;\n includeSession?: boolean;\n }): string {\n const {\n userId,\n sessionId,\n includeCritical = true,\n includeUser = true,\n includeSession = true,\n } = options;\n\n const sections: string[] = [];\n\n // Critical memories first\n if (includeCritical) {\n const critical = this.getCriticalMemories({ userId });\n if (critical) sections.push(critical);\n }\n\n // User-specific context\n if (includeUser && userId) {\n const userContext = this.getUserProactiveMemories(userId);\n if (userContext) sections.push(userContext);\n }\n\n // Session-specific context\n if (includeSession && sessionId) {\n const sessionContext = this.getSessionProactiveMemories(sessionId);\n if (sessionContext) sections.push(sessionContext);\n }\n\n return sections.join('\\n\\n');\n }\n}\n\n// ============================================================================\n// Memory Tools for AI Agents\n// ============================================================================\n\n// Create a singleton memory store instance\nexport const memoryStore = new MemoryStore();\n\n/**\n * Tool: Lookup memories\n */\nexport const memoryLookup = tool({\n description: `Search and retrieve memories from the memory store.\n Use this to recall past conversations, learned facts, or previous interactions.\n Memories decay over time but are reinforced through repeated access.`,\n inputSchema: z.object({\n query: z.string().describe('Search query to find relevant memories'),\n type: z\n .enum(['episodic', 'semantic', 'procedural'])\n .optional()\n .describe('Type of memory to search'),\n limit: z\n .number()\n .int()\n .positive()\n .max(50)\n .default(10)\n .describe('Maximum number of memories to retrieve'),\n minImportance: z\n .number()\n .min(1)\n .max(10)\n .optional()\n .describe('Minimum importance level (1-10)'),\n tags: z.array(z.string()).optional().describe('Filter by tags'),\n }),\n execute: async ({ query, type, limit, minImportance, tags }) => {\n console.log('Memory lookup:', { query, type, limit, minImportance, tags });\n\n const results = memoryStore.lookup({\n query,\n type,\n limit,\n minImportance,\n tags,\n });\n\n return {\n count: results.length,\n memories: results.map((m) => ({\n id: m.id,\n content: m.content,\n type: m.type,\n importance: m.importance,\n tags: m.tags,\n timestamp: new Date(m.timestamp).toISOString(),\n accessCount: m.accessCount,\n decay: m.decay?.toFixed(2),\n context: m.context,\n })),\n };\n },\n});\n\n/**\n * Tool: Explain a specific memory\n */\nexport const memoryExplain = tool({\n description: `Get detailed information about a specific memory, including its relationships,\n access history, and decay status. Use this to understand the context and relevance of a memory.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to explain'),\n includeRelated: z\n .boolean()\n .default(true)\n .describe('Include related memories in the explanation'),\n }),\n execute: async ({ id, includeRelated }) => {\n console.log('Memory explain:', { id, includeRelated });\n\n const memory = memoryStore.get(id);\n\n if (!memory) {\n return {\n found: false,\n message: `No memory found with ID: ${id}`,\n };\n }\n\n const related = includeRelated ? memoryStore.getRelated(id) : [];\n\n return {\n found: true,\n memory: {\n id: memory.id,\n content: memory.content,\n type: memory.type,\n importance: memory.importance,\n tags: memory.tags,\n timestamp: new Date(memory.timestamp).toISOString(),\n lastAccessed: new Date(memory.lastAccessed).toISOString(),\n accessCount: memory.accessCount,\n decay: memory.decay?.toFixed(2),\n context: memory.context,\n age: {\n days: Math.floor(\n (Date.now() - memory.timestamp) / (1000 * 60 * 60 * 24),\n ),\n hours: Math.floor((Date.now() - memory.timestamp) / (1000 * 60 * 60)),\n },\n timeSinceAccess: {\n days: Math.floor(\n (Date.now() - memory.lastAccessed) / (1000 * 60 * 60 * 24),\n ),\n hours: Math.floor(\n (Date.now() - memory.lastAccessed) / (1000 * 60 * 60),\n ),\n },\n },\n related: related.map((r) => ({\n id: r.id,\n content:\n r.content.substring(0, 100) + (r.content.length > 100 ? '...' : ''),\n type: r.type,\n importance: r.importance,\n })),\n };\n },\n});\n\n/**\n * Tool: Write a new memory\n */\nexport const memoryWrite = tool({\n description: `Store a new memory in the memory system. Use this to remember important facts,\n events, or learnings. Choose the appropriate memory type:\n - episodic: Events, conversations, experiences with temporal context\n - semantic: Facts, concepts, general knowledge\n - procedural: Patterns, methods, learned behaviors`,\n inputSchema: z.object({\n content: z.string().describe('The content of the memory to store'),\n type: z\n .enum(['episodic', 'semantic', 'procedural'])\n .describe('Type of memory'),\n importance: z\n .number()\n .min(1)\n .max(10)\n .default(5)\n .describe('Importance level (1-10), affects retention'),\n tags: z\n .array(z.string())\n .default([])\n .describe('Tags for categorization and retrieval'),\n context: z\n .record(z.any(), z.any())\n .optional()\n .describe('Additional context metadata'),\n relationships: z\n .array(z.string())\n .optional()\n .describe('IDs of related memories'),\n }),\n execute: async ({\n content,\n type,\n importance,\n tags,\n context,\n relationships,\n }) => {\n console.log('Memory write:', { content, type, importance, tags });\n\n const memory = memoryStore.write({\n content,\n type,\n importance,\n tags,\n context,\n relationships,\n });\n\n return {\n success: true,\n id: memory.id,\n message: 'Memory stored successfully',\n memory: {\n id: memory.id,\n type: memory.type,\n importance: memory.importance,\n timestamp: new Date(memory.timestamp).toISOString(),\n },\n };\n },\n});\n\n/**\n * Tool: Forget a memory\n */\nexport const memoryForget = tool({\n description: `Delete a memory from the memory store. Use this to remove outdated,\n incorrect, or irrelevant memories. This action is irreversible.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to forget'),\n reason: z.string().optional().describe('Optional reason for forgetting'),\n }),\n execute: async ({ id, reason }) => {\n console.log('Memory forget:', { id, reason });\n\n const success = memoryStore.forget(id);\n\n return {\n success,\n message: success\n ? `Memory ${id} has been forgotten${reason ? `: ${reason}` : ''}`\n : `No memory found with ID: ${id}`,\n };\n },\n});\n\n/**\n * Tool: Correct a memory\n */\nexport const memoryCorrect = tool({\n description: `Update or correct an existing memory. Use this to fix errors,\n add new information, or adjust importance levels. The original timestamp is preserved.`,\n inputSchema: z.object({\n id: z.string().describe('The unique identifier of the memory to correct'),\n updates: z.object({\n content: z.string().optional().describe('Updated content'),\n importance: z\n .number()\n .min(1)\n .max(10)\n .optional()\n .describe('Updated importance'),\n tags: z.array(z.string()).optional().describe('Updated tags'),\n context: z\n .record(z.any(), z.any())\n .optional()\n .describe('Updated context'),\n relationships: z\n .array(z.string())\n .optional()\n .describe('Updated relationships'),\n }),\n correctionNote: z\n .string()\n .optional()\n .describe('Note explaining the correction'),\n }),\n execute: async ({ id, updates, correctionNote }) => {\n console.log('Memory correct:', { id, updates, correctionNote });\n\n const memory = memoryStore.correct(id, updates);\n\n if (!memory) {\n return {\n success: false,\n message: `No memory found with ID: ${id}`,\n };\n }\n\n return {\n success: true,\n message: `Memory ${id} has been updated${correctionNote ? `: ${correctionNote}` : ''}`,\n memory: {\n id: memory.id,\n content: memory.content,\n type: memory.type,\n importance: memory.importance,\n lastAccessed: new Date(memory.lastAccessed).toISOString(),\n },\n };\n },\n});\n\n/**\n * Tool: Get memory statistics\n */\nexport const memoryStats = tool({\n description: `Get statistics about the memory system, including total memories,\n distribution by type, most accessed memories, and recent memories.`,\n inputSchema: z.object({}),\n execute: async () => {\n console.log('Memory stats requested');\n\n const stats = memoryStore.getStats();\n\n return {\n total: stats.totalMemories,\n byType: stats.byType,\n averageImportance: stats.averageImportance.toFixed(2),\n mostAccessed: stats.mostAccessed.slice(0, 5).map((m) => ({\n id: m.id,\n content: m.content.substring(0, 50) + '...',\n accessCount: m.accessCount,\n type: m.type,\n })),\n recent: stats.recentMemories.slice(0, 5).map((m) => ({\n id: m.id,\n content: m.content.substring(0, 50) + '...',\n timestamp: new Date(m.timestamp).toISOString(),\n type: m.type,\n })),\n };\n },\n});\n\n// Export all tools as a collection\nexport const memoryTools = {\n memoryLookup,\n memoryExplain,\n memoryWrite,\n memoryForget,\n memoryCorrect,\n memoryStats,\n};\n\n// Export default\nexport default {\n memoryStore,\n memoryTools,\n MemoryStore,\n};\n", "import { createOpenAICompatible } from '@ai-sdk/openai-compatible';\nimport { embedMany } from 'ai';\n\nexport const lmstudio = createOpenAICompatible({\n name: 'lmstudio',\n baseURL: process.env.LM_STUDIO_BASE_URL ?? 'http://127.0.0.1:1234/v1',\n supportsStructuredOutputs: true,\n includeUsage: true,\n});\n\nexport const ollama = createOpenAICompatible({\n name: 'ollama',\n baseURL: process.env.OLLAMA_BASE_URL ?? 'http://127.0.0.1:11434/v1',\n supportsStructuredOutputs: true,\n});\n\nexport const glm = createOpenAICompatible({\n name: 'z.ai',\n baseURL: 'https://api.z.ai/api/paas/v4/',\n apiKey: process.env.ZAI_API_KEY,\n});\n\nexport const cerebras = createOpenAICompatible({\n name: 'cerebras',\n baseURL: 'https://api.cerebras.ai/v1',\n apiKey: process.env.CEREBRAS_API_KEY,\n includeUsage: true,\n supportsStructuredOutputs: true,\n});\nexport const nebius = createOpenAICompatible({\n name: 'nebius',\n baseURL: 'https://api.tokenfactory.nebius.com/v1/',\n apiKey: process.env.NEBIUS_API_KEY,\n includeUsage: true,\n supportsStructuredOutputs: true,\n});\n\nexport async function embed(documents: string[]): Promise<{\n embeddings: number[][];\n dimensions: number;\n}> {\n const dimensions = 1024;\n const { embeddings } = await embedMany({\n model: lmstudio.textEmbeddingModel('text-embedding-qwen3-embedding-0.6b'),\n values: documents,\n providerOptions: { lmstudio: { dimensions } },\n });\n return { embeddings, dimensions };\n}\n", "import { type UIMessage, createUIMessageStream, generateId } from 'ai';\n\nimport { Agent } from './agent.ts';\nimport { execute } from './swarm.ts';\n\nexport type Pipeable<I, O> =\n | Agent<unknown, I, O>\n | StreamFunction<I, O>\n | StringFunction<I, O>;\n\ntype InitialState = { messages: UIMessage[] };\n\ntype InOf<IS, P> =\n P extends Agent<unknown, infer I, infer O>\n ? IS & I & O\n : P extends StreamFunction<infer I, infer O>\n ? IS & I & O\n : P extends StringFunction<infer I, infer O>\n ? IS & I & O\n : IS;\n\ntype InitialInput<P> =\n P extends Agent<unknown, infer I>\n ? I\n : P extends StreamFunction<infer I>\n ? I\n : P extends StringFunction<infer I>\n ? I\n : unknown;\n\nexport type StreamFunction<StateIn, StateOut = StateIn> = (\n state: StateIn,\n setState: (state: StateOut) => void,\n) =>\n | ReturnType<typeof createUIMessageStream>\n | Promise<ReturnType<typeof createUIMessageStream>>;\n\nexport type StringFunction<StateIn, StateOut = StateIn> = (\n state: StateIn,\n setState: (state: StateOut) => void,\n) => string | Promise<string>;\n\nexport function pipe<IS, P1 extends Pipeable<any, any>>(\n state: IS & InitialInput<P1>,\n p1: P1,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe<\n IS,\n P1 extends Pipeable<any, any>,\n P2 extends Pipeable<InOf<IS, P1>, any>,\n>(\n state: IS & InitialInput<P1>,\n p1: P1,\n p2: P2,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe<\n IS extends InitialState,\n P1 extends Pipeable<any, any>,\n P2 extends Pipeable<InOf<IS, P1>, any>,\n P3 extends Pipeable<InOf<InOf<IS, P1>, P2>, any>,\n>(\n state: IS & InitialInput<P1>,\n p1: P1,\n p2: P2,\n p3: P3,\n): () => ReturnType<typeof createUIMessageStream>;\nexport function pipe(\n state: InitialState,\n ...processes: Array<Pipeable<any, any>>\n) {\n return () => {\n return createUIMessageStream({\n originalMessages: state.messages,\n generateId,\n onError(error) {\n console.error('Error in pipe execution:', error);\n return ' An error occurred during processing. ';\n },\n execute: async ({ writer }) => {\n for (const it of processes) {\n if (it instanceof Agent) {\n const result = execute(it, state.messages, state);\n writer.merge(\n result.toUIMessageStream({\n generateMessageId: generateId,\n originalMessages: state.messages,\n onFinish: async ({ responseMessage }) => {\n state.messages.push(responseMessage);\n },\n }),\n );\n await result.consumeStream();\n } else {\n const output = await it(state, (newState) => {\n Object.assign(\n state as Record<string, unknown>,\n newState as Record<string, unknown>,\n );\n });\n\n if (typeof output === 'string') {\n writer.write({\n id: generateId(),\n type: 'text-start',\n });\n writer.write({\n id: generateId(),\n type: 'text-delta',\n delta: output,\n });\n writer.write({\n id: generateId(),\n type: 'text-end',\n });\n } else {\n writer.merge(output);\n }\n }\n }\n },\n });\n };\n}\n"],
|
|
5
|
+
"mappings": ";AAAA;AAAA,EAIE,UAAAA;AAAA,EAOA;AAAA,EACA,gBAAAC;AAAA,EACA;AAAA,EACA,eAAAC;AAAA,EACA;AAAA,OACK;AACP,OAAOC,YAAW;AAClB,SAAS,iBAAiB;AAC1B,OAAO,OAAO;;;ACnBd,OAAO,YAAY;AAEZ,IAAM,4BAA4B;AAAA,EACvC;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA,EACA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAeF,EAAE,KAAK,IAAI;AAEJ,IAAM,2BAA2B;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAiCjC,SAAS,kBACd,YAAY,cACZ,YAAY,aACJ;AACR,SAAO;AAAA;AAAA;AAAA,0BAGiB,SAAS,OAAO,SAAS,yEAAyE,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA,iCAKpG,SAAS;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAQ1C;AAoBO,IAAM,0BAA6C;AAAA,EACxD;AAAA,IACE,kBACE;AAAA,IACF,kBAAkB;AAAA,IAClB,gBACE;AAAA,IACF,a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AAM,SAAS,MAAM,GAAG,OAAO,CAAC,aAAa;AAC3C,qBAAO;AAAA,gBACL;AAAA,gBACA;AAAA,cACF;AAAA,YACF,CAAC;AAED,gBAAI,OAAO,WAAW,UAAU;AAC9B,qBAAO,MAAM;AAAA,gBACX,IAAIA,YAAW;AAAA,gBACf,MAAM;AAAA,cACR,CAAC;AACD,qBAAO,MAAM;AAAA,gBACX,IAAIA,YAAW;AAAA,gBACf,MAAM;AAAA,gBACN,OAAO;AAAA,cACT,CAAC;AACD,qBAAO,MAAM;AAAA,gBACX,IAAIA,YAAW;AAAA,gBACf,MAAM;AAAA,cACR,CAAC;AAAA,YACH,OAAO;AACL,qBAAO,MAAM,MAAM;AAAA,YACrB;AAAA,UACF;AAAA,QACF;AAAA,MACF;AAAA,IACF,CAAC;AAAA,EACH;AACF;",
|
|
6
|
+
"names": ["Output", "generateText", "stepCountIs", "chalk", "agent", "stream", "wordMatch", "generateId", "dedent", "agent", "generateId", "stream", "agent", "tool", "input", "generateText", "stepCountIs", "Output", "chalk", "agent", "i", "tool", "z", "createUIMessageStream", "generateId", "createUIMessageStream", "generateId"]
|
|
7
7
|
}
|
|
@@ -23,4 +23,36 @@ export declare function last<T>(iterable: AsyncIterable<T>, position?: number):
|
|
|
23
23
|
export declare function finished<T>(iterable: AsyncIterable<T>): Promise<void>;
|
|
24
24
|
export declare function toOutput<T>(result: Promise<GenerateTextResult<ToolSet, T>> | StreamTextResult<ToolSet, T>): Promise<T>;
|
|
25
25
|
export declare function toState<C>(options: ToolCallOptions): C;
|
|
26
|
+
/**
|
|
27
|
+
* Custom chunking function for smoothStream that buffers HTML elements until complete.
|
|
28
|
+
*
|
|
29
|
+
* This solves the problem of streaming HTML elements with multiline attributes
|
|
30
|
+
* (like SQL queries) where partial elements would break frontend parsing.
|
|
31
|
+
*
|
|
32
|
+
* Behavior:
|
|
33
|
+
* - Regular text: chunks word-by-word (same as smoothStream default)
|
|
34
|
+
* - HTML elements: buffers until the entire element is complete (including closing tag)
|
|
35
|
+
*
|
|
36
|
+
* Supports:
|
|
37
|
+
* - Single-word elements: `<kpi>`, `<div>`
|
|
38
|
+
* - Kebab-case elements: `<bar-chart>`, `<data-table>`
|
|
39
|
+
* - Self-closing elements: `<kpi />`
|
|
40
|
+
* - Elements with content: `<kpi>...</kpi>`
|
|
41
|
+
* - Quoted attributes with all quote types: `"`, `'`, `` ` ``
|
|
42
|
+
* - Escaped quotes within attributes
|
|
43
|
+
* - Nested elements of the same type
|
|
44
|
+
*
|
|
45
|
+
* @example
|
|
46
|
+
* ```typescript
|
|
47
|
+
* import { smoothStream } from 'ai';
|
|
48
|
+
*
|
|
49
|
+
* streamText({
|
|
50
|
+
* // ...
|
|
51
|
+
* experimental_transform: smoothStream({
|
|
52
|
+
* chunking: htmlElementChunking(),
|
|
53
|
+
* }),
|
|
54
|
+
* });
|
|
55
|
+
* ```
|
|
56
|
+
*/
|
|
57
|
+
export declare function htmlElementChunking(): (buffer: string) => string | null;
|
|
26
58
|
//# sourceMappingURL=stream_utils.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"stream_utils.d.ts","sourceRoot":"","sources":["../../src/lib/stream_utils.ts"],"names":[],"mappings":"AAAA,OAAO,EACL,KAAK,kBAAkB,EACvB,KAAK,mBAAmB,EACxB,KAAK,gBAAgB,EACrB,KAAK,eAAe,EACpB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,SAAS,EACd,KAAK,OAAO,EAEb,MAAM,IAAI,CAAC;AAaZ,wBAAsB,WAAW,CAAC,QAAQ,EAAE,gBAAgB,CAAC,OAAO,EAAE,KAAK,CAAC,iBA0B3E;AAmCD,eAAO,MAAM,OAAO;6BAER,cAAc,CACpB,mBAAmB,CAAC,SAAS,CAAC,OAAO,EAAE,WAAW,EAAE,OAAO,CAAC,CAAC,CAC9D,YACS;QAAE,SAAS,CAAC,EAAE,OAAO,CAAC;QAAC,UAAU,CAAC,EAAE,OAAO,CAAC;QAAC,IAA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8BG;AACH,wBAAgB,mBAAmB,IAAI,CAAC,MAAM,EAAE,MAAM,KAAK,MAAM,GAAG,IAAI,CAwDvE"}
|
package/dist/lib/swarm.d.ts.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"swarm.d.ts","sourceRoot":"","sources":["../../src/lib/swarm.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,YAAY,EAGjB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EAGtB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,SAAS,EAEd,KAAK,OAAO,EAIZ,YAAY,EAGZ,UAAU,EAEX,MAAM,IAAI,CAAC;AAKZ,OAAO,EACL,KAAK,KAAK,EACV,KAAK,UAAU,EAGhB,MAAM,YAAY,CAAC;
|
|
1
|
+
{"version":3,"file":"swarm.d.ts","sourceRoot":"","sources":["../../src/lib/swarm.ts"],"names":[],"mappings":"AACA,OAAO,EAEL,KAAK,YAAY,EAGjB,KAAK,mBAAmB,EACxB,KAAK,iBAAiB,EAGtB,KAAK,OAAO,EACZ,KAAK,WAAW,EAChB,KAAK,SAAS,EAEd,KAAK,OAAO,EAIZ,YAAY,EAGZ,UAAU,EAEX,MAAM,IAAI,CAAC;AAKZ,OAAO,EACL,KAAK,KAAK,EACV,KAAK,UAAU,EAGhB,MAAM,YAAY,CAAC;AAQpB,MAAM,MAAM,UAAU,GAAG,cAAc,GAAG,cAAc,CAAC;AAEzD,MAAM,WAAW,cAAc;IAC7B,gBAAgB,CAAC,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;IAC3C,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,WAAW,CAAC,EAAE,WAAW,CAAC;IAC1B,UAAU,CAAC,EAAE,UAAU,CAAC;CACzB;AAsCD,wBAAgB,QAAQ,CAAC,CAAC,EAAE,GAAG,EAAE,IAAI,GAAG,GAAG,EACzC,KAAK,EAAE,KAAK,CAAC,CAAC,EAAE,GAAG,EAA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EAAE,YAAY,EAAE,EACxB,gBAAgB,CAAC,EAAE,GAAG,GACrB,OAAO,CAAC,iBAAiB,CAAC,OAAO,CAAC,OAAO,CAAC,CAAC,CAAC,CA+B9C"}
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@deepagents/agent",
|
|
3
|
-
"version": "0.
|
|
3
|
+
"version": "0.8.0",
|
|
4
4
|
"license": "MIT",
|
|
5
5
|
"repository": {
|
|
6
6
|
"type": "git",
|
|
@@ -32,18 +32,19 @@
|
|
|
32
32
|
"access": "public"
|
|
33
33
|
},
|
|
34
34
|
"dependencies": {
|
|
35
|
-
"stringcase": "^4.3.1",
|
|
36
|
-
"lodash-es": "^4.17.21",
|
|
37
|
-
"zod-to-json-schema": "^3.24.6",
|
|
38
|
-
"ai": "^5.0.82",
|
|
39
|
-
"chalk": "^5.6.2",
|
|
40
35
|
"@ai-sdk/groq": "2.0.26",
|
|
41
|
-
"listr2": "^9.0.4",
|
|
42
36
|
"@ai-sdk/openai": "2.0.58",
|
|
43
|
-
"conf": "^15.0.2",
|
|
44
37
|
"@ai-sdk/openai-compatible": "^1.0.24",
|
|
38
|
+
"@deepagents/retrieval": "0.8.0",
|
|
39
|
+
"ai": "^5.0.82",
|
|
40
|
+
"chalk": "^5.6.2",
|
|
41
|
+
"conf": "^15.0.2",
|
|
45
42
|
"dedent": "1.7.0",
|
|
46
|
-
"
|
|
43
|
+
"htmlparser2": "^10.0.0",
|
|
44
|
+
"listr2": "^9.0.4",
|
|
45
|
+
"lodash-es": "^4.17.21",
|
|
46
|
+
"stringcase": "^4.3.1",
|
|
47
|
+
"zod-to-json-schema": "^3.24.6"
|
|
47
48
|
},
|
|
48
49
|
"peerDependencies": {
|
|
49
50
|
"zod": "^3.25.76 || ^4.0.0"
|