@microfox/ai-router 2.1.4 → 2.1.5
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/CHANGELOG.md +6 -0
- package/dist/index.d.mts +18 -1
- package/dist/index.d.ts +18 -1
- package/dist/index.js +45 -0
- package/dist/index.js.map +1 -1
- package/dist/index.mjs +45 -0
- package/dist/index.mjs.map +1 -1
- package/package.json +1 -1
package/CHANGELOG.md
CHANGED
package/dist/index.d.mts
CHANGED
|
@@ -36,6 +36,18 @@ declare const findLastMessageWith: <T>(message: UIMessage[] | null | undefined,
|
|
|
36
36
|
metadata?: Record<string, any>;
|
|
37
37
|
}) => UIMessage<unknown, UIDataTypes, ai.UITools> | null | undefined;
|
|
38
38
|
|
|
39
|
+
/** Result type for ctx.dispatchWorker. */
|
|
40
|
+
type DispatchWorkerResult = {
|
|
41
|
+
jobId: string;
|
|
42
|
+
messageId: string;
|
|
43
|
+
status: 'queued';
|
|
44
|
+
};
|
|
45
|
+
/** Options for ctx.dispatchWorker. */
|
|
46
|
+
type DispatchWorkerOptions = {
|
|
47
|
+
jobId?: string;
|
|
48
|
+
webhookUrl?: string;
|
|
49
|
+
metadata?: Record<string, any>;
|
|
50
|
+
};
|
|
39
51
|
/**
|
|
40
52
|
* Sets a global logger that will be used by all router instances when no instance-specific logger is set.
|
|
41
53
|
* This is useful for debugging across multiple router instances.
|
|
@@ -110,6 +122,11 @@ type AiContext<METADATA extends Record<string, any> = Record<string, any>, Conte
|
|
|
110
122
|
* @internal
|
|
111
123
|
*/
|
|
112
124
|
next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;
|
|
125
|
+
/**
|
|
126
|
+
* Dispatch a background worker by ID (when @microfox/ai-worker is installed).
|
|
127
|
+
* No need to import the worker module. Sends to the workers trigger API.
|
|
128
|
+
*/
|
|
129
|
+
dispatchWorker?: (workerId: string, input?: Record<string, unknown>, options?: DispatchWorkerOptions) => Promise<DispatchWorkerResult>;
|
|
113
130
|
_onExecutionStart?: () => void;
|
|
114
131
|
_onExecutionEnd?: () => void;
|
|
115
132
|
};
|
|
@@ -337,4 +354,4 @@ declare class NextHandler<METADATA extends Record<string, any> = Record<string,
|
|
|
337
354
|
getToolDefinition(agentPath: string | RegExp): AgentTool<any, any> | undefined;
|
|
338
355
|
}
|
|
339
356
|
|
|
340
|
-
export { type AgentData, AgentDefinitionMissingError, AgentNotFoundError, type AgentTool, type AiContext, type AiHandler, AiKitError, type AiLogger, type AiMiddleware, AiRouter, type AiRouterType, type AiStreamWriter, MaxCallDepthExceededError, type NextFunction, Store, StreamWriter, type UITools, findFirstElement, findLastElement, findLastMessageWith, getGlobalLogger, getTextParts, getTextPartsContent, setGlobalLogger };
|
|
357
|
+
export { type AgentData, AgentDefinitionMissingError, AgentNotFoundError, type AgentTool, type AiContext, type AiHandler, AiKitError, type AiLogger, type AiMiddleware, AiRouter, type AiRouterType, type AiStreamWriter, type DispatchWorkerOptions, type DispatchWorkerResult, MaxCallDepthExceededError, type NextFunction, Store, StreamWriter, type UITools, findFirstElement, findLastElement, findLastMessageWith, getGlobalLogger, getTextParts, getTextPartsContent, setGlobalLogger };
|
package/dist/index.d.ts
CHANGED
|
@@ -36,6 +36,18 @@ declare const findLastMessageWith: <T>(message: UIMessage[] | null | undefined,
|
|
|
36
36
|
metadata?: Record<string, any>;
|
|
37
37
|
}) => UIMessage<unknown, UIDataTypes, ai.UITools> | null | undefined;
|
|
38
38
|
|
|
39
|
+
/** Result type for ctx.dispatchWorker. */
|
|
40
|
+
type DispatchWorkerResult = {
|
|
41
|
+
jobId: string;
|
|
42
|
+
messageId: string;
|
|
43
|
+
status: 'queued';
|
|
44
|
+
};
|
|
45
|
+
/** Options for ctx.dispatchWorker. */
|
|
46
|
+
type DispatchWorkerOptions = {
|
|
47
|
+
jobId?: string;
|
|
48
|
+
webhookUrl?: string;
|
|
49
|
+
metadata?: Record<string, any>;
|
|
50
|
+
};
|
|
39
51
|
/**
|
|
40
52
|
* Sets a global logger that will be used by all router instances when no instance-specific logger is set.
|
|
41
53
|
* This is useful for debugging across multiple router instances.
|
|
@@ -110,6 +122,11 @@ type AiContext<METADATA extends Record<string, any> = Record<string, any>, Conte
|
|
|
110
122
|
* @internal
|
|
111
123
|
*/
|
|
112
124
|
next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;
|
|
125
|
+
/**
|
|
126
|
+
* Dispatch a background worker by ID (when @microfox/ai-worker is installed).
|
|
127
|
+
* No need to import the worker module. Sends to the workers trigger API.
|
|
128
|
+
*/
|
|
129
|
+
dispatchWorker?: (workerId: string, input?: Record<string, unknown>, options?: DispatchWorkerOptions) => Promise<DispatchWorkerResult>;
|
|
113
130
|
_onExecutionStart?: () => void;
|
|
114
131
|
_onExecutionEnd?: () => void;
|
|
115
132
|
};
|
|
@@ -337,4 +354,4 @@ declare class NextHandler<METADATA extends Record<string, any> = Record<string,
|
|
|
337
354
|
getToolDefinition(agentPath: string | RegExp): AgentTool<any, any> | undefined;
|
|
338
355
|
}
|
|
339
356
|
|
|
340
|
-
export { type AgentData, AgentDefinitionMissingError, AgentNotFoundError, type AgentTool, type AiContext, type AiHandler, AiKitError, type AiLogger, type AiMiddleware, AiRouter, type AiRouterType, type AiStreamWriter, MaxCallDepthExceededError, type NextFunction, Store, StreamWriter, type UITools, findFirstElement, findLastElement, findLastMessageWith, getGlobalLogger, getTextParts, getTextPartsContent, setGlobalLogger };
|
|
357
|
+
export { type AgentData, AgentDefinitionMissingError, AgentNotFoundError, type AgentTool, type AiContext, type AiHandler, AiKitError, type AiLogger, type AiMiddleware, AiRouter, type AiRouterType, type AiStreamWriter, type DispatchWorkerOptions, type DispatchWorkerResult, MaxCallDepthExceededError, type NextFunction, Store, StreamWriter, type UITools, findFirstElement, findLastElement, findLastMessageWith, getGlobalLogger, getTextParts, getTextPartsContent, setGlobalLogger };
|
package/dist/index.js
CHANGED
|
@@ -212,6 +212,50 @@ var MemoryStore = class {
|
|
|
212
212
|
};
|
|
213
213
|
|
|
214
214
|
// src/router.ts
|
|
215
|
+
function getWorkersTriggerUrl() {
|
|
216
|
+
const raw = process.env.WORKER_BASE_URL || process.env.WORKERS_TRIGGER_API_URL || process.env.WORKERS_CONFIG_API_URL;
|
|
217
|
+
if (!raw) {
|
|
218
|
+
throw new Error("WORKER_BASE_URL is required for ctx.dispatchWorker. Set it server-side only.");
|
|
219
|
+
}
|
|
220
|
+
const url = new URL(raw);
|
|
221
|
+
url.search = "";
|
|
222
|
+
url.hash = "";
|
|
223
|
+
const pathname = url.pathname || "";
|
|
224
|
+
url.pathname = pathname.replace(/\/?workers\/(trigger|config)\/?$/, "");
|
|
225
|
+
const basePath = url.pathname.replace(/\/+$/, "");
|
|
226
|
+
url.pathname = `${basePath}/workers/trigger`.replace(/\/+$/, "");
|
|
227
|
+
return url.toString();
|
|
228
|
+
}
|
|
229
|
+
async function dispatchWorker(workerId, input, options = {}) {
|
|
230
|
+
const jobId = options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
231
|
+
const triggerUrl = getWorkersTriggerUrl();
|
|
232
|
+
const messageBody = {
|
|
233
|
+
workerId,
|
|
234
|
+
jobId,
|
|
235
|
+
input: input ?? {},
|
|
236
|
+
context: {},
|
|
237
|
+
webhookUrl: options.webhookUrl,
|
|
238
|
+
metadata: options.metadata || {},
|
|
239
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
240
|
+
};
|
|
241
|
+
const headers = { "Content-Type": "application/json" };
|
|
242
|
+
const key = process.env.WORKERS_TRIGGER_API_KEY;
|
|
243
|
+
if (key) headers["x-workers-trigger-key"] = key;
|
|
244
|
+
const response = await fetch(triggerUrl, {
|
|
245
|
+
method: "POST",
|
|
246
|
+
headers,
|
|
247
|
+
body: JSON.stringify({ workerId, body: messageBody })
|
|
248
|
+
});
|
|
249
|
+
if (!response.ok) {
|
|
250
|
+
const text = await response.text().catch(() => "");
|
|
251
|
+
throw new Error(
|
|
252
|
+
`Failed to trigger worker "${workerId}": ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`
|
|
253
|
+
);
|
|
254
|
+
}
|
|
255
|
+
const data = await response.json().catch(() => ({}));
|
|
256
|
+
const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;
|
|
257
|
+
return { messageId, status: "queued", jobId };
|
|
258
|
+
}
|
|
215
259
|
var globalLogger = void 0;
|
|
216
260
|
function setGlobalLogger(logger) {
|
|
217
261
|
globalLogger = logger;
|
|
@@ -870,6 +914,7 @@ var AiRouter = class _AiRouter {
|
|
|
870
914
|
},
|
|
871
915
|
next: void 0,
|
|
872
916
|
// Will be replaced right after
|
|
917
|
+
dispatchWorker,
|
|
873
918
|
_onExecutionStart: () => {
|
|
874
919
|
self.pendingExecutions++;
|
|
875
920
|
self.logger?.log(
|
package/dist/index.js.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/router.ts","../../../node_modules/nanoid/index.js","../src/helper.ts","../src/store.ts"],"sourcesContent":["export * from './router.js';\nexport * from './types.js';\nexport * from './helper.js';\nexport * from './store.js';\n","import {\n UIMessage,\n createUIMessageStream,\n UIMessageStreamWriter,\n createUIMessageStreamResponse,\n UIDataTypes,\n generateId,\n Tool,\n tool,\n JSONValue,\n ToolCallOptions,\n convertToModelMessages,\n ToolSet,\n DataUIPart,\n pipeUIMessageStreamToResponse,\n readUIMessageStream,\n} from 'ai';\nimport { StreamWriter } from './helper.js';\nimport { UITools } from './types.js';\nimport { z, ZodObject, ZodType } from 'zod';\nimport path from 'path';\nimport { Store, MemoryStore } from './store.js';\n\n// Add global logger management\nlet globalLogger: AiLogger | undefined = undefined;\n\n/**\n * Sets a global logger that will be used by all router instances when no instance-specific logger is set.\n * This is useful for debugging across multiple router instances.\n * @param logger The logger to use globally, or undefined to disable global logging\n */\nexport function setGlobalLogger(logger?: AiLogger) {\n globalLogger = logger;\n}\n\n/**\n * Gets the current global logger.\n * @returns The current global logger or undefined if none is set\n */\nexport function getGlobalLogger(): AiLogger | undefined {\n return globalLogger;\n}\n\n// --- Helper Functions ---\n/**\n * Clubs parts based on toolCallId for tool-* types and id for data-* types\n * @param parts Array of parts to club\n * @returns Clubbed parts array\n */\nfunction clubParts(parts: any[]): any[] {\n if (!parts || parts.length === 0) return parts;\n\n const clubbedParts: any[] = [];\n const toolCallIdGroups = new Map<string, any[]>();\n const dataIdGroups = new Map<string, any[]>();\n\n // Group parts by toolCallId for tool-* types and by id for data-* types\n for (const part of parts) {\n if (part.type?.startsWith('tool-') && (part as any).toolCallId) {\n const toolCallId = (part as any).toolCallId;\n if (!toolCallIdGroups.has(toolCallId)) {\n toolCallIdGroups.set(toolCallId, []);\n }\n toolCallIdGroups.get(toolCallId)!.push(part);\n } else if (part.type?.startsWith('data-') && part.id) {\n const id = part.id;\n if (!dataIdGroups.has(id)) {\n dataIdGroups.set(id, []);\n }\n dataIdGroups.get(id)!.push(part);\n } else {\n // For parts that don't match the clubbing criteria, add them directly\n clubbedParts.push(part);\n }\n }\n\n // Add clubbed tool parts\n for (const [toolCallId, toolParts] of toolCallIdGroups) {\n if (toolParts.length === 1) {\n clubbedParts.push(toolParts[0]);\n } else {\n // Merge multiple parts with same toolCallId\n const mergedPart = { ...toolParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < toolParts.length; i++) {\n const currentPart = toolParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'toolCallId') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n // Add clubbed data parts\n for (const [id, dataParts] of dataIdGroups) {\n if (dataParts.length === 1) {\n clubbedParts.push(dataParts[0]);\n } else {\n // Merge multiple parts with same id\n const mergedPart = { ...dataParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < dataParts.length; i++) {\n const currentPart = dataParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'id') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n return clubbedParts;\n}\n\n// --- Custom Errors ---\nexport class AiKitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AiKitError';\n }\n}\n\nexport class AgentNotFoundError extends AiKitError {\n constructor(path: string) {\n super(`[AiAgentKit] Agent not found for path: ${path}`);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class MaxCallDepthExceededError extends AiKitError {\n constructor(maxDepth: number) {\n super(`[AiAgentKit] Agent call depth limit (${maxDepth}) exceeded.`);\n this.name = 'MaxCallDepthExceededError';\n }\n}\n\nexport class AgentDefinitionMissingError extends AiKitError {\n constructor(path: string) {\n super(\n `[AiAgentKit] agentAsTool: No definition found for \"${path}\". Please define it using '.actAsTool()' or pass a definition as the second argument.`\n );\n this.name = 'AgentDefinitionMissingError';\n }\n}\n\n// --- Dynamic Parameter Support ---\n\n/**\n * Converts a path pattern with dynamic parameters (e.g., \"/users/:id/posts/:postId\")\n * into a RegExp that can match actual paths and extract parameters.\n * @param pattern The path pattern with dynamic parameters\n * @returns A RegExp and parameter names array\n */\nfunction parsePathPattern(pattern: string): {\n regex: RegExp;\n paramNames: string[];\n} {\n const paramNames: string[] = [];\n // Split the pattern by dynamic parameter segments, but keep the segments in the result\n const parts = pattern.split(/(\\/:[^\\/]+)/);\n\n const regexPattern = parts\n .map((part) => {\n if (part.startsWith('/:')) {\n // This is a dynamic segment like \"/:id\"\n paramNames.push(part.substring(2)); // Extract \"id\"\n return '/([^/]+)'; // Replace with a capturing group\n }\n // This is a static segment, escape any special regex characters in it\n return part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n })\n .join('');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return { regex, paramNames };\n}\n\n/**\n * Extracts dynamic parameters from a path based on a pattern.\n * @param pattern The path pattern with dynamic parameters\n * @param path The actual path to extract parameters from\n * @returns An object with extracted parameters or null if no match\n */\nfunction extractPathParams(\n pattern: string,\n path: string\n): Record<string, string> | null {\n const { regex, paramNames } = parsePathPattern(pattern);\n const match = path.match(regex);\n\n if (!match) {\n return null;\n }\n\n const params: Record<string, string> = {};\n paramNames.forEach((paramName, index) => {\n const value = match[index + 1]; // +1 because match[0] is the full match\n if (value !== undefined) {\n params[paramName] = value;\n }\n });\n\n return params;\n}\n\n/**\n * Checks if a path pattern contains dynamic parameters.\n * @param pattern The path pattern to check\n * @returns True if the pattern contains dynamic parameters\n */\nfunction hasDynamicParams(pattern: string): boolean {\n return /\\/:[^\\/]+/.test(pattern);\n}\n\nexport type AiStreamWriter<\n METADATA = unknown,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = UIMessageStreamWriter<UIMessage<METADATA, PARTS, TOOLS>> &\n Omit<StreamWriter<METADATA, TOOLS>, 'writer'> & {\n generateId: typeof generateId;\n };\n\n// --- Core Types ---\n\n/**\n * The context object passed to every agent, tool, and middleware. It contains\n * all the necessary information and utilities for a handler to perform its work.\n * @template METADATA - The type for custom metadata in UI messages.\n * @template PARTS - The type for custom parts in UI messages.\n * @template TOOLS - The type for custom tools in UI messages.\n * @template ContextState - The type for the shared state object.\n */\nexport type AiContext<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n request: {\n /** The message history for the current request. The user can modify this array to change the message history or manipulate the message history, but beware that in the routing, the messages are passed as a reference and not a copy, making the mutatated value available to all the handlers in the request chain. */\n messages: UIMessage<METADATA, PARTS, TOOLS>[];\n /** Parameters passed from an internal tool or agent call. */\n params: PARAMS;\n [key: string]: any;\n } & METADATA;\n /** A shared, mutable state object that persists for the lifetime of a single request. */\n state: ContextState;\n /** A shared, mutable store object that persists for the lifetime of a single request. */\n store: Store;\n /**\n * Internal execution context for the router. Should not be modified by user code.\n * @internal\n */\n executionContext: {\n handlerPathStack?: string[];\n currentPath?: string;\n callDepth?: number;\n [key: string]: any;\n };\n /**\n * A unique ID for the top-level request, useful for logging and tracing.\n */\n requestId: string;\n /**\n * A structured logger that automatically includes the `requestId` and current handler path.\n */\n logger: AiLogger;\n /**\n * The stream writer to send data back to the end-user's UI.\n * Includes helpers for writing structured data like tool calls and metadata.\n */\n response: AiStreamWriter<Partial<METADATA>, PARTS, TOOLS>;\n /**\n * Provides functions for an agent to dispatch calls to other agents or tools.\n * @internal\n */\n next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n\n _onExecutionStart?: () => void;\n _onExecutionEnd?: () => void;\n};\n\n/** Represents the `next` function in a middleware chain, used to pass control to the next handler. */\nexport type NextFunction = () => Promise<any>;\n/** A function that handles a request for a specific agent path. */\nexport type AiHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n) => Promise<any>;\n\n/** A function that acts as middleware, processing a request and optionally passing control to the next handler. */\nexport type AiMiddleware<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n next: NextFunction\n) => Promise<any>;\n\n// --- Router Implementation ---\n\n/** A simple structured logger interface. */\nexport type AiLogger = {\n log: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\n/** Internal representation of a registered handler in the router's stack. */\ntype Layer<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n path: string | RegExp;\n handler: AiMiddleware<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n isAgent: boolean;\n // Timing for middleware: 'before' runs before agents, 'after' runs after agents\n timing?: 'before' | 'after';\n // Dynamic parameter support\n hasDynamicParams?: boolean;\n paramNames?: string[];\n};\n\nexport type AgentTool<\n INPUT extends JSONValue | unknown | never = any,\n OUTPUT extends JSONValue | unknown | never = any,\n> = Tool<INPUT, OUTPUT> & {\n name: string;\n id: string;\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n};\n\nexport type AgentData = {\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n [key: string]: any;\n};\n\n/**\n * A composable router for building structured, multi-agent AI applications.\n * It allows you to define agents and tools, compose them together, and handle\n * requests in a predictable, middleware-style pattern.\n *\n * @template KIT_METADATA - The base metadata type for all UI messages in this router.\n * @template PARTS - The base custom parts type for all UI messages.\n * @template TOOLS - The base custom tools type for all UI messages.\n * @template ContextState - The base type for the shared state object.\n */\nexport class AiRouter<\n KIT_METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = {},\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n REGISTERED_TOOLS extends ToolSet = {},\n> {\n private stack: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[] = [];\n public actAsToolDefinitions: Map<string | RegExp, AgentTool<any, any>> =\n new Map();\n private logger?: AiLogger = undefined;\n private _store: Store = new MemoryStore();\n\n /** Configuration options for the router instance. */\n public options: {\n /** The maximum number of agent-to-agent calls allowed in a single request to prevent infinite loops. */\n maxCallDepth: number;\n } = {\n maxCallDepth: 10,\n };\n\n /**\n * Constructs a new AiAgentKit router.\n * @param stack An optional initial stack of layers, used for composing routers.\n * @param options Optional configuration for the router.\n */\n constructor(\n stack?: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[],\n options?: { maxCallDepth?: number; logger?: AiLogger }\n ) {\n // Remove logger from constructor - it should be set via setLogger\n if (stack) {\n this.stack = stack;\n }\n if (options?.maxCallDepth) {\n this.options.maxCallDepth = options.maxCallDepth;\n }\n }\n\n setStore(store: Store) {\n this._store = store;\n }\n\n /**\n * Sets a logger for this router instance.\n * If no logger is set, the router will fall back to the global logger.\n * @param logger The logger to use for this router instance, or undefined to use global logger\n */\n setLogger(logger?: AiLogger) {\n this.logger = logger;\n }\n\n /**\n * Gets the effective logger for this router instance.\n * Returns instance logger if set, otherwise falls back to global logger.\n * @returns The effective logger or undefined if no logging should occur\n */\n private _getEffectiveLogger(): AiLogger | undefined {\n return this.logger ?? globalLogger;\n }\n\n /**\n * Registers a middleware-style agent that runs for a specific path prefix, regex pattern, or wildcard.\n * Agents can modify the context and must call `next()` to pass control to the next handler in the chain.\n * This method is primarily for middleware. For terminal agents, see `.agent()` on an instance.\n *\n * @param path The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param agents The agent middleware function(s).\n */\n agent<\n const TAgents extends (\n | AiMiddleware<any, any, any, any, any>\n | AiRouter<any, any, any, any, any, any>\n )[],\n >(\n agentPath:\n | string\n | RegExp\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n ...agents: TAgents\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (TAgents[number] extends AiRouter<any, any, any, any, any, infer R>\n ? R\n : {})\n > {\n let prefix: string | RegExp = '/';\n if (typeof agentPath === 'string' || agentPath instanceof RegExp) {\n prefix = agentPath;\n } else {\n agents.unshift(agentPath);\n }\n\n for (const handler of agents) {\n if (typeof handler !== 'function') {\n // Check if it's an AiRouter instance for mounting\n if (handler instanceof AiRouter && typeof prefix === 'string') {\n // Mount the router's stack directly\n const router = handler;\n const mountPath = prefix.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n }\n continue;\n }\n // Check if path has dynamic parameters\n const hasDynamic =\n typeof prefix === 'string' ? hasDynamicParams(prefix) : false;\n const paramNames =\n typeof prefix === 'string' && hasDynamic\n ? parsePathPattern(prefix).paramNames\n : undefined;\n\n this.stack.push({\n path: prefix,\n handler: handler as any,\n isAgent: true, // Mark as an agent\n hasDynamicParams: hasDynamic,\n paramNames: paramNames,\n });\n this.logger?.log(`Agent registered: path=${prefix}`);\n }\n\n return this as any;\n }\n\n /**\n * Registers middleware that runs BEFORE agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n before<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'before', // Mark as before middleware\n });\n }\n return this as any;\n }\n\n /**\n * Registers middleware that runs AFTER agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n after<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'after', // Mark as after middleware\n });\n }\n return this as any;\n }\n\n /**\n * Pre-defines the schema and description for an agent when it is used as a tool by an LLM.\n * This allows `next.agentAsTool()` to create a valid `Tool` object without needing the definition at call time.\n * @param path The path of the agent being defined.\n * @param options The tool definition, including a Zod schema and description.\n */\n actAsTool<\n const TPath extends string | RegExp,\n const TTool extends AgentTool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n >,\n >(\n path: TPath,\n options: TTool\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS & {\n [K in TTool['id']]: Tool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n > & {\n metadata: TTool['metadata'] & {\n toolKey: TTool['id'];\n name: TTool['name'];\n description: TTool['description'];\n };\n };\n }\n > {\n this.actAsToolDefinitions.set(path, options);\n this.logger?.log(`[actAsTool] Added definition: at path ${path}`);\n this.logger?.log(\n `[actAsTool] Router now has ${this.actAsToolDefinitions.size} definitions`\n );\n return this as any;\n }\n\n getToolSet(): REGISTERED_TOOLS {\n let allTools = Array.from(this.actAsToolDefinitions.entries()).map(\n ([key, value]) => {\n return {\n ...value,\n metadata: {\n ...value.metadata,\n absolutePath: key,\n },\n } as AgentTool<any, any>;\n }\n ) as AgentTool<any, any>[];\n return allTools.reduce((acc, _tool) => {\n const { inputSchema, outputSchema } = _tool;\n acc[_tool.id] = {\n ...tool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>(\n _tool\n ),\n metadata: {\n ..._tool.metadata,\n toolKey: _tool.id,\n name: _tool.name,\n description: _tool.description,\n },\n } as AgentTool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>;\n return acc;\n }, {} as any) as REGISTERED_TOOLS;\n }\n\n getToolDefinition(path: string) {\n let definition = this.actAsToolDefinitions.get(path);\n if (!definition) {\n this.logger?.error(\n `[getToolDefinition] No definition found for path: ${path}`\n );\n throw new AgentDefinitionMissingError(path);\n }\n return definition;\n }\n\n /**\n * Outputs all registered paths, and the middlewares and agents registered on each path.\n * @returns A map of paths to their registered handlers.\n */\n registry(): {\n map: Record<string, { before: any[]; agents: any[]; after: any[] }>;\n tools: REGISTERED_TOOLS;\n } {\n const registryMap: Record<\n string,\n { before: any[]; agents: any[]; after: any[] }\n > = {};\n\n for (const layer of this.stack) {\n const pathKey = layer.path.toString();\n if (!registryMap[pathKey]) {\n registryMap[pathKey] = { before: [], agents: [], after: [] };\n }\n\n if (layer.isAgent) {\n const agentInfo: any = {\n handler: layer.handler.name || 'anonymous',\n };\n const actAsToolDef = this.actAsToolDefinitions.get(layer.path);\n if (actAsToolDef) {\n agentInfo.actAsTool = {\n ...actAsToolDef,\n };\n }\n registryMap[pathKey].agents.push(agentInfo);\n } else {\n const middlewareInfo: any = {\n handler: layer.handler.name || 'anonymous',\n timing: layer.timing || 'middleware',\n };\n if (layer.timing === 'before') {\n registryMap[pathKey].before.push(middlewareInfo);\n } else if (layer.timing === 'after') {\n registryMap[pathKey].after.push(middlewareInfo);\n } else {\n // Legacy middleware without timing (shouldn't happen with new API, but handle gracefully)\n registryMap[pathKey].before.push(middlewareInfo);\n }\n }\n }\n\n return {\n map: registryMap,\n tools: this.getToolSet(),\n };\n }\n\n /**\n * Resolves a path based on the parent path and the requested path.\n * - If path starts with `@/`, it's an absolute path from the root.\n * - Otherwise, it's a relative path.\n * @internal\n */\n private _resolvePath(parentPath: string, newPath: string): string {\n if (newPath.startsWith('@/')) {\n // Absolute path from root, use POSIX normalize for consistency\n return path.posix.normalize(newPath.substring(1));\n }\n // Relative path, use POSIX join to ensure consistent behavior\n const joinedPath = path.posix.join(parentPath, newPath);\n return joinedPath;\n }\n\n /**\n * Creates a new context for an internal agent or tool call.\n * It inherits from the parent context but gets a new logger and call depth.\n * @internal\n */\n private _createSubContext(\n parentCtx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n options: {\n type: 'agent' | 'tool';\n path: string;\n messages?: UIMessage<KIT_METADATA, PARTS, TOOLS>[];\n params: PARAMS;\n }\n ) {\n const parentDepth = parentCtx.executionContext.callDepth ?? 0;\n const newCallDepth = parentDepth + (options.type === 'agent' ? 1 : 0);\n\n const subContext: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > = {\n ...parentCtx,\n // State is passed by reference to allow sub-agents to modify the parent's state.\n // The execution context is a shallow copy to ensure call-specific data is isolated.\n state: parentCtx.state,\n store: parentCtx.store,\n executionContext: {\n ...parentCtx.executionContext,\n currentPath: options.path,\n callDepth: newCallDepth,\n },\n request: {\n ...parentCtx.request,\n messages:\n options.messages ||\n parentCtx.request.messages ||\n ([] as UIMessage<KIT_METADATA, PARTS, TOOLS>[]),\n params: options.params,\n path: options.path, // The path to execute\n },\n logger: this._createLogger(\n parentCtx.requestId,\n options.path,\n newCallDepth\n ),\n next: undefined as any, // Will be replaced right after\n };\n\n // The current path for the new context is the path we are about to execute.\n subContext.executionContext.currentPath = options.path;\n\n subContext.next = new NextHandler<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n >(\n subContext,\n this,\n (parentCtx as any)._onExecutionStart,\n (parentCtx as any)._onExecutionEnd,\n parentCtx.next\n ) as any;\n\n return subContext;\n }\n\n /**\n * Creates a new logger instance with a structured prefix.\n * @internal\n */\n private _createLogger(\n requestId: string,\n path: string | RegExp,\n callDepth: number = 0\n ): AiLogger {\n const effectiveLogger = this._getEffectiveLogger();\n\n // If no logger is available, return a no-op logger\n if (!effectiveLogger) {\n return {\n log: () => { },\n warn: () => { },\n error: () => { },\n };\n }\n\n const indent = ' '.repeat(callDepth);\n const prefix = `${indent}[${path.toString()}]`;\n // Add requestId to every log message for better tracking.\n const fullPrefix = `[${requestId}]${prefix}`;\n return {\n log: (...args: any[]) => effectiveLogger.log(fullPrefix, ...args),\n warn: (...args: any[]) => effectiveLogger.warn(fullPrefix, ...args),\n error: (...args: any[]) => effectiveLogger.error(fullPrefix, ...args),\n };\n }\n\n /**\n * Calculates a specificity score for a layer to enable Express-style routing.\n * Higher score means more specific.\n * - Middleware is less specific than an agent/tool.\n * - Deeper paths are more specific.\n * - Static segments are more specific than dynamic segments.\n * @internal\n */\n private _getSpecificityScore(\n layer: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ): number {\n const path = layer.path.toString();\n let score = 0;\n\n // Base score on depth. Deeper is more specific.\n score += path.split('/').length * 100;\n\n // More dynamic segments mean less specific.\n score -= (path.match(/:/g) || []).length * 10;\n\n // Regex is less specific than a string path.\n if (layer.path instanceof RegExp) {\n score -= 50;\n }\n\n // Agents/tools are more specific than middleware.\n if (layer.isAgent) {\n score += 1;\n }\n\n return score;\n }\n\n /**\n * The core execution engine. It finds all matching layers for a given path\n * and runs them in a middleware-style chain.\n * @internal\n */\n private async _execute(\n path: string,\n ctx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n isInternalCall = false\n ) {\n // The context's `currentPath` is now the single source of truth.\n // No more stack manipulation is needed here.\n try {\n const normalizedPath =\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n ctx.logger.log(`Executing path. isInternalCall=${isInternalCall}`);\n const layersToRun = this.stack.filter((layer) => {\n let shouldRun = false;\n\n // Handle RegExp paths. For internal calls, we demand an exact match.\n if (layer.path instanceof RegExp) {\n if (isInternalCall) {\n const exactRegex = new RegExp(`^${layer.path.source}$`);\n shouldRun = exactRegex.test(normalizedPath);\n } else {\n shouldRun = layer.path.test(normalizedPath);\n }\n } else if (typeof layer.path === 'string') {\n const layerPath = layer.path;\n\n // Wildcard middleware only runs for external calls.\n if (layerPath === '*') {\n return !isInternalCall;\n }\n\n const normalizedLayerPath =\n layerPath.length > 1 && layerPath.endsWith('/')\n ? layerPath.slice(0, -1)\n : layerPath;\n\n const isExactMatch = normalizedPath === normalizedLayerPath;\n\n // Check for dynamic parameters in the layer path\n const hasDynamic = hasDynamicParams(normalizedLayerPath);\n\n if (hasDynamic) {\n // Use extractPathParams to check if the path matches the pattern\n const extractedParams = extractPathParams(normalizedLayerPath, normalizedPath);\n if (extractedParams !== null) {\n shouldRun = true;\n // Merge extracted params into ctx.request.params\n ctx.request.params = {\n ...ctx.request.params,\n ...extractedParams,\n };\n }\n } else if (isInternalCall) {\n // --- Internal Call Logic ---\n // For internal calls, we only consider exact matches for all layer types.\n shouldRun = isExactMatch;\n } else {\n // --- External Call Logic ---\n if (layer.isAgent) {\n // Agents are only matched exactly (or by dynamic params, handled above).\n shouldRun = isExactMatch;\n } else {\n // Middlewares are matched by prefix.\n shouldRun = normalizedPath.startsWith(normalizedLayerPath);\n }\n }\n }\n\n if (shouldRun) {\n ctx.logger.log(\n `[AiAgentKit][_execute] Layer MATCH: path=${normalizedPath}, layer.path=${layer.path}, isAgent=${layer.isAgent}, isInternal=${isInternalCall}`\n );\n }\n return shouldRun;\n });\n\n // Separate layers into before, agents, and after\n const beforeLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'before'\n );\n const agentLayers = layersToRun.filter((l) => l.isAgent);\n const afterLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'after'\n );\n\n // Sort each group by specificity (most general first) to ensure correct execution order.\n beforeLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n agentLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n afterLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n\n // Combine in order: before, agents, after\n const orderedLayers = [...beforeLayers, ...agentLayers, ...afterLayers];\n\n const layerDescriptions = orderedLayers.map((l) => {\n const type = l.isAgent\n ? 'agent'\n : l.timing === 'before'\n ? 'before'\n : l.timing === 'after'\n ? 'after'\n : 'middleware';\n return `${l.path.toString()} (${type})`;\n });\n ctx.logger.log(\n `Found ${orderedLayers.length} layers to run: [${layerDescriptions.join(\n ', '\n )}]`\n );\n\n if (!agentLayers.length && !beforeLayers.length && !afterLayers.length) {\n const errorMsg = `No agent or tool found for path: ${normalizedPath}`;\n ctx.logger.error(errorMsg);\n throw new AgentNotFoundError(normalizedPath);\n }\n\n // A more robust, explicit dispatcher to avoid promise chain issues.\n const dispatch = async (index: number): Promise<any> => {\n const layer = orderedLayers[index];\n if (!layer) {\n // End of the chain\n return;\n }\n\n const next = () => dispatch(index + 1);\n\n const layerPath =\n typeof layer.path === 'string' ? layer.path : layer.path.toString();\n\n const layerType = layer.isAgent\n ? 'agent'\n : layer.timing === 'before'\n ? 'before'\n : layer.timing === 'after'\n ? 'after'\n : 'middleware';\n ctx.logger.log(`-> Running ${layerType}: ${layerPath}`);\n\n try {\n if (ctx._onExecutionStart) {\n ctx._onExecutionStart();\n }\n // The handler is an async function, so we can await it directly.\n // The original Promise wrapper was redundant and could hide issues.\n const result = await layer.handler(ctx, next);\n // Agents typically don't call next(), so \"after\" middlewares would never run.\n // After an agent completes, explicitly continue the chain so .after() runs.\n if (layer.isAgent) {\n await next();\n }\n\n // if (!isInternalCall) {\n // console.log('toolDefinition', result);\n // const toolDefinition = this.actAsToolDefinitions.get(path);\n // if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n // ctx.response.writeCustomTool({\n // toolName: toolDefinition.id as string,\n // toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n // output: result,\n // });\n // }\n // }\n ctx.logger.log(`<- Finished ${layerType}: ${layerPath}`);\n return result;\n } catch (err) {\n ctx.logger.error(\n `Error in ${layerType} layer for path: ${layerPath}`,\n err\n );\n throw err;\n } finally {\n if (ctx._onExecutionEnd) {\n ctx._onExecutionEnd();\n }\n }\n };\n\n return await dispatch(0);\n } finally {\n // No-op. Stack is managed by context creation/destruction.\n }\n }\n\n private pendingExecutions = 0;\n\n /**\n * The main public entry point for the router. It handles an incoming request,\n * sets up the response stream, creates the root context, and starts the execution chain.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A standard `Response` object containing the rich UI stream.\n */\n handle(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Response {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n // --- End Execution Lifecycle Management ---\n\n return createUIMessageStreamResponse({\n stream: self.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n ),\n });\n }\n\n handleStream(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >,\n executionCompletionPromise: Promise<void>,\n executionCompletionResolver: (() => void) | null\n ) {\n const self = this;\n return createUIMessageStream({\n originalMessages: initialContext.request.messages,\n execute: async ({ writer }) => {\n const streamWriter = new StreamWriter<KIT_METADATA, TOOLS>(writer);\n const requestId = generateId();\n\n // If the configured store is a MemoryStore, create a new one for each request\n // to prevent state leakage between concurrent requests. If it's a different\n // type of store, we assume it's designed to be shared.\n const store =\n self._store instanceof MemoryStore ? new MemoryStore() : self._store;\n\n const ctx: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > & {\n _onExecutionStart: () => void;\n _onExecutionEnd: () => void;\n } = {\n ...initialContext,\n request: {\n ...initialContext.request,\n path: path, // Set the initial path for the root context\n },\n state: {} as any,\n store: store,\n executionContext: { currentPath: path, callDepth: 0 },\n requestId: requestId,\n logger: self._createLogger(requestId, path, 0),\n response: {\n ...streamWriter.writer,\n writeMessageMetadata: streamWriter.writeMessageMetadata,\n writeCustomTool: streamWriter.writeCustomTool,\n writeObjectAsTool: streamWriter.writeObjectAsTool,\n generateId: generateId,\n },\n next: undefined as any, // Will be replaced right after\n _onExecutionStart: () => {\n self.pendingExecutions++;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution started. Pending: ${self.pendingExecutions}`\n );\n },\n _onExecutionEnd: () => {\n self.pendingExecutions--;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution ended. Pending: ${self.pendingExecutions}`\n );\n if (self.pendingExecutions === 0 && executionCompletionResolver) {\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions finished. Resolving promise.`\n );\n executionCompletionResolver();\n }\n },\n };\n ctx.next = new NextHandler(\n ctx,\n self,\n ctx._onExecutionStart,\n ctx._onExecutionEnd\n ) as any;\n\n ctx._onExecutionStart();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain started.`\n );\n\n // Fire off the main execution chain. We don't await it here because, in a streaming\n // context, the await might resolve prematurely when the agent yields control.\n // Instead, we catch errors and use .finally() to reliably mark the end of this\n // specific execution, while the main function body waits on the lifecycle promise.\n // self\n // ._execute(path, ctx)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // // Optionally, you could write an error message to the stream here.\n // })\n // .finally(() => {\n // ctx._onExecutionEnd();\n // });\n\n try {\n const response = await self._execute(path, ctx);\n const toolDefinition = this.actAsToolDefinitions.get(path);\n if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n ctx.response.writeCustomTool({\n toolName: toolDefinition.id as string,\n toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n output: response,\n });\n }\n return response;\n } catch (err) {\n ctx.logger.error('Unhandled error in main execution chain', err);\n } finally {\n ctx._onExecutionEnd();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain finished.`\n );\n }\n\n // ctx.next\n // .callAgent(path, initialContext.request.params)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // });\n\n // Wait for the promise that resolves only when all executions (the main one\n // and all sub-calls) have completed.\n await executionCompletionPromise;\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions truly finished. Stream can be safely closed.`\n );\n },\n });\n }\n\n /**\n * Handles an incoming request and returns a promise that resolves with the full,\n * non-streamed response. This is useful for environments where streaming is not\n * desired or for testing.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A `Promise<Response>` that resolves with the final JSON response.\n */\n async toAwaitResponse(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Promise<Response> {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n const stream = this.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n );\n\n const messageStream = readUIMessageStream({\n stream,\n onError: (error) => {\n this.logger?.error('Error reading UI message stream', error);\n },\n });\n\n let finalMessages: UIMessage[] = [];\n const thisMessageId = generateId();\n for await (const message of messageStream) {\n if (message.id?.length > 0) {\n finalMessages.push(message);\n } else if (finalMessages.find((m) => m.id === thisMessageId)) {\n finalMessages = finalMessages.map((m) =>\n m.id === thisMessageId\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n ...(message.metadata ?? {}),\n },\n parts: clubParts([\n ...(m.parts ?? []),\n ...(message.parts ?? []),\n ]),\n }\n : m\n );\n } else {\n finalMessages.push({\n ...message,\n id: thisMessageId,\n });\n }\n }\n const responseBody = JSON.stringify(finalMessages);\n return new Response(responseBody, {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n}\n\nexport type AiRouterType = typeof AiRouter;\n\nclass NextHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> {\n public maxCallDepth: number;\n\n constructor(\n private ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private router: AiRouter<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private onExecutionStart: () => void,\n private onExecutionEnd: () => void,\n parentNext?: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ) {\n this.maxCallDepth = this.router.options.maxCallDepth;\n }\n\n async callAgent(\n agentPath: string,\n params?: Record<string, any>,\n options?: {\n streamToUI?: boolean;\n }\n ): Promise<{ ok: true; data: any } | { ok: false; error: Error }> {\n this.onExecutionStart();\n try {\n const currentDepth = this.ctx.executionContext.callDepth ?? 0;\n if (currentDepth >= this.maxCallDepth) {\n const err = new MaxCallDepthExceededError(this.maxCallDepth);\n this.ctx.logger.error(`[callAgent] Aborting. ${err.message}`);\n throw err;\n }\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n this.ctx.logger.log(`Calling agent: resolvedPath='${resolvedPath}'`);\n\n const subContext = (this.router as any)._createSubContext(this.ctx, {\n type: 'agent',\n path: resolvedPath,\n params: params ?? ({} as PARAMS),\n messages: this.ctx.request.messages,\n });\n\n const definition = this.router.actAsToolDefinitions.get(resolvedPath);\n const toolCallId = definition?.id + '-' + this.ctx.response.generateId();\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n input: subContext.request.params,\n });\n }\n\n const data = await (this.router as any)._execute(\n resolvedPath,\n subContext,\n true\n );\n\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n output: data,\n });\n }\n\n return { ok: true, data };\n } catch (error: any) {\n this.ctx.logger.error(`[callAgent] Error:`, error);\n return { ok: false, error };\n } finally {\n this.onExecutionEnd();\n }\n }\n\n agentAsTool<INPUT extends JSONValue | unknown | never = any, OUTPUT = any>(\n agentPath: string,\n schemaControl?: Record<string, any> & { disableAllInputs?: boolean }\n ) {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n const definition = this.getToolDefinition(agentPath);\n\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n throw new AgentDefinitionMissingError(resolvedPath);\n }\n\n const originalSchema = definition.inputSchema as ZodObject<any> | undefined;\n let finalSchema = originalSchema;\n const fixedParams: Record<string, any> = {};\n\n if (schemaControl) {\n if (schemaControl.disableAllInputs) {\n finalSchema = z.object({});\n } else if (originalSchema) {\n let isPickMode = false;\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n isPickMode = true;\n break;\n }\n }\n\n if (isPickMode) {\n const pickShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n pickShape[key] = true;\n } else {\n fixedParams[key] = schemaControl[key];\n }\n }\n finalSchema = originalSchema.pick(pickShape);\n } else {\n // Omit mode\n const omitShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (key !== 'disableAllInputs') {\n fixedParams[key] = schemaControl[key];\n omitShape[key] = true;\n }\n }\n finalSchema = originalSchema.omit(omitShape);\n }\n }\n }\n\n const { id, metadata, ...restDefinition } = definition;\n\n (restDefinition as { inputSchema?: unknown }).inputSchema = finalSchema;\n\n return {\n [id]: {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n execute: async (params: any, options: any) => {\n const result = await this.callAgent(agentPath, params, options);\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n },\n } as Tool<INPUT, OUTPUT>,\n };\n }\n\n getToolDefinition(\n agentPath: string | RegExp\n ): AgentTool<any, any> | undefined {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath.toString()\n );\n let preDefined;\n const pathsToTry = [resolvedPath];\n // If the agentPath starts with '/', it's an absolute path from root, so also try it directly\n if (typeof agentPath === 'string' && agentPath.startsWith('/')) {\n pathsToTry.unshift(agentPath);\n }\n for (const pathToTry of pathsToTry) {\n for (const [key, value] of (this.router as any).actAsToolDefinitions) {\n if (typeof key === 'string') {\n // Check for exact match first\n if (key === pathToTry) {\n preDefined = value;\n break;\n }\n // Then check for dynamic path parameters\n if (extractPathParams(key, pathToTry) !== null) {\n preDefined = value;\n break;\n }\n }\n // Basic RegExp match\n if (key instanceof RegExp && key.test(pathToTry)) {\n preDefined = value;\n break;\n }\n }\n if (preDefined) break;\n }\n\n const definition = preDefined;\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n return undefined;\n }\n const { metadata, ...restDefinition } = definition;\n return {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: restDefinition.id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n } as AgentTool<any, any>;\n }\n\n\n /** \n * Deprecated execute style for L1402\n * execute: (params: any, options: any) => {\n const finalParams = { ...params, ...fixedParams };\n \n const executeInternal = async () => {\n const result = await this.callAgent(\n agentPath,\n finalParams,\n options\n );\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n };\n \n const newPromise = this.router.toolExecutionPromise.then(\n executeInternal,\n executeInternal\n );\n this.router.toolExecutionPromise = newPromise;\n return newPromise;\n *\n */\n\n}\n","import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import {\n GenerateObjectResult,\n UIDataTypes,\n UIMessage,\n UIMessageStreamWriter,\n} from 'ai';\nimport { UITools } from './types.js';\nimport { customAlphabet } from 'nanoid';\n\nexport const findLastElement = <T>(array: T[]) => {\n return array[array.length - 1];\n};\n\nexport const findFirstElement = <T>(array: T[]) => {\n return array[0];\n};\n\nexport class StreamWriter<METADATA, TOOLS extends UITools> {\n public writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>;\n constructor(writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>) {\n this.writer = writer;\n }\n generateId = () => {\n return customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 10)();\n };\n writeMessageMetadata = <NEW_METADATA extends METADATA>(\n metadata: NEW_METADATA\n ) => {\n return this.writer.write({\n type: 'message-metadata' as const,\n messageMetadata: metadata as NEW_METADATA,\n });\n };\n writeCustomTool = <K extends keyof TOOLS>(tool: {\n toolCallId?: string;\n toolName: K;\n inputTextDelta?: string[];\n input?: any;\n output?: any;\n }) => {\n const toolCallId =\n tool.toolCallId || tool.toolName?.toString() + '-' + this.generateId();\n if ('input' in tool && tool.input) {\n this.writer.write({\n type: 'tool-input-available' as const,\n input: tool.input,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n }\n if (\n (tool.inputTextDelta && tool.inputTextDelta.length > 0) ||\n ('output' in tool && tool.output)\n ) {\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n if (tool.inputTextDelta) {\n for (const delta of tool.inputTextDelta) {\n this.writer.write({\n type: 'tool-input-delta' as const,\n toolCallId: toolCallId,\n inputTextDelta: delta,\n });\n }\n }\n }\n if ('output' in tool && tool.output) {\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.output,\n });\n }\n };\n writeObjectAsTool = <K extends keyof TOOLS>(tool: {\n toolName: K;\n result?: GenerateObjectResult<TOOLS[K]['output']>;\n input?: GenerateObjectResult<TOOLS[K]['input']>;\n }) => {\n if (!tool.result?.object) {\n throw new Error('No object found in the GenerateObjectResult');\n }\n\n const toolCallId = tool.toolName.toString() + '-' + this.generateId();\n\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-input-available' as const,\n toolCallId: toolCallId,\n input:\n (tool.input ?? tool.result)\n ? {\n usage: tool.result?.usage,\n warnings: tool.result?.warnings,\n finishReason: tool.result?.finishReason,\n }\n : undefined,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.result?.object,\n });\n };\n}\n\nexport const getTextParts = (message: UIMessage | null | undefined) => {\n if (!message) return [];\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text);\n};\n\nexport const getTextPartsContent = (message: UIMessage | null | undefined) => {\n if (!message) return '';\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('')\n .trim();\n};\n\nexport const findLastMessageWith = <T>(\n message: UIMessage[] | null | undefined,\n filters: {\n role?: 'user' | 'assistant' | 'system';\n metadata?: Record<string, any>;\n }\n) => {\n if (!message) return null;\n return message\n .filter((m) => {\n if (filters.role && m.role !== filters.role) return false;\n if (filters.metadata) {\n for (const key in filters.metadata) {\n }\n }\n return true;\n })\n .pop();\n};\n","export interface Store {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n delete(key: string): Promise<void>;\n has(key: string): Promise<boolean>;\n entries?(): Promise<[string, any][]>;\n clear?(): Promise<void>;\n}\n\n/**\n * An in-memory implementation of the `Store` interface.\n *\n * @remarks\n * Each instance of `MemoryStore` maintains its own isolated key-value map.\n * In a server environment where a single `AiRouter` instance handles multiple\n * concurrent requests, the router's `handle` method automatically creates a new\n * `MemoryStore` for each request to ensure state isolation. This prevents\n * data leakage between different requests.\n */\nexport class MemoryStore implements Store {\n private store = new Map<string, any>();\n\n async get<T>(key: string): Promise<T | undefined> {\n return this.store.get(key);\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n this.store.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async has(key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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BF;","names":["crypto","tool","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/router.ts","../../../node_modules/nanoid/index.js","../src/helper.ts","../src/store.ts"],"sourcesContent":["export * from './router.js';\nexport * from './types.js';\nexport * from './helper.js';\nexport * from './store.js';\n","import {\n UIMessage,\n createUIMessageStream,\n UIMessageStreamWriter,\n createUIMessageStreamResponse,\n UIDataTypes,\n generateId,\n Tool,\n tool,\n JSONValue,\n ToolCallOptions,\n convertToModelMessages,\n ToolSet,\n DataUIPart,\n pipeUIMessageStreamToResponse,\n readUIMessageStream,\n} from 'ai';\nimport { StreamWriter } from './helper.js';\nimport { UITools } from './types.js';\nimport { z, ZodObject, ZodType } from 'zod';\nimport path from 'path';\nimport { Store, MemoryStore } from './store.js';\n\n/** Result type for ctx.dispatchWorker. */\nexport type DispatchWorkerResult = {\n jobId: string;\n messageId: string;\n status: 'queued';\n};\n\n/** Options for ctx.dispatchWorker. */\nexport type DispatchWorkerOptions = {\n jobId?: string;\n webhookUrl?: string;\n metadata?: Record<string, any>;\n};\n\n/** Derives /workers/trigger URL from env (WORKER_BASE_URL or WORKERS_TRIGGER_API_URL / WORKERS_CONFIG_API_URL). */\nfunction getWorkersTriggerUrl(): string {\n const raw =\n process.env.WORKER_BASE_URL ||\n process.env.WORKERS_TRIGGER_API_URL ||\n process.env.WORKERS_CONFIG_API_URL;\n if (!raw) {\n throw new Error('WORKER_BASE_URL is required for ctx.dispatchWorker. Set it server-side only.');\n }\n const url = new URL(raw);\n url.search = '';\n url.hash = '';\n const pathname = url.pathname || '';\n url.pathname = pathname.replace(/\\/?workers\\/(trigger|config)\\/?$/, '');\n const basePath = url.pathname.replace(/\\/+$/, '');\n url.pathname = `${basePath}/workers/trigger`.replace(/\\/+$/, '');\n return url.toString();\n}\n\n/** Dispatch a worker by ID via the workers trigger API. Inlined so ai-router has no dependency on @microfox/ai-worker. */\nasync function dispatchWorker(\n workerId: string,\n input?: Record<string, unknown>,\n options: DispatchWorkerOptions = {}\n): Promise<DispatchWorkerResult> {\n const jobId =\n options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const triggerUrl = getWorkersTriggerUrl();\n const messageBody = {\n workerId,\n jobId,\n input: input ?? {},\n context: {},\n webhookUrl: options.webhookUrl,\n metadata: options.metadata || {},\n timestamp: new Date().toISOString(),\n };\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n const key = process.env.WORKERS_TRIGGER_API_KEY;\n if (key) headers['x-workers-trigger-key'] = key;\n const response = await fetch(triggerUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify({ workerId, body: messageBody }),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Failed to trigger worker \"${workerId}\": ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n const data = (await response.json().catch(() => ({}))) as any;\n const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;\n return { messageId, status: 'queued', jobId };\n}\n\n// Add global logger management\nlet globalLogger: AiLogger | undefined = undefined;\n\n/**\n * Sets a global logger that will be used by all router instances when no instance-specific logger is set.\n * This is useful for debugging across multiple router instances.\n * @param logger The logger to use globally, or undefined to disable global logging\n */\nexport function setGlobalLogger(logger?: AiLogger) {\n globalLogger = logger;\n}\n\n/**\n * Gets the current global logger.\n * @returns The current global logger or undefined if none is set\n */\nexport function getGlobalLogger(): AiLogger | undefined {\n return globalLogger;\n}\n\n// --- Helper Functions ---\n/**\n * Clubs parts based on toolCallId for tool-* types and id for data-* types\n * @param parts Array of parts to club\n * @returns Clubbed parts array\n */\nfunction clubParts(parts: any[]): any[] {\n if (!parts || parts.length === 0) return parts;\n\n const clubbedParts: any[] = [];\n const toolCallIdGroups = new Map<string, any[]>();\n const dataIdGroups = new Map<string, any[]>();\n\n // Group parts by toolCallId for tool-* types and by id for data-* types\n for (const part of parts) {\n if (part.type?.startsWith('tool-') && (part as any).toolCallId) {\n const toolCallId = (part as any).toolCallId;\n if (!toolCallIdGroups.has(toolCallId)) {\n toolCallIdGroups.set(toolCallId, []);\n }\n toolCallIdGroups.get(toolCallId)!.push(part);\n } else if (part.type?.startsWith('data-') && part.id) {\n const id = part.id;\n if (!dataIdGroups.has(id)) {\n dataIdGroups.set(id, []);\n }\n dataIdGroups.get(id)!.push(part);\n } else {\n // For parts that don't match the clubbing criteria, add them directly\n clubbedParts.push(part);\n }\n }\n\n // Add clubbed tool parts\n for (const [toolCallId, toolParts] of toolCallIdGroups) {\n if (toolParts.length === 1) {\n clubbedParts.push(toolParts[0]);\n } else {\n // Merge multiple parts with same toolCallId\n const mergedPart = { ...toolParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < toolParts.length; i++) {\n const currentPart = toolParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'toolCallId') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n // Add clubbed data parts\n for (const [id, dataParts] of dataIdGroups) {\n if (dataParts.length === 1) {\n clubbedParts.push(dataParts[0]);\n } else {\n // Merge multiple parts with same id\n const mergedPart = { ...dataParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < dataParts.length; i++) {\n const currentPart = dataParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'id') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n return clubbedParts;\n}\n\n// --- Custom Errors ---\nexport class AiKitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AiKitError';\n }\n}\n\nexport class AgentNotFoundError extends AiKitError {\n constructor(path: string) {\n super(`[AiAgentKit] Agent not found for path: ${path}`);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class MaxCallDepthExceededError extends AiKitError {\n constructor(maxDepth: number) {\n super(`[AiAgentKit] Agent call depth limit (${maxDepth}) exceeded.`);\n this.name = 'MaxCallDepthExceededError';\n }\n}\n\nexport class AgentDefinitionMissingError extends AiKitError {\n constructor(path: string) {\n super(\n `[AiAgentKit] agentAsTool: No definition found for \"${path}\". Please define it using '.actAsTool()' or pass a definition as the second argument.`\n );\n this.name = 'AgentDefinitionMissingError';\n }\n}\n\n// --- Dynamic Parameter Support ---\n\n/**\n * Converts a path pattern with dynamic parameters (e.g., \"/users/:id/posts/:postId\")\n * into a RegExp that can match actual paths and extract parameters.\n * @param pattern The path pattern with dynamic parameters\n * @returns A RegExp and parameter names array\n */\nfunction parsePathPattern(pattern: string): {\n regex: RegExp;\n paramNames: string[];\n} {\n const paramNames: string[] = [];\n // Split the pattern by dynamic parameter segments, but keep the segments in the result\n const parts = pattern.split(/(\\/:[^\\/]+)/);\n\n const regexPattern = parts\n .map((part) => {\n if (part.startsWith('/:')) {\n // This is a dynamic segment like \"/:id\"\n paramNames.push(part.substring(2)); // Extract \"id\"\n return '/([^/]+)'; // Replace with a capturing group\n }\n // This is a static segment, escape any special regex characters in it\n return part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n })\n .join('');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return { regex, paramNames };\n}\n\n/**\n * Extracts dynamic parameters from a path based on a pattern.\n * @param pattern The path pattern with dynamic parameters\n * @param path The actual path to extract parameters from\n * @returns An object with extracted parameters or null if no match\n */\nfunction extractPathParams(\n pattern: string,\n path: string\n): Record<string, string> | null {\n const { regex, paramNames } = parsePathPattern(pattern);\n const match = path.match(regex);\n\n if (!match) {\n return null;\n }\n\n const params: Record<string, string> = {};\n paramNames.forEach((paramName, index) => {\n const value = match[index + 1]; // +1 because match[0] is the full match\n if (value !== undefined) {\n params[paramName] = value;\n }\n });\n\n return params;\n}\n\n/**\n * Checks if a path pattern contains dynamic parameters.\n * @param pattern The path pattern to check\n * @returns True if the pattern contains dynamic parameters\n */\nfunction hasDynamicParams(pattern: string): boolean {\n return /\\/:[^\\/]+/.test(pattern);\n}\n\nexport type AiStreamWriter<\n METADATA = unknown,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = UIMessageStreamWriter<UIMessage<METADATA, PARTS, TOOLS>> &\n Omit<StreamWriter<METADATA, TOOLS>, 'writer'> & {\n generateId: typeof generateId;\n };\n\n// --- Core Types ---\n\n/**\n * The context object passed to every agent, tool, and middleware. It contains\n * all the necessary information and utilities for a handler to perform its work.\n * @template METADATA - The type for custom metadata in UI messages.\n * @template PARTS - The type for custom parts in UI messages.\n * @template TOOLS - The type for custom tools in UI messages.\n * @template ContextState - The type for the shared state object.\n */\nexport type AiContext<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n request: {\n /** The message history for the current request. The user can modify this array to change the message history or manipulate the message history, but beware that in the routing, the messages are passed as a reference and not a copy, making the mutatated value available to all the handlers in the request chain. */\n messages: UIMessage<METADATA, PARTS, TOOLS>[];\n /** Parameters passed from an internal tool or agent call. */\n params: PARAMS;\n [key: string]: any;\n } & METADATA;\n /** A shared, mutable state object that persists for the lifetime of a single request. */\n state: ContextState;\n /** A shared, mutable store object that persists for the lifetime of a single request. */\n store: Store;\n /**\n * Internal execution context for the router. Should not be modified by user code.\n * @internal\n */\n executionContext: {\n handlerPathStack?: string[];\n currentPath?: string;\n callDepth?: number;\n [key: string]: any;\n };\n /**\n * A unique ID for the top-level request, useful for logging and tracing.\n */\n requestId: string;\n /**\n * A structured logger that automatically includes the `requestId` and current handler path.\n */\n logger: AiLogger;\n /**\n * The stream writer to send data back to the end-user's UI.\n * Includes helpers for writing structured data like tool calls and metadata.\n */\n response: AiStreamWriter<Partial<METADATA>, PARTS, TOOLS>;\n /**\n * Provides functions for an agent to dispatch calls to other agents or tools.\n * @internal\n */\n next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n /**\n * Dispatch a background worker by ID (when @microfox/ai-worker is installed).\n * No need to import the worker module. Sends to the workers trigger API.\n */\n dispatchWorker?: (\n workerId: string,\n input?: Record<string, unknown>,\n options?: DispatchWorkerOptions\n ) => Promise<DispatchWorkerResult>;\n\n _onExecutionStart?: () => void;\n _onExecutionEnd?: () => void;\n};\n\n/** Represents the `next` function in a middleware chain, used to pass control to the next handler. */\nexport type NextFunction = () => Promise<any>;\n/** A function that handles a request for a specific agent path. */\nexport type AiHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n) => Promise<any>;\n\n/** A function that acts as middleware, processing a request and optionally passing control to the next handler. */\nexport type AiMiddleware<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n next: NextFunction\n) => Promise<any>;\n\n// --- Router Implementation ---\n\n/** A simple structured logger interface. */\nexport type AiLogger = {\n log: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\n/** Internal representation of a registered handler in the router's stack. */\ntype Layer<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n path: string | RegExp;\n handler: AiMiddleware<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n isAgent: boolean;\n // Timing for middleware: 'before' runs before agents, 'after' runs after agents\n timing?: 'before' | 'after';\n // Dynamic parameter support\n hasDynamicParams?: boolean;\n paramNames?: string[];\n};\n\nexport type AgentTool<\n INPUT extends JSONValue | unknown | never = any,\n OUTPUT extends JSONValue | unknown | never = any,\n> = Tool<INPUT, OUTPUT> & {\n name: string;\n id: string;\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n};\n\nexport type AgentData = {\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n [key: string]: any;\n};\n\n/**\n * A composable router for building structured, multi-agent AI applications.\n * It allows you to define agents and tools, compose them together, and handle\n * requests in a predictable, middleware-style pattern.\n *\n * @template KIT_METADATA - The base metadata type for all UI messages in this router.\n * @template PARTS - The base custom parts type for all UI messages.\n * @template TOOLS - The base custom tools type for all UI messages.\n * @template ContextState - The base type for the shared state object.\n */\nexport class AiRouter<\n KIT_METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = {},\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n REGISTERED_TOOLS extends ToolSet = {},\n> {\n private stack: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[] = [];\n public actAsToolDefinitions: Map<string | RegExp, AgentTool<any, any>> =\n new Map();\n private logger?: AiLogger = undefined;\n private _store: Store = new MemoryStore();\n\n /** Configuration options for the router instance. */\n public options: {\n /** The maximum number of agent-to-agent calls allowed in a single request to prevent infinite loops. */\n maxCallDepth: number;\n } = {\n maxCallDepth: 10,\n };\n\n /**\n * Constructs a new AiAgentKit router.\n * @param stack An optional initial stack of layers, used for composing routers.\n * @param options Optional configuration for the router.\n */\n constructor(\n stack?: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[],\n options?: { maxCallDepth?: number; logger?: AiLogger }\n ) {\n // Remove logger from constructor - it should be set via setLogger\n if (stack) {\n this.stack = stack;\n }\n if (options?.maxCallDepth) {\n this.options.maxCallDepth = options.maxCallDepth;\n }\n }\n\n setStore(store: Store) {\n this._store = store;\n }\n\n /**\n * Sets a logger for this router instance.\n * If no logger is set, the router will fall back to the global logger.\n * @param logger The logger to use for this router instance, or undefined to use global logger\n */\n setLogger(logger?: AiLogger) {\n this.logger = logger;\n }\n\n /**\n * Gets the effective logger for this router instance.\n * Returns instance logger if set, otherwise falls back to global logger.\n * @returns The effective logger or undefined if no logging should occur\n */\n private _getEffectiveLogger(): AiLogger | undefined {\n return this.logger ?? globalLogger;\n }\n\n /**\n * Registers a middleware-style agent that runs for a specific path prefix, regex pattern, or wildcard.\n * Agents can modify the context and must call `next()` to pass control to the next handler in the chain.\n * This method is primarily for middleware. For terminal agents, see `.agent()` on an instance.\n *\n * @param path The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param agents The agent middleware function(s).\n */\n agent<\n const TAgents extends (\n | AiMiddleware<any, any, any, any, any>\n | AiRouter<any, any, any, any, any, any>\n )[],\n >(\n agentPath:\n | string\n | RegExp\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n ...agents: TAgents\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (TAgents[number] extends AiRouter<any, any, any, any, any, infer R>\n ? R\n : {})\n > {\n let prefix: string | RegExp = '/';\n if (typeof agentPath === 'string' || agentPath instanceof RegExp) {\n prefix = agentPath;\n } else {\n agents.unshift(agentPath);\n }\n\n for (const handler of agents) {\n if (typeof handler !== 'function') {\n // Check if it's an AiRouter instance for mounting\n if (handler instanceof AiRouter && typeof prefix === 'string') {\n // Mount the router's stack directly\n const router = handler;\n const mountPath = prefix.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n }\n continue;\n }\n // Check if path has dynamic parameters\n const hasDynamic =\n typeof prefix === 'string' ? hasDynamicParams(prefix) : false;\n const paramNames =\n typeof prefix === 'string' && hasDynamic\n ? parsePathPattern(prefix).paramNames\n : undefined;\n\n this.stack.push({\n path: prefix,\n handler: handler as any,\n isAgent: true, // Mark as an agent\n hasDynamicParams: hasDynamic,\n paramNames: paramNames,\n });\n this.logger?.log(`Agent registered: path=${prefix}`);\n }\n\n return this as any;\n }\n\n /**\n * Registers middleware that runs BEFORE agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n before<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'before', // Mark as before middleware\n });\n }\n return this as any;\n }\n\n /**\n * Registers middleware that runs AFTER agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n after<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'after', // Mark as after middleware\n });\n }\n return this as any;\n }\n\n /**\n * Pre-defines the schema and description for an agent when it is used as a tool by an LLM.\n * This allows `next.agentAsTool()` to create a valid `Tool` object without needing the definition at call time.\n * @param path The path of the agent being defined.\n * @param options The tool definition, including a Zod schema and description.\n */\n actAsTool<\n const TPath extends string | RegExp,\n const TTool extends AgentTool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n >,\n >(\n path: TPath,\n options: TTool\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS & {\n [K in TTool['id']]: Tool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n > & {\n metadata: TTool['metadata'] & {\n toolKey: TTool['id'];\n name: TTool['name'];\n description: TTool['description'];\n };\n };\n }\n > {\n this.actAsToolDefinitions.set(path, options);\n this.logger?.log(`[actAsTool] Added definition: at path ${path}`);\n this.logger?.log(\n `[actAsTool] Router now has ${this.actAsToolDefinitions.size} definitions`\n );\n return this as any;\n }\n\n getToolSet(): REGISTERED_TOOLS {\n let allTools = Array.from(this.actAsToolDefinitions.entries()).map(\n ([key, value]) => {\n return {\n ...value,\n metadata: {\n ...value.metadata,\n absolutePath: key,\n },\n } as AgentTool<any, any>;\n }\n ) as AgentTool<any, any>[];\n return allTools.reduce((acc, _tool) => {\n const { inputSchema, outputSchema } = _tool;\n acc[_tool.id] = {\n ...tool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>(\n _tool\n ),\n metadata: {\n ..._tool.metadata,\n toolKey: _tool.id,\n name: _tool.name,\n description: _tool.description,\n },\n } as AgentTool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>;\n return acc;\n }, {} as any) as REGISTERED_TOOLS;\n }\n\n getToolDefinition(path: string) {\n let definition = this.actAsToolDefinitions.get(path);\n if (!definition) {\n this.logger?.error(\n `[getToolDefinition] No definition found for path: ${path}`\n );\n throw new AgentDefinitionMissingError(path);\n }\n return definition;\n }\n\n /**\n * Outputs all registered paths, and the middlewares and agents registered on each path.\n * @returns A map of paths to their registered handlers.\n */\n registry(): {\n map: Record<string, { before: any[]; agents: any[]; after: any[] }>;\n tools: REGISTERED_TOOLS;\n } {\n const registryMap: Record<\n string,\n { before: any[]; agents: any[]; after: any[] }\n > = {};\n\n for (const layer of this.stack) {\n const pathKey = layer.path.toString();\n if (!registryMap[pathKey]) {\n registryMap[pathKey] = { before: [], agents: [], after: [] };\n }\n\n if (layer.isAgent) {\n const agentInfo: any = {\n handler: layer.handler.name || 'anonymous',\n };\n const actAsToolDef = this.actAsToolDefinitions.get(layer.path);\n if (actAsToolDef) {\n agentInfo.actAsTool = {\n ...actAsToolDef,\n };\n }\n registryMap[pathKey].agents.push(agentInfo);\n } else {\n const middlewareInfo: any = {\n handler: layer.handler.name || 'anonymous',\n timing: layer.timing || 'middleware',\n };\n if (layer.timing === 'before') {\n registryMap[pathKey].before.push(middlewareInfo);\n } else if (layer.timing === 'after') {\n registryMap[pathKey].after.push(middlewareInfo);\n } else {\n // Legacy middleware without timing (shouldn't happen with new API, but handle gracefully)\n registryMap[pathKey].before.push(middlewareInfo);\n }\n }\n }\n\n return {\n map: registryMap,\n tools: this.getToolSet(),\n };\n }\n\n /**\n * Resolves a path based on the parent path and the requested path.\n * - If path starts with `@/`, it's an absolute path from the root.\n * - Otherwise, it's a relative path.\n * @internal\n */\n private _resolvePath(parentPath: string, newPath: string): string {\n if (newPath.startsWith('@/')) {\n // Absolute path from root, use POSIX normalize for consistency\n return path.posix.normalize(newPath.substring(1));\n }\n // Relative path, use POSIX join to ensure consistent behavior\n const joinedPath = path.posix.join(parentPath, newPath);\n return joinedPath;\n }\n\n /**\n * Creates a new context for an internal agent or tool call.\n * It inherits from the parent context but gets a new logger and call depth.\n * @internal\n */\n private _createSubContext(\n parentCtx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n options: {\n type: 'agent' | 'tool';\n path: string;\n messages?: UIMessage<KIT_METADATA, PARTS, TOOLS>[];\n params: PARAMS;\n }\n ) {\n const parentDepth = parentCtx.executionContext.callDepth ?? 0;\n const newCallDepth = parentDepth + (options.type === 'agent' ? 1 : 0);\n\n const subContext: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > = {\n ...parentCtx,\n // State is passed by reference to allow sub-agents to modify the parent's state.\n // The execution context is a shallow copy to ensure call-specific data is isolated.\n state: parentCtx.state,\n store: parentCtx.store,\n executionContext: {\n ...parentCtx.executionContext,\n currentPath: options.path,\n callDepth: newCallDepth,\n },\n request: {\n ...parentCtx.request,\n messages:\n options.messages ||\n parentCtx.request.messages ||\n ([] as UIMessage<KIT_METADATA, PARTS, TOOLS>[]),\n params: options.params,\n path: options.path, // The path to execute\n },\n logger: this._createLogger(\n parentCtx.requestId,\n options.path,\n newCallDepth\n ),\n next: undefined as any, // Will be replaced right after\n };\n\n // The current path for the new context is the path we are about to execute.\n subContext.executionContext.currentPath = options.path;\n\n subContext.next = new NextHandler<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n >(\n subContext,\n this,\n (parentCtx as any)._onExecutionStart,\n (parentCtx as any)._onExecutionEnd,\n parentCtx.next\n ) as any;\n\n return subContext;\n }\n\n /**\n * Creates a new logger instance with a structured prefix.\n * @internal\n */\n private _createLogger(\n requestId: string,\n path: string | RegExp,\n callDepth: number = 0\n ): AiLogger {\n const effectiveLogger = this._getEffectiveLogger();\n\n // If no logger is available, return a no-op logger\n if (!effectiveLogger) {\n return {\n log: () => { },\n warn: () => { },\n error: () => { },\n };\n }\n\n const indent = ' '.repeat(callDepth);\n const prefix = `${indent}[${path.toString()}]`;\n // Add requestId to every log message for better tracking.\n const fullPrefix = `[${requestId}]${prefix}`;\n return {\n log: (...args: any[]) => effectiveLogger.log(fullPrefix, ...args),\n warn: (...args: any[]) => effectiveLogger.warn(fullPrefix, ...args),\n error: (...args: any[]) => effectiveLogger.error(fullPrefix, ...args),\n };\n }\n\n /**\n * Calculates a specificity score for a layer to enable Express-style routing.\n * Higher score means more specific.\n * - Middleware is less specific than an agent/tool.\n * - Deeper paths are more specific.\n * - Static segments are more specific than dynamic segments.\n * @internal\n */\n private _getSpecificityScore(\n layer: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ): number {\n const path = layer.path.toString();\n let score = 0;\n\n // Base score on depth. Deeper is more specific.\n score += path.split('/').length * 100;\n\n // More dynamic segments mean less specific.\n score -= (path.match(/:/g) || []).length * 10;\n\n // Regex is less specific than a string path.\n if (layer.path instanceof RegExp) {\n score -= 50;\n }\n\n // Agents/tools are more specific than middleware.\n if (layer.isAgent) {\n score += 1;\n }\n\n return score;\n }\n\n /**\n * The core execution engine. It finds all matching layers for a given path\n * and runs them in a middleware-style chain.\n * @internal\n */\n private async _execute(\n path: string,\n ctx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n isInternalCall = false\n ) {\n // The context's `currentPath` is now the single source of truth.\n // No more stack manipulation is needed here.\n try {\n const normalizedPath =\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n ctx.logger.log(`Executing path. isInternalCall=${isInternalCall}`);\n const layersToRun = this.stack.filter((layer) => {\n let shouldRun = false;\n\n // Handle RegExp paths. For internal calls, we demand an exact match.\n if (layer.path instanceof RegExp) {\n if (isInternalCall) {\n const exactRegex = new RegExp(`^${layer.path.source}$`);\n shouldRun = exactRegex.test(normalizedPath);\n } else {\n shouldRun = layer.path.test(normalizedPath);\n }\n } else if (typeof layer.path === 'string') {\n const layerPath = layer.path;\n\n // Wildcard middleware only runs for external calls.\n if (layerPath === '*') {\n return !isInternalCall;\n }\n\n const normalizedLayerPath =\n layerPath.length > 1 && layerPath.endsWith('/')\n ? layerPath.slice(0, -1)\n : layerPath;\n\n const isExactMatch = normalizedPath === normalizedLayerPath;\n\n // Check for dynamic parameters in the layer path\n const hasDynamic = hasDynamicParams(normalizedLayerPath);\n\n if (hasDynamic) {\n // Use extractPathParams to check if the path matches the pattern\n const extractedParams = extractPathParams(normalizedLayerPath, normalizedPath);\n if (extractedParams !== null) {\n shouldRun = true;\n // Merge extracted params into ctx.request.params\n ctx.request.params = {\n ...ctx.request.params,\n ...extractedParams,\n };\n }\n } else if (isInternalCall) {\n // --- Internal Call Logic ---\n // For internal calls, we only consider exact matches for all layer types.\n shouldRun = isExactMatch;\n } else {\n // --- External Call Logic ---\n if (layer.isAgent) {\n // Agents are only matched exactly (or by dynamic params, handled above).\n shouldRun = isExactMatch;\n } else {\n // Middlewares are matched by prefix.\n shouldRun = normalizedPath.startsWith(normalizedLayerPath);\n }\n }\n }\n\n if (shouldRun) {\n ctx.logger.log(\n `[AiAgentKit][_execute] Layer MATCH: path=${normalizedPath}, layer.path=${layer.path}, isAgent=${layer.isAgent}, isInternal=${isInternalCall}`\n );\n }\n return shouldRun;\n });\n\n // Separate layers into before, agents, and after\n const beforeLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'before'\n );\n const agentLayers = layersToRun.filter((l) => l.isAgent);\n const afterLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'after'\n );\n\n // Sort each group by specificity (most general first) to ensure correct execution order.\n beforeLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n agentLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n afterLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n\n // Combine in order: before, agents, after\n const orderedLayers = [...beforeLayers, ...agentLayers, ...afterLayers];\n\n const layerDescriptions = orderedLayers.map((l) => {\n const type = l.isAgent\n ? 'agent'\n : l.timing === 'before'\n ? 'before'\n : l.timing === 'after'\n ? 'after'\n : 'middleware';\n return `${l.path.toString()} (${type})`;\n });\n ctx.logger.log(\n `Found ${orderedLayers.length} layers to run: [${layerDescriptions.join(\n ', '\n )}]`\n );\n\n if (!agentLayers.length && !beforeLayers.length && !afterLayers.length) {\n const errorMsg = `No agent or tool found for path: ${normalizedPath}`;\n ctx.logger.error(errorMsg);\n throw new AgentNotFoundError(normalizedPath);\n }\n\n // A more robust, explicit dispatcher to avoid promise chain issues.\n const dispatch = async (index: number): Promise<any> => {\n const layer = orderedLayers[index];\n if (!layer) {\n // End of the chain\n return;\n }\n\n const next = () => dispatch(index + 1);\n\n const layerPath =\n typeof layer.path === 'string' ? layer.path : layer.path.toString();\n\n const layerType = layer.isAgent\n ? 'agent'\n : layer.timing === 'before'\n ? 'before'\n : layer.timing === 'after'\n ? 'after'\n : 'middleware';\n ctx.logger.log(`-> Running ${layerType}: ${layerPath}`);\n\n try {\n if (ctx._onExecutionStart) {\n ctx._onExecutionStart();\n }\n // The handler is an async function, so we can await it directly.\n // The original Promise wrapper was redundant and could hide issues.\n const result = await layer.handler(ctx, next);\n // Agents typically don't call next(), so \"after\" middlewares would never run.\n // After an agent completes, explicitly continue the chain so .after() runs.\n if (layer.isAgent) {\n await next();\n }\n\n // if (!isInternalCall) {\n // console.log('toolDefinition', result);\n // const toolDefinition = this.actAsToolDefinitions.get(path);\n // if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n // ctx.response.writeCustomTool({\n // toolName: toolDefinition.id as string,\n // toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n // output: result,\n // });\n // }\n // }\n ctx.logger.log(`<- Finished ${layerType}: ${layerPath}`);\n return result;\n } catch (err) {\n ctx.logger.error(\n `Error in ${layerType} layer for path: ${layerPath}`,\n err\n );\n throw err;\n } finally {\n if (ctx._onExecutionEnd) {\n ctx._onExecutionEnd();\n }\n }\n };\n\n return await dispatch(0);\n } finally {\n // No-op. Stack is managed by context creation/destruction.\n }\n }\n\n private pendingExecutions = 0;\n\n /**\n * The main public entry point for the router. It handles an incoming request,\n * sets up the response stream, creates the root context, and starts the execution chain.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A standard `Response` object containing the rich UI stream.\n */\n handle(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Response {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n // --- End Execution Lifecycle Management ---\n\n return createUIMessageStreamResponse({\n stream: self.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n ),\n });\n }\n\n handleStream(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >,\n executionCompletionPromise: Promise<void>,\n executionCompletionResolver: (() => void) | null\n ) {\n const self = this;\n return createUIMessageStream({\n originalMessages: initialContext.request.messages,\n execute: async ({ writer }) => {\n const streamWriter = new StreamWriter<KIT_METADATA, TOOLS>(writer);\n const requestId = generateId();\n\n // If the configured store is a MemoryStore, create a new one for each request\n // to prevent state leakage between concurrent requests. If it's a different\n // type of store, we assume it's designed to be shared.\n const store =\n self._store instanceof MemoryStore ? new MemoryStore() : self._store;\n\n const ctx: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > & {\n _onExecutionStart: () => void;\n _onExecutionEnd: () => void;\n } = {\n ...initialContext,\n request: {\n ...initialContext.request,\n path: path, // Set the initial path for the root context\n },\n state: {} as any,\n store: store,\n executionContext: { currentPath: path, callDepth: 0 },\n requestId: requestId,\n logger: self._createLogger(requestId, path, 0),\n response: {\n ...streamWriter.writer,\n writeMessageMetadata: streamWriter.writeMessageMetadata,\n writeCustomTool: streamWriter.writeCustomTool,\n writeObjectAsTool: streamWriter.writeObjectAsTool,\n generateId: generateId,\n },\n next: undefined as any, // Will be replaced right after\n dispatchWorker,\n _onExecutionStart: () => {\n self.pendingExecutions++;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution started. Pending: ${self.pendingExecutions}`\n );\n },\n _onExecutionEnd: () => {\n self.pendingExecutions--;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution ended. Pending: ${self.pendingExecutions}`\n );\n if (self.pendingExecutions === 0 && executionCompletionResolver) {\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions finished. Resolving promise.`\n );\n executionCompletionResolver();\n }\n },\n };\n ctx.next = new NextHandler(\n ctx,\n self,\n ctx._onExecutionStart,\n ctx._onExecutionEnd\n ) as any;\n\n ctx._onExecutionStart();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain started.`\n );\n\n // Fire off the main execution chain. We don't await it here because, in a streaming\n // context, the await might resolve prematurely when the agent yields control.\n // Instead, we catch errors and use .finally() to reliably mark the end of this\n // specific execution, while the main function body waits on the lifecycle promise.\n // self\n // ._execute(path, ctx)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // // Optionally, you could write an error message to the stream here.\n // })\n // .finally(() => {\n // ctx._onExecutionEnd();\n // });\n\n try {\n const response = await self._execute(path, ctx);\n const toolDefinition = this.actAsToolDefinitions.get(path);\n if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n ctx.response.writeCustomTool({\n toolName: toolDefinition.id as string,\n toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n output: response,\n });\n }\n return response;\n } catch (err) {\n ctx.logger.error('Unhandled error in main execution chain', err);\n } finally {\n ctx._onExecutionEnd();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain finished.`\n );\n }\n\n // ctx.next\n // .callAgent(path, initialContext.request.params)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // });\n\n // Wait for the promise that resolves only when all executions (the main one\n // and all sub-calls) have completed.\n await executionCompletionPromise;\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions truly finished. Stream can be safely closed.`\n );\n },\n });\n }\n\n /**\n * Handles an incoming request and returns a promise that resolves with the full,\n * non-streamed response. This is useful for environments where streaming is not\n * desired or for testing.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A `Promise<Response>` that resolves with the final JSON response.\n */\n async toAwaitResponse(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Promise<Response> {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n const stream = this.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n );\n\n const messageStream = readUIMessageStream({\n stream,\n onError: (error) => {\n this.logger?.error('Error reading UI message stream', error);\n },\n });\n\n let finalMessages: UIMessage[] = [];\n const thisMessageId = generateId();\n for await (const message of messageStream) {\n if (message.id?.length > 0) {\n finalMessages.push(message);\n } else if (finalMessages.find((m) => m.id === thisMessageId)) {\n finalMessages = finalMessages.map((m) =>\n m.id === thisMessageId\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n ...(message.metadata ?? {}),\n },\n parts: clubParts([\n ...(m.parts ?? []),\n ...(message.parts ?? []),\n ]),\n }\n : m\n );\n } else {\n finalMessages.push({\n ...message,\n id: thisMessageId,\n });\n }\n }\n const responseBody = JSON.stringify(finalMessages);\n return new Response(responseBody, {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n}\n\nexport type AiRouterType = typeof AiRouter;\n\nclass NextHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> {\n public maxCallDepth: number;\n\n constructor(\n private ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private router: AiRouter<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private onExecutionStart: () => void,\n private onExecutionEnd: () => void,\n parentNext?: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ) {\n this.maxCallDepth = this.router.options.maxCallDepth;\n }\n\n async callAgent(\n agentPath: string,\n params?: Record<string, any>,\n options?: {\n streamToUI?: boolean;\n }\n ): Promise<{ ok: true; data: any } | { ok: false; error: Error }> {\n this.onExecutionStart();\n try {\n const currentDepth = this.ctx.executionContext.callDepth ?? 0;\n if (currentDepth >= this.maxCallDepth) {\n const err = new MaxCallDepthExceededError(this.maxCallDepth);\n this.ctx.logger.error(`[callAgent] Aborting. ${err.message}`);\n throw err;\n }\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n this.ctx.logger.log(`Calling agent: resolvedPath='${resolvedPath}'`);\n\n const subContext = (this.router as any)._createSubContext(this.ctx, {\n type: 'agent',\n path: resolvedPath,\n params: params ?? ({} as PARAMS),\n messages: this.ctx.request.messages,\n });\n\n const definition = this.router.actAsToolDefinitions.get(resolvedPath);\n const toolCallId = definition?.id + '-' + this.ctx.response.generateId();\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n input: subContext.request.params,\n });\n }\n\n const data = await (this.router as any)._execute(\n resolvedPath,\n subContext,\n true\n );\n\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n output: data,\n });\n }\n\n return { ok: true, data };\n } catch (error: any) {\n this.ctx.logger.error(`[callAgent] Error:`, error);\n return { ok: false, error };\n } finally {\n this.onExecutionEnd();\n }\n }\n\n agentAsTool<INPUT extends JSONValue | unknown | never = any, OUTPUT = any>(\n agentPath: string,\n schemaControl?: Record<string, any> & { disableAllInputs?: boolean }\n ) {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n const definition = this.getToolDefinition(agentPath);\n\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n throw new AgentDefinitionMissingError(resolvedPath);\n }\n\n const originalSchema = definition.inputSchema as ZodObject<any> | undefined;\n let finalSchema = originalSchema;\n const fixedParams: Record<string, any> = {};\n\n if (schemaControl) {\n if (schemaControl.disableAllInputs) {\n finalSchema = z.object({});\n } else if (originalSchema) {\n let isPickMode = false;\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n isPickMode = true;\n break;\n }\n }\n\n if (isPickMode) {\n const pickShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n pickShape[key] = true;\n } else {\n fixedParams[key] = schemaControl[key];\n }\n }\n finalSchema = originalSchema.pick(pickShape);\n } else {\n // Omit mode\n const omitShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (key !== 'disableAllInputs') {\n fixedParams[key] = schemaControl[key];\n omitShape[key] = true;\n }\n }\n finalSchema = originalSchema.omit(omitShape);\n }\n }\n }\n\n const { id, metadata, ...restDefinition } = definition;\n\n (restDefinition as { inputSchema?: unknown }).inputSchema = finalSchema;\n\n return {\n [id]: {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n execute: async (params: any, options: any) => {\n const result = await this.callAgent(agentPath, params, options);\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n },\n } as Tool<INPUT, OUTPUT>,\n };\n }\n\n getToolDefinition(\n agentPath: string | RegExp\n ): AgentTool<any, any> | undefined {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath.toString()\n );\n let preDefined;\n const pathsToTry = [resolvedPath];\n // If the agentPath starts with '/', it's an absolute path from root, so also try it directly\n if (typeof agentPath === 'string' && agentPath.startsWith('/')) {\n pathsToTry.unshift(agentPath);\n }\n for (const pathToTry of pathsToTry) {\n for (const [key, value] of (this.router as any).actAsToolDefinitions) {\n if (typeof key === 'string') {\n // Check for exact match first\n if (key === pathToTry) {\n preDefined = value;\n break;\n }\n // Then check for dynamic path parameters\n if (extractPathParams(key, pathToTry) !== null) {\n preDefined = value;\n break;\n }\n }\n // Basic RegExp match\n if (key instanceof RegExp && key.test(pathToTry)) {\n preDefined = value;\n break;\n }\n }\n if (preDefined) break;\n }\n\n const definition = preDefined;\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n return undefined;\n }\n const { metadata, ...restDefinition } = definition;\n return {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: restDefinition.id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n } as AgentTool<any, any>;\n }\n\n\n /** \n * Deprecated execute style for L1402\n * execute: (params: any, options: any) => {\n const finalParams = { ...params, ...fixedParams };\n \n const executeInternal = async () => {\n const result = await this.callAgent(\n agentPath,\n finalParams,\n options\n );\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n };\n \n const newPromise = this.router.toolExecutionPromise.then(\n executeInternal,\n executeInternal\n );\n this.router.toolExecutionPromise = newPromise;\n return newPromise;\n *\n */\n\n}\n","import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import {\n GenerateObjectResult,\n UIDataTypes,\n UIMessage,\n UIMessageStreamWriter,\n} from 'ai';\nimport { UITools } from './types.js';\nimport { customAlphabet } from 'nanoid';\n\nexport const findLastElement = <T>(array: T[]) => {\n return array[array.length - 1];\n};\n\nexport const findFirstElement = <T>(array: T[]) => {\n return array[0];\n};\n\nexport class StreamWriter<METADATA, TOOLS extends UITools> {\n public writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>;\n constructor(writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>) {\n this.writer = writer;\n }\n generateId = () => {\n return customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 10)();\n };\n writeMessageMetadata = <NEW_METADATA extends METADATA>(\n metadata: NEW_METADATA\n ) => {\n return this.writer.write({\n type: 'message-metadata' as const,\n messageMetadata: metadata as NEW_METADATA,\n });\n };\n writeCustomTool = <K extends keyof TOOLS>(tool: {\n toolCallId?: string;\n toolName: K;\n inputTextDelta?: string[];\n input?: any;\n output?: any;\n }) => {\n const toolCallId =\n tool.toolCallId || tool.toolName?.toString() + '-' + this.generateId();\n if ('input' in tool && tool.input) {\n this.writer.write({\n type: 'tool-input-available' as const,\n input: tool.input,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n }\n if (\n (tool.inputTextDelta && tool.inputTextDelta.length > 0) ||\n ('output' in tool && tool.output)\n ) {\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n if (tool.inputTextDelta) {\n for (const delta of tool.inputTextDelta) {\n this.writer.write({\n type: 'tool-input-delta' as const,\n toolCallId: toolCallId,\n inputTextDelta: delta,\n });\n }\n }\n }\n if ('output' in tool && tool.output) {\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.output,\n });\n }\n };\n writeObjectAsTool = <K extends keyof TOOLS>(tool: {\n toolName: K;\n result?: GenerateObjectResult<TOOLS[K]['output']>;\n input?: GenerateObjectResult<TOOLS[K]['input']>;\n }) => {\n if (!tool.result?.object) {\n throw new Error('No object found in the GenerateObjectResult');\n }\n\n const toolCallId = tool.toolName.toString() + '-' + this.generateId();\n\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-input-available' as const,\n toolCallId: toolCallId,\n input:\n (tool.input ?? tool.result)\n ? {\n usage: tool.result?.usage,\n warnings: tool.result?.warnings,\n finishReason: tool.result?.finishReason,\n }\n : undefined,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.result?.object,\n });\n };\n}\n\nexport const getTextParts = (message: UIMessage | null | undefined) => {\n if (!message) return [];\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text);\n};\n\nexport const getTextPartsContent = (message: UIMessage | null | undefined) => {\n if (!message) return '';\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('')\n .trim();\n};\n\nexport const findLastMessageWith = <T>(\n message: UIMessage[] | null | undefined,\n filters: {\n role?: 'user' | 'assistant' | 'system';\n metadata?: Record<string, any>;\n }\n) => {\n if (!message) return null;\n return message\n .filter((m) => {\n if (filters.role && m.role !== filters.role) return false;\n if (filters.metadata) {\n for (const key in filters.metadata) {\n }\n }\n return true;\n })\n .pop();\n};\n","export interface Store {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n delete(key: string): Promise<void>;\n has(key: string): Promise<boolean>;\n entries?(): Promise<[string, any][]>;\n clear?(): Promise<void>;\n}\n\n/**\n * An in-memory implementation of the `Store` interface.\n *\n * @remarks\n * Each instance of `MemoryStore` maintains its own isolated key-value map.\n * In a server environment where a single `AiRouter` instance handles multiple\n * concurrent requests, the router's `handle` method automatically creates a new\n * `MemoryStore` for each request to ensure state isolation. This prevents\n * data leakage between different requests.\n */\nexport class MemoryStore implements Store {\n private store = new Map<string, any>();\n\n async get<T>(key: string): Promise<T | undefined> {\n return this.store.get(key);\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n this.store.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async has(key: string): Promise<boolean> {\n return this.store.has(key);\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;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AAe,IAAI;AACxC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,UAAU;AAAA,QACR,GAAG;AAAA,QACH,SAAS,eAAe;AAAA,QACxB,MAAM,eAAe;AAAA,QACrB,aAAa,eAAe;AAAA,QAC5B,cAAc;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BF;","names":["crypto","tool","path"]}
|
package/dist/index.mjs
CHANGED
|
@@ -171,6 +171,50 @@ var MemoryStore = class {
|
|
|
171
171
|
};
|
|
172
172
|
|
|
173
173
|
// src/router.ts
|
|
174
|
+
function getWorkersTriggerUrl() {
|
|
175
|
+
const raw = process.env.WORKER_BASE_URL || process.env.WORKERS_TRIGGER_API_URL || process.env.WORKERS_CONFIG_API_URL;
|
|
176
|
+
if (!raw) {
|
|
177
|
+
throw new Error("WORKER_BASE_URL is required for ctx.dispatchWorker. Set it server-side only.");
|
|
178
|
+
}
|
|
179
|
+
const url = new URL(raw);
|
|
180
|
+
url.search = "";
|
|
181
|
+
url.hash = "";
|
|
182
|
+
const pathname = url.pathname || "";
|
|
183
|
+
url.pathname = pathname.replace(/\/?workers\/(trigger|config)\/?$/, "");
|
|
184
|
+
const basePath = url.pathname.replace(/\/+$/, "");
|
|
185
|
+
url.pathname = `${basePath}/workers/trigger`.replace(/\/+$/, "");
|
|
186
|
+
return url.toString();
|
|
187
|
+
}
|
|
188
|
+
async function dispatchWorker(workerId, input, options = {}) {
|
|
189
|
+
const jobId = options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;
|
|
190
|
+
const triggerUrl = getWorkersTriggerUrl();
|
|
191
|
+
const messageBody = {
|
|
192
|
+
workerId,
|
|
193
|
+
jobId,
|
|
194
|
+
input: input ?? {},
|
|
195
|
+
context: {},
|
|
196
|
+
webhookUrl: options.webhookUrl,
|
|
197
|
+
metadata: options.metadata || {},
|
|
198
|
+
timestamp: (/* @__PURE__ */ new Date()).toISOString()
|
|
199
|
+
};
|
|
200
|
+
const headers = { "Content-Type": "application/json" };
|
|
201
|
+
const key = process.env.WORKERS_TRIGGER_API_KEY;
|
|
202
|
+
if (key) headers["x-workers-trigger-key"] = key;
|
|
203
|
+
const response = await fetch(triggerUrl, {
|
|
204
|
+
method: "POST",
|
|
205
|
+
headers,
|
|
206
|
+
body: JSON.stringify({ workerId, body: messageBody })
|
|
207
|
+
});
|
|
208
|
+
if (!response.ok) {
|
|
209
|
+
const text = await response.text().catch(() => "");
|
|
210
|
+
throw new Error(
|
|
211
|
+
`Failed to trigger worker "${workerId}": ${response.status} ${response.statusText}${text ? ` - ${text}` : ""}`
|
|
212
|
+
);
|
|
213
|
+
}
|
|
214
|
+
const data = await response.json().catch(() => ({}));
|
|
215
|
+
const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;
|
|
216
|
+
return { messageId, status: "queued", jobId };
|
|
217
|
+
}
|
|
174
218
|
var globalLogger = void 0;
|
|
175
219
|
function setGlobalLogger(logger) {
|
|
176
220
|
globalLogger = logger;
|
|
@@ -829,6 +873,7 @@ var AiRouter = class _AiRouter {
|
|
|
829
873
|
},
|
|
830
874
|
next: void 0,
|
|
831
875
|
// Will be replaced right after
|
|
876
|
+
dispatchWorker,
|
|
832
877
|
_onExecutionStart: () => {
|
|
833
878
|
self.pendingExecutions++;
|
|
834
879
|
self.logger?.log(
|
package/dist/index.mjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/router.ts","../../../node_modules/nanoid/index.js","../src/helper.ts","../src/store.ts"],"sourcesContent":["import {\n UIMessage,\n createUIMessageStream,\n UIMessageStreamWriter,\n createUIMessageStreamResponse,\n UIDataTypes,\n generateId,\n Tool,\n tool,\n JSONValue,\n ToolCallOptions,\n convertToModelMessages,\n ToolSet,\n DataUIPart,\n pipeUIMessageStreamToResponse,\n readUIMessageStream,\n} from 'ai';\nimport { StreamWriter } from './helper.js';\nimport { UITools } from './types.js';\nimport { z, ZodObject, ZodType } from 'zod';\nimport path from 'path';\nimport { Store, MemoryStore } from './store.js';\n\n// Add global logger management\nlet globalLogger: AiLogger | undefined = undefined;\n\n/**\n * Sets a global logger that will be used by all router instances when no instance-specific logger is set.\n * This is useful for debugging across multiple router instances.\n * @param logger The logger to use globally, or undefined to disable global logging\n */\nexport function setGlobalLogger(logger?: AiLogger) {\n globalLogger = logger;\n}\n\n/**\n * Gets the current global logger.\n * @returns The current global logger or undefined if none is set\n */\nexport function getGlobalLogger(): AiLogger | undefined {\n return globalLogger;\n}\n\n// --- Helper Functions ---\n/**\n * Clubs parts based on toolCallId for tool-* types and id for data-* types\n * @param parts Array of parts to club\n * @returns Clubbed parts array\n */\nfunction clubParts(parts: any[]): any[] {\n if (!parts || parts.length === 0) return parts;\n\n const clubbedParts: any[] = [];\n const toolCallIdGroups = new Map<string, any[]>();\n const dataIdGroups = new Map<string, any[]>();\n\n // Group parts by toolCallId for tool-* types and by id for data-* types\n for (const part of parts) {\n if (part.type?.startsWith('tool-') && (part as any).toolCallId) {\n const toolCallId = (part as any).toolCallId;\n if (!toolCallIdGroups.has(toolCallId)) {\n toolCallIdGroups.set(toolCallId, []);\n }\n toolCallIdGroups.get(toolCallId)!.push(part);\n } else if (part.type?.startsWith('data-') && part.id) {\n const id = part.id;\n if (!dataIdGroups.has(id)) {\n dataIdGroups.set(id, []);\n }\n dataIdGroups.get(id)!.push(part);\n } else {\n // For parts that don't match the clubbing criteria, add them directly\n clubbedParts.push(part);\n }\n }\n\n // Add clubbed tool parts\n for (const [toolCallId, toolParts] of toolCallIdGroups) {\n if (toolParts.length === 1) {\n clubbedParts.push(toolParts[0]);\n } else {\n // Merge multiple parts with same toolCallId\n const mergedPart = { ...toolParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < toolParts.length; i++) {\n const currentPart = toolParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'toolCallId') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n // Add clubbed data parts\n for (const [id, dataParts] of dataIdGroups) {\n if (dataParts.length === 1) {\n clubbedParts.push(dataParts[0]);\n } else {\n // Merge multiple parts with same id\n const mergedPart = { ...dataParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < dataParts.length; i++) {\n const currentPart = dataParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'id') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n return clubbedParts;\n}\n\n// --- Custom Errors ---\nexport class AiKitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AiKitError';\n }\n}\n\nexport class AgentNotFoundError extends AiKitError {\n constructor(path: string) {\n super(`[AiAgentKit] Agent not found for path: ${path}`);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class MaxCallDepthExceededError extends AiKitError {\n constructor(maxDepth: number) {\n super(`[AiAgentKit] Agent call depth limit (${maxDepth}) exceeded.`);\n this.name = 'MaxCallDepthExceededError';\n }\n}\n\nexport class AgentDefinitionMissingError extends AiKitError {\n constructor(path: string) {\n super(\n `[AiAgentKit] agentAsTool: No definition found for \"${path}\". Please define it using '.actAsTool()' or pass a definition as the second argument.`\n );\n this.name = 'AgentDefinitionMissingError';\n }\n}\n\n// --- Dynamic Parameter Support ---\n\n/**\n * Converts a path pattern with dynamic parameters (e.g., \"/users/:id/posts/:postId\")\n * into a RegExp that can match actual paths and extract parameters.\n * @param pattern The path pattern with dynamic parameters\n * @returns A RegExp and parameter names array\n */\nfunction parsePathPattern(pattern: string): {\n regex: RegExp;\n paramNames: string[];\n} {\n const paramNames: string[] = [];\n // Split the pattern by dynamic parameter segments, but keep the segments in the result\n const parts = pattern.split(/(\\/:[^\\/]+)/);\n\n const regexPattern = parts\n .map((part) => {\n if (part.startsWith('/:')) {\n // This is a dynamic segment like \"/:id\"\n paramNames.push(part.substring(2)); // Extract \"id\"\n return '/([^/]+)'; // Replace with a capturing group\n }\n // This is a static segment, escape any special regex characters in it\n return part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n })\n .join('');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return { regex, paramNames };\n}\n\n/**\n * Extracts dynamic parameters from a path based on a pattern.\n * @param pattern The path pattern with dynamic parameters\n * @param path The actual path to extract parameters from\n * @returns An object with extracted parameters or null if no match\n */\nfunction extractPathParams(\n pattern: string,\n path: string\n): Record<string, string> | null {\n const { regex, paramNames } = parsePathPattern(pattern);\n const match = path.match(regex);\n\n if (!match) {\n return null;\n }\n\n const params: Record<string, string> = {};\n paramNames.forEach((paramName, index) => {\n const value = match[index + 1]; // +1 because match[0] is the full match\n if (value !== undefined) {\n params[paramName] = value;\n }\n });\n\n return params;\n}\n\n/**\n * Checks if a path pattern contains dynamic parameters.\n * @param pattern The path pattern to check\n * @returns True if the pattern contains dynamic parameters\n */\nfunction hasDynamicParams(pattern: string): boolean {\n return /\\/:[^\\/]+/.test(pattern);\n}\n\nexport type AiStreamWriter<\n METADATA = unknown,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = UIMessageStreamWriter<UIMessage<METADATA, PARTS, TOOLS>> &\n Omit<StreamWriter<METADATA, TOOLS>, 'writer'> & {\n generateId: typeof generateId;\n };\n\n// --- Core Types ---\n\n/**\n * The context object passed to every agent, tool, and middleware. It contains\n * all the necessary information and utilities for a handler to perform its work.\n * @template METADATA - The type for custom metadata in UI messages.\n * @template PARTS - The type for custom parts in UI messages.\n * @template TOOLS - The type for custom tools in UI messages.\n * @template ContextState - The type for the shared state object.\n */\nexport type AiContext<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n request: {\n /** The message history for the current request. The user can modify this array to change the message history or manipulate the message history, but beware that in the routing, the messages are passed as a reference and not a copy, making the mutatated value available to all the handlers in the request chain. */\n messages: UIMessage<METADATA, PARTS, TOOLS>[];\n /** Parameters passed from an internal tool or agent call. */\n params: PARAMS;\n [key: string]: any;\n } & METADATA;\n /** A shared, mutable state object that persists for the lifetime of a single request. */\n state: ContextState;\n /** A shared, mutable store object that persists for the lifetime of a single request. */\n store: Store;\n /**\n * Internal execution context for the router. Should not be modified by user code.\n * @internal\n */\n executionContext: {\n handlerPathStack?: string[];\n currentPath?: string;\n callDepth?: number;\n [key: string]: any;\n };\n /**\n * A unique ID for the top-level request, useful for logging and tracing.\n */\n requestId: string;\n /**\n * A structured logger that automatically includes the `requestId` and current handler path.\n */\n logger: AiLogger;\n /**\n * The stream writer to send data back to the end-user's UI.\n * Includes helpers for writing structured data like tool calls and metadata.\n */\n response: AiStreamWriter<Partial<METADATA>, PARTS, TOOLS>;\n /**\n * Provides functions for an agent to dispatch calls to other agents or tools.\n * @internal\n */\n next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n\n _onExecutionStart?: () => void;\n _onExecutionEnd?: () => void;\n};\n\n/** Represents the `next` function in a middleware chain, used to pass control to the next handler. */\nexport type NextFunction = () => Promise<any>;\n/** A function that handles a request for a specific agent path. */\nexport type AiHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n) => Promise<any>;\n\n/** A function that acts as middleware, processing a request and optionally passing control to the next handler. */\nexport type AiMiddleware<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n next: NextFunction\n) => Promise<any>;\n\n// --- Router Implementation ---\n\n/** A simple structured logger interface. */\nexport type AiLogger = {\n log: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\n/** Internal representation of a registered handler in the router's stack. */\ntype Layer<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n path: string | RegExp;\n handler: AiMiddleware<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n isAgent: boolean;\n // Timing for middleware: 'before' runs before agents, 'after' runs after agents\n timing?: 'before' | 'after';\n // Dynamic parameter support\n hasDynamicParams?: boolean;\n paramNames?: string[];\n};\n\nexport type AgentTool<\n INPUT extends JSONValue | unknown | never = any,\n OUTPUT extends JSONValue | unknown | never = any,\n> = Tool<INPUT, OUTPUT> & {\n name: string;\n id: string;\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n};\n\nexport type AgentData = {\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n [key: string]: any;\n};\n\n/**\n * A composable router for building structured, multi-agent AI applications.\n * It allows you to define agents and tools, compose them together, and handle\n * requests in a predictable, middleware-style pattern.\n *\n * @template KIT_METADATA - The base metadata type for all UI messages in this router.\n * @template PARTS - The base custom parts type for all UI messages.\n * @template TOOLS - The base custom tools type for all UI messages.\n * @template ContextState - The base type for the shared state object.\n */\nexport class AiRouter<\n KIT_METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = {},\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n REGISTERED_TOOLS extends ToolSet = {},\n> {\n private stack: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[] = [];\n public actAsToolDefinitions: Map<string | RegExp, AgentTool<any, any>> =\n new Map();\n private logger?: AiLogger = undefined;\n private _store: Store = new MemoryStore();\n\n /** Configuration options for the router instance. */\n public options: {\n /** The maximum number of agent-to-agent calls allowed in a single request to prevent infinite loops. */\n maxCallDepth: number;\n } = {\n maxCallDepth: 10,\n };\n\n /**\n * Constructs a new AiAgentKit router.\n * @param stack An optional initial stack of layers, used for composing routers.\n * @param options Optional configuration for the router.\n */\n constructor(\n stack?: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[],\n options?: { maxCallDepth?: number; logger?: AiLogger }\n ) {\n // Remove logger from constructor - it should be set via setLogger\n if (stack) {\n this.stack = stack;\n }\n if (options?.maxCallDepth) {\n this.options.maxCallDepth = options.maxCallDepth;\n }\n }\n\n setStore(store: Store) {\n this._store = store;\n }\n\n /**\n * Sets a logger for this router instance.\n * If no logger is set, the router will fall back to the global logger.\n * @param logger The logger to use for this router instance, or undefined to use global logger\n */\n setLogger(logger?: AiLogger) {\n this.logger = logger;\n }\n\n /**\n * Gets the effective logger for this router instance.\n * Returns instance logger if set, otherwise falls back to global logger.\n * @returns The effective logger or undefined if no logging should occur\n */\n private _getEffectiveLogger(): AiLogger | undefined {\n return this.logger ?? globalLogger;\n }\n\n /**\n * Registers a middleware-style agent that runs for a specific path prefix, regex pattern, or wildcard.\n * Agents can modify the context and must call `next()` to pass control to the next handler in the chain.\n * This method is primarily for middleware. For terminal agents, see `.agent()` on an instance.\n *\n * @param path The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param agents The agent middleware function(s).\n */\n agent<\n const TAgents extends (\n | AiMiddleware<any, any, any, any, any>\n | AiRouter<any, any, any, any, any, any>\n )[],\n >(\n agentPath:\n | string\n | RegExp\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n ...agents: TAgents\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (TAgents[number] extends AiRouter<any, any, any, any, any, infer R>\n ? R\n : {})\n > {\n let prefix: string | RegExp = '/';\n if (typeof agentPath === 'string' || agentPath instanceof RegExp) {\n prefix = agentPath;\n } else {\n agents.unshift(agentPath);\n }\n\n for (const handler of agents) {\n if (typeof handler !== 'function') {\n // Check if it's an AiRouter instance for mounting\n if (handler instanceof AiRouter && typeof prefix === 'string') {\n // Mount the router's stack directly\n const router = handler;\n const mountPath = prefix.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n }\n continue;\n }\n // Check if path has dynamic parameters\n const hasDynamic =\n typeof prefix === 'string' ? hasDynamicParams(prefix) : false;\n const paramNames =\n typeof prefix === 'string' && hasDynamic\n ? parsePathPattern(prefix).paramNames\n : undefined;\n\n this.stack.push({\n path: prefix,\n handler: handler as any,\n isAgent: true, // Mark as an agent\n hasDynamicParams: hasDynamic,\n paramNames: paramNames,\n });\n this.logger?.log(`Agent registered: path=${prefix}`);\n }\n\n return this as any;\n }\n\n /**\n * Registers middleware that runs BEFORE agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n before<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'before', // Mark as before middleware\n });\n }\n return this as any;\n }\n\n /**\n * Registers middleware that runs AFTER agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n after<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'after', // Mark as after middleware\n });\n }\n return this as any;\n }\n\n /**\n * Pre-defines the schema and description for an agent when it is used as a tool by an LLM.\n * This allows `next.agentAsTool()` to create a valid `Tool` object without needing the definition at call time.\n * @param path The path of the agent being defined.\n * @param options The tool definition, including a Zod schema and description.\n */\n actAsTool<\n const TPath extends string | RegExp,\n const TTool extends AgentTool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n >,\n >(\n path: TPath,\n options: TTool\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS & {\n [K in TTool['id']]: Tool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n > & {\n metadata: TTool['metadata'] & {\n toolKey: TTool['id'];\n name: TTool['name'];\n description: TTool['description'];\n };\n };\n }\n > {\n this.actAsToolDefinitions.set(path, options);\n this.logger?.log(`[actAsTool] Added definition: at path ${path}`);\n this.logger?.log(\n `[actAsTool] Router now has ${this.actAsToolDefinitions.size} definitions`\n );\n return this as any;\n }\n\n getToolSet(): REGISTERED_TOOLS {\n let allTools = Array.from(this.actAsToolDefinitions.entries()).map(\n ([key, value]) => {\n return {\n ...value,\n metadata: {\n ...value.metadata,\n absolutePath: key,\n },\n } as AgentTool<any, any>;\n }\n ) as AgentTool<any, any>[];\n return allTools.reduce((acc, _tool) => {\n const { inputSchema, outputSchema } = _tool;\n acc[_tool.id] = {\n ...tool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>(\n _tool\n ),\n metadata: {\n ..._tool.metadata,\n toolKey: _tool.id,\n name: _tool.name,\n description: _tool.description,\n },\n } as AgentTool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>;\n return acc;\n }, {} as any) as REGISTERED_TOOLS;\n }\n\n getToolDefinition(path: string) {\n let definition = this.actAsToolDefinitions.get(path);\n if (!definition) {\n this.logger?.error(\n `[getToolDefinition] No definition found for path: ${path}`\n );\n throw new AgentDefinitionMissingError(path);\n }\n return definition;\n }\n\n /**\n * Outputs all registered paths, and the middlewares and agents registered on each path.\n * @returns A map of paths to their registered handlers.\n */\n registry(): {\n map: Record<string, { before: any[]; agents: any[]; after: any[] }>;\n tools: REGISTERED_TOOLS;\n } {\n const registryMap: Record<\n string,\n { before: any[]; agents: any[]; after: any[] }\n > = {};\n\n for (const layer of this.stack) {\n const pathKey = layer.path.toString();\n if (!registryMap[pathKey]) {\n registryMap[pathKey] = { before: [], agents: [], after: [] };\n }\n\n if (layer.isAgent) {\n const agentInfo: any = {\n handler: layer.handler.name || 'anonymous',\n };\n const actAsToolDef = this.actAsToolDefinitions.get(layer.path);\n if (actAsToolDef) {\n agentInfo.actAsTool = {\n ...actAsToolDef,\n };\n }\n registryMap[pathKey].agents.push(agentInfo);\n } else {\n const middlewareInfo: any = {\n handler: layer.handler.name || 'anonymous',\n timing: layer.timing || 'middleware',\n };\n if (layer.timing === 'before') {\n registryMap[pathKey].before.push(middlewareInfo);\n } else if (layer.timing === 'after') {\n registryMap[pathKey].after.push(middlewareInfo);\n } else {\n // Legacy middleware without timing (shouldn't happen with new API, but handle gracefully)\n registryMap[pathKey].before.push(middlewareInfo);\n }\n }\n }\n\n return {\n map: registryMap,\n tools: this.getToolSet(),\n };\n }\n\n /**\n * Resolves a path based on the parent path and the requested path.\n * - If path starts with `@/`, it's an absolute path from the root.\n * - Otherwise, it's a relative path.\n * @internal\n */\n private _resolvePath(parentPath: string, newPath: string): string {\n if (newPath.startsWith('@/')) {\n // Absolute path from root, use POSIX normalize for consistency\n return path.posix.normalize(newPath.substring(1));\n }\n // Relative path, use POSIX join to ensure consistent behavior\n const joinedPath = path.posix.join(parentPath, newPath);\n return joinedPath;\n }\n\n /**\n * Creates a new context for an internal agent or tool call.\n * It inherits from the parent context but gets a new logger and call depth.\n * @internal\n */\n private _createSubContext(\n parentCtx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n options: {\n type: 'agent' | 'tool';\n path: string;\n messages?: UIMessage<KIT_METADATA, PARTS, TOOLS>[];\n params: PARAMS;\n }\n ) {\n const parentDepth = parentCtx.executionContext.callDepth ?? 0;\n const newCallDepth = parentDepth + (options.type === 'agent' ? 1 : 0);\n\n const subContext: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > = {\n ...parentCtx,\n // State is passed by reference to allow sub-agents to modify the parent's state.\n // The execution context is a shallow copy to ensure call-specific data is isolated.\n state: parentCtx.state,\n store: parentCtx.store,\n executionContext: {\n ...parentCtx.executionContext,\n currentPath: options.path,\n callDepth: newCallDepth,\n },\n request: {\n ...parentCtx.request,\n messages:\n options.messages ||\n parentCtx.request.messages ||\n ([] as UIMessage<KIT_METADATA, PARTS, TOOLS>[]),\n params: options.params,\n path: options.path, // The path to execute\n },\n logger: this._createLogger(\n parentCtx.requestId,\n options.path,\n newCallDepth\n ),\n next: undefined as any, // Will be replaced right after\n };\n\n // The current path for the new context is the path we are about to execute.\n subContext.executionContext.currentPath = options.path;\n\n subContext.next = new NextHandler<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n >(\n subContext,\n this,\n (parentCtx as any)._onExecutionStart,\n (parentCtx as any)._onExecutionEnd,\n parentCtx.next\n ) as any;\n\n return subContext;\n }\n\n /**\n * Creates a new logger instance with a structured prefix.\n * @internal\n */\n private _createLogger(\n requestId: string,\n path: string | RegExp,\n callDepth: number = 0\n ): AiLogger {\n const effectiveLogger = this._getEffectiveLogger();\n\n // If no logger is available, return a no-op logger\n if (!effectiveLogger) {\n return {\n log: () => { },\n warn: () => { },\n error: () => { },\n };\n }\n\n const indent = ' '.repeat(callDepth);\n const prefix = `${indent}[${path.toString()}]`;\n // Add requestId to every log message for better tracking.\n const fullPrefix = `[${requestId}]${prefix}`;\n return {\n log: (...args: any[]) => effectiveLogger.log(fullPrefix, ...args),\n warn: (...args: any[]) => effectiveLogger.warn(fullPrefix, ...args),\n error: (...args: any[]) => effectiveLogger.error(fullPrefix, ...args),\n };\n }\n\n /**\n * Calculates a specificity score for a layer to enable Express-style routing.\n * Higher score means more specific.\n * - Middleware is less specific than an agent/tool.\n * - Deeper paths are more specific.\n * - Static segments are more specific than dynamic segments.\n * @internal\n */\n private _getSpecificityScore(\n layer: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ): number {\n const path = layer.path.toString();\n let score = 0;\n\n // Base score on depth. Deeper is more specific.\n score += path.split('/').length * 100;\n\n // More dynamic segments mean less specific.\n score -= (path.match(/:/g) || []).length * 10;\n\n // Regex is less specific than a string path.\n if (layer.path instanceof RegExp) {\n score -= 50;\n }\n\n // Agents/tools are more specific than middleware.\n if (layer.isAgent) {\n score += 1;\n }\n\n return score;\n }\n\n /**\n * The core execution engine. It finds all matching layers for a given path\n * and runs them in a middleware-style chain.\n * @internal\n */\n private async _execute(\n path: string,\n ctx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n isInternalCall = false\n ) {\n // The context's `currentPath` is now the single source of truth.\n // No more stack manipulation is needed here.\n try {\n const normalizedPath =\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n ctx.logger.log(`Executing path. isInternalCall=${isInternalCall}`);\n const layersToRun = this.stack.filter((layer) => {\n let shouldRun = false;\n\n // Handle RegExp paths. For internal calls, we demand an exact match.\n if (layer.path instanceof RegExp) {\n if (isInternalCall) {\n const exactRegex = new RegExp(`^${layer.path.source}$`);\n shouldRun = exactRegex.test(normalizedPath);\n } else {\n shouldRun = layer.path.test(normalizedPath);\n }\n } else if (typeof layer.path === 'string') {\n const layerPath = layer.path;\n\n // Wildcard middleware only runs for external calls.\n if (layerPath === '*') {\n return !isInternalCall;\n }\n\n const normalizedLayerPath =\n layerPath.length > 1 && layerPath.endsWith('/')\n ? layerPath.slice(0, -1)\n : layerPath;\n\n const isExactMatch = normalizedPath === normalizedLayerPath;\n\n // Check for dynamic parameters in the layer path\n const hasDynamic = hasDynamicParams(normalizedLayerPath);\n\n if (hasDynamic) {\n // Use extractPathParams to check if the path matches the pattern\n const extractedParams = extractPathParams(normalizedLayerPath, normalizedPath);\n if (extractedParams !== null) {\n shouldRun = true;\n // Merge extracted params into ctx.request.params\n ctx.request.params = {\n ...ctx.request.params,\n ...extractedParams,\n };\n }\n } else if (isInternalCall) {\n // --- Internal Call Logic ---\n // For internal calls, we only consider exact matches for all layer types.\n shouldRun = isExactMatch;\n } else {\n // --- External Call Logic ---\n if (layer.isAgent) {\n // Agents are only matched exactly (or by dynamic params, handled above).\n shouldRun = isExactMatch;\n } else {\n // Middlewares are matched by prefix.\n shouldRun = normalizedPath.startsWith(normalizedLayerPath);\n }\n }\n }\n\n if (shouldRun) {\n ctx.logger.log(\n `[AiAgentKit][_execute] Layer MATCH: path=${normalizedPath}, layer.path=${layer.path}, isAgent=${layer.isAgent}, isInternal=${isInternalCall}`\n );\n }\n return shouldRun;\n });\n\n // Separate layers into before, agents, and after\n const beforeLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'before'\n );\n const agentLayers = layersToRun.filter((l) => l.isAgent);\n const afterLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'after'\n );\n\n // Sort each group by specificity (most general first) to ensure correct execution order.\n beforeLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n agentLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n afterLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n\n // Combine in order: before, agents, after\n const orderedLayers = [...beforeLayers, ...agentLayers, ...afterLayers];\n\n const layerDescriptions = orderedLayers.map((l) => {\n const type = l.isAgent\n ? 'agent'\n : l.timing === 'before'\n ? 'before'\n : l.timing === 'after'\n ? 'after'\n : 'middleware';\n return `${l.path.toString()} (${type})`;\n });\n ctx.logger.log(\n `Found ${orderedLayers.length} layers to run: [${layerDescriptions.join(\n ', '\n )}]`\n );\n\n if (!agentLayers.length && !beforeLayers.length && !afterLayers.length) {\n const errorMsg = `No agent or tool found for path: ${normalizedPath}`;\n ctx.logger.error(errorMsg);\n throw new AgentNotFoundError(normalizedPath);\n }\n\n // A more robust, explicit dispatcher to avoid promise chain issues.\n const dispatch = async (index: number): Promise<any> => {\n const layer = orderedLayers[index];\n if (!layer) {\n // End of the chain\n return;\n }\n\n const next = () => dispatch(index + 1);\n\n const layerPath =\n typeof layer.path === 'string' ? layer.path : layer.path.toString();\n\n const layerType = layer.isAgent\n ? 'agent'\n : layer.timing === 'before'\n ? 'before'\n : layer.timing === 'after'\n ? 'after'\n : 'middleware';\n ctx.logger.log(`-> Running ${layerType}: ${layerPath}`);\n\n try {\n if (ctx._onExecutionStart) {\n ctx._onExecutionStart();\n }\n // The handler is an async function, so we can await it directly.\n // The original Promise wrapper was redundant and could hide issues.\n const result = await layer.handler(ctx, next);\n // Agents typically don't call next(), so \"after\" middlewares would never run.\n // After an agent completes, explicitly continue the chain so .after() runs.\n if (layer.isAgent) {\n await next();\n }\n\n // if (!isInternalCall) {\n // console.log('toolDefinition', result);\n // const toolDefinition = this.actAsToolDefinitions.get(path);\n // if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n // ctx.response.writeCustomTool({\n // toolName: toolDefinition.id as string,\n // toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n // output: result,\n // });\n // }\n // }\n ctx.logger.log(`<- Finished ${layerType}: ${layerPath}`);\n return result;\n } catch (err) {\n ctx.logger.error(\n `Error in ${layerType} layer for path: ${layerPath}`,\n err\n );\n throw err;\n } finally {\n if (ctx._onExecutionEnd) {\n ctx._onExecutionEnd();\n }\n }\n };\n\n return await dispatch(0);\n } finally {\n // No-op. Stack is managed by context creation/destruction.\n }\n }\n\n private pendingExecutions = 0;\n\n /**\n * The main public entry point for the router. It handles an incoming request,\n * sets up the response stream, creates the root context, and starts the execution chain.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A standard `Response` object containing the rich UI stream.\n */\n handle(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Response {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n // --- End Execution Lifecycle Management ---\n\n return createUIMessageStreamResponse({\n stream: self.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n ),\n });\n }\n\n handleStream(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >,\n executionCompletionPromise: Promise<void>,\n executionCompletionResolver: (() => void) | null\n ) {\n const self = this;\n return createUIMessageStream({\n originalMessages: initialContext.request.messages,\n execute: async ({ writer }) => {\n const streamWriter = new StreamWriter<KIT_METADATA, TOOLS>(writer);\n const requestId = generateId();\n\n // If the configured store is a MemoryStore, create a new one for each request\n // to prevent state leakage between concurrent requests. If it's a different\n // type of store, we assume it's designed to be shared.\n const store =\n self._store instanceof MemoryStore ? new MemoryStore() : self._store;\n\n const ctx: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > & {\n _onExecutionStart: () => void;\n _onExecutionEnd: () => void;\n } = {\n ...initialContext,\n request: {\n ...initialContext.request,\n path: path, // Set the initial path for the root context\n },\n state: {} as any,\n store: store,\n executionContext: { currentPath: path, callDepth: 0 },\n requestId: requestId,\n logger: self._createLogger(requestId, path, 0),\n response: {\n ...streamWriter.writer,\n writeMessageMetadata: streamWriter.writeMessageMetadata,\n writeCustomTool: streamWriter.writeCustomTool,\n writeObjectAsTool: streamWriter.writeObjectAsTool,\n generateId: generateId,\n },\n next: undefined as any, // Will be replaced right after\n _onExecutionStart: () => {\n self.pendingExecutions++;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution started. Pending: ${self.pendingExecutions}`\n );\n },\n _onExecutionEnd: () => {\n self.pendingExecutions--;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution ended. Pending: ${self.pendingExecutions}`\n );\n if (self.pendingExecutions === 0 && executionCompletionResolver) {\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions finished. Resolving promise.`\n );\n executionCompletionResolver();\n }\n },\n };\n ctx.next = new NextHandler(\n ctx,\n self,\n ctx._onExecutionStart,\n ctx._onExecutionEnd\n ) as any;\n\n ctx._onExecutionStart();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain started.`\n );\n\n // Fire off the main execution chain. We don't await it here because, in a streaming\n // context, the await might resolve prematurely when the agent yields control.\n // Instead, we catch errors and use .finally() to reliably mark the end of this\n // specific execution, while the main function body waits on the lifecycle promise.\n // self\n // ._execute(path, ctx)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // // Optionally, you could write an error message to the stream here.\n // })\n // .finally(() => {\n // ctx._onExecutionEnd();\n // });\n\n try {\n const response = await self._execute(path, ctx);\n const toolDefinition = this.actAsToolDefinitions.get(path);\n if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n ctx.response.writeCustomTool({\n toolName: toolDefinition.id as string,\n toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n output: response,\n });\n }\n return response;\n } catch (err) {\n ctx.logger.error('Unhandled error in main execution chain', err);\n } finally {\n ctx._onExecutionEnd();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain finished.`\n );\n }\n\n // ctx.next\n // .callAgent(path, initialContext.request.params)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // });\n\n // Wait for the promise that resolves only when all executions (the main one\n // and all sub-calls) have completed.\n await executionCompletionPromise;\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions truly finished. Stream can be safely closed.`\n );\n },\n });\n }\n\n /**\n * Handles an incoming request and returns a promise that resolves with the full,\n * non-streamed response. This is useful for environments where streaming is not\n * desired or for testing.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A `Promise<Response>` that resolves with the final JSON response.\n */\n async toAwaitResponse(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Promise<Response> {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n const stream = this.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n );\n\n const messageStream = readUIMessageStream({\n stream,\n onError: (error) => {\n this.logger?.error('Error reading UI message stream', error);\n },\n });\n\n let finalMessages: UIMessage[] = [];\n const thisMessageId = generateId();\n for await (const message of messageStream) {\n if (message.id?.length > 0) {\n finalMessages.push(message);\n } else if (finalMessages.find((m) => m.id === thisMessageId)) {\n finalMessages = finalMessages.map((m) =>\n m.id === thisMessageId\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n ...(message.metadata ?? {}),\n },\n parts: clubParts([\n ...(m.parts ?? []),\n ...(message.parts ?? []),\n ]),\n }\n : m\n );\n } else {\n finalMessages.push({\n ...message,\n id: thisMessageId,\n });\n }\n }\n const responseBody = JSON.stringify(finalMessages);\n return new Response(responseBody, {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n}\n\nexport type AiRouterType = typeof AiRouter;\n\nclass NextHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> {\n public maxCallDepth: number;\n\n constructor(\n private ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private router: AiRouter<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private onExecutionStart: () => void,\n private onExecutionEnd: () => void,\n parentNext?: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ) {\n this.maxCallDepth = this.router.options.maxCallDepth;\n }\n\n async callAgent(\n agentPath: string,\n params?: Record<string, any>,\n options?: {\n streamToUI?: boolean;\n }\n ): Promise<{ ok: true; data: any } | { ok: false; error: Error }> {\n this.onExecutionStart();\n try {\n const currentDepth = this.ctx.executionContext.callDepth ?? 0;\n if (currentDepth >= this.maxCallDepth) {\n const err = new MaxCallDepthExceededError(this.maxCallDepth);\n this.ctx.logger.error(`[callAgent] Aborting. ${err.message}`);\n throw err;\n }\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n this.ctx.logger.log(`Calling agent: resolvedPath='${resolvedPath}'`);\n\n const subContext = (this.router as any)._createSubContext(this.ctx, {\n type: 'agent',\n path: resolvedPath,\n params: params ?? ({} as PARAMS),\n messages: this.ctx.request.messages,\n });\n\n const definition = this.router.actAsToolDefinitions.get(resolvedPath);\n const toolCallId = definition?.id + '-' + this.ctx.response.generateId();\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n input: subContext.request.params,\n });\n }\n\n const data = await (this.router as any)._execute(\n resolvedPath,\n subContext,\n true\n );\n\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n output: data,\n });\n }\n\n return { ok: true, data };\n } catch (error: any) {\n this.ctx.logger.error(`[callAgent] Error:`, error);\n return { ok: false, error };\n } finally {\n this.onExecutionEnd();\n }\n }\n\n agentAsTool<INPUT extends JSONValue | unknown | never = any, OUTPUT = any>(\n agentPath: string,\n schemaControl?: Record<string, any> & { disableAllInputs?: boolean }\n ) {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n const definition = this.getToolDefinition(agentPath);\n\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n throw new AgentDefinitionMissingError(resolvedPath);\n }\n\n const originalSchema = definition.inputSchema as ZodObject<any> | undefined;\n let finalSchema = originalSchema;\n const fixedParams: Record<string, any> = {};\n\n if (schemaControl) {\n if (schemaControl.disableAllInputs) {\n finalSchema = z.object({});\n } else if (originalSchema) {\n let isPickMode = false;\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n isPickMode = true;\n break;\n }\n }\n\n if (isPickMode) {\n const pickShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n pickShape[key] = true;\n } else {\n fixedParams[key] = schemaControl[key];\n }\n }\n finalSchema = originalSchema.pick(pickShape);\n } else {\n // Omit mode\n const omitShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (key !== 'disableAllInputs') {\n fixedParams[key] = schemaControl[key];\n omitShape[key] = true;\n }\n }\n finalSchema = originalSchema.omit(omitShape);\n }\n }\n }\n\n const { id, metadata, ...restDefinition } = definition;\n\n (restDefinition as { inputSchema?: unknown }).inputSchema = finalSchema;\n\n return {\n [id]: {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n execute: async (params: any, options: any) => {\n const result = await this.callAgent(agentPath, params, options);\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n },\n } as Tool<INPUT, OUTPUT>,\n };\n }\n\n getToolDefinition(\n agentPath: string | RegExp\n ): AgentTool<any, any> | undefined {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath.toString()\n );\n let preDefined;\n const pathsToTry = [resolvedPath];\n // If the agentPath starts with '/', it's an absolute path from root, so also try it directly\n if (typeof agentPath === 'string' && agentPath.startsWith('/')) {\n pathsToTry.unshift(agentPath);\n }\n for (const pathToTry of pathsToTry) {\n for (const [key, value] of (this.router as any).actAsToolDefinitions) {\n if (typeof key === 'string') {\n // Check for exact match first\n if (key === pathToTry) {\n preDefined = value;\n break;\n }\n // Then check for dynamic path parameters\n if (extractPathParams(key, pathToTry) !== null) {\n preDefined = value;\n break;\n }\n }\n // Basic RegExp match\n if (key instanceof RegExp && key.test(pathToTry)) {\n preDefined = value;\n break;\n }\n }\n if (preDefined) break;\n }\n\n const definition = preDefined;\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n return undefined;\n }\n const { metadata, ...restDefinition } = definition;\n return {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: restDefinition.id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n } as AgentTool<any, any>;\n }\n\n\n /** \n * Deprecated execute style for L1402\n * execute: (params: any, options: any) => {\n const finalParams = { ...params, ...fixedParams };\n \n const executeInternal = async () => {\n const result = await this.callAgent(\n agentPath,\n finalParams,\n options\n );\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n };\n \n const newPromise = this.router.toolExecutionPromise.then(\n executeInternal,\n executeInternal\n );\n this.router.toolExecutionPromise = newPromise;\n return newPromise;\n *\n */\n\n}\n","import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import {\n GenerateObjectResult,\n UIDataTypes,\n UIMessage,\n UIMessageStreamWriter,\n} from 'ai';\nimport { UITools } from './types.js';\nimport { customAlphabet } from 'nanoid';\n\nexport const findLastElement = <T>(array: T[]) => {\n return array[array.length - 1];\n};\n\nexport const findFirstElement = <T>(array: T[]) => {\n return array[0];\n};\n\nexport class StreamWriter<METADATA, TOOLS extends UITools> {\n public writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>;\n constructor(writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>) {\n this.writer = writer;\n }\n generateId = () => {\n return customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 10)();\n };\n writeMessageMetadata = <NEW_METADATA extends METADATA>(\n metadata: NEW_METADATA\n ) => {\n return this.writer.write({\n type: 'message-metadata' as const,\n messageMetadata: metadata as NEW_METADATA,\n });\n };\n writeCustomTool = <K extends keyof TOOLS>(tool: {\n toolCallId?: string;\n toolName: K;\n inputTextDelta?: string[];\n input?: any;\n output?: any;\n }) => {\n const toolCallId =\n tool.toolCallId || tool.toolName?.toString() + '-' + this.generateId();\n if ('input' in tool && tool.input) {\n this.writer.write({\n type: 'tool-input-available' as const,\n input: tool.input,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n }\n if (\n (tool.inputTextDelta && tool.inputTextDelta.length > 0) ||\n ('output' in tool && tool.output)\n ) {\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n if (tool.inputTextDelta) {\n for (const delta of tool.inputTextDelta) {\n this.writer.write({\n type: 'tool-input-delta' as const,\n toolCallId: toolCallId,\n inputTextDelta: delta,\n });\n }\n }\n }\n if ('output' in tool && tool.output) {\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.output,\n });\n }\n };\n writeObjectAsTool = <K extends keyof TOOLS>(tool: {\n toolName: K;\n result?: GenerateObjectResult<TOOLS[K]['output']>;\n input?: GenerateObjectResult<TOOLS[K]['input']>;\n }) => {\n if (!tool.result?.object) {\n throw new Error('No object found in the GenerateObjectResult');\n }\n\n const toolCallId = tool.toolName.toString() + '-' + this.generateId();\n\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-input-available' as const,\n toolCallId: toolCallId,\n input:\n (tool.input ?? tool.result)\n ? {\n usage: tool.result?.usage,\n warnings: tool.result?.warnings,\n finishReason: tool.result?.finishReason,\n }\n : undefined,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.result?.object,\n });\n };\n}\n\nexport const getTextParts = (message: UIMessage | null | undefined) => {\n if (!message) return [];\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text);\n};\n\nexport const getTextPartsContent = (message: UIMessage | null | undefined) => {\n if (!message) return '';\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('')\n .trim();\n};\n\nexport const findLastMessageWith = <T>(\n message: UIMessage[] | null | undefined,\n filters: {\n role?: 'user' | 'assistant' | 'system';\n metadata?: Record<string, any>;\n }\n) => {\n if (!message) return null;\n return message\n .filter((m) => {\n if (filters.role && m.role !== filters.role) return false;\n if (filters.metadata) {\n for (const key in filters.metadata) {\n }\n }\n return true;\n })\n .pop();\n};\n","export interface Store {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n delete(key: string): Promise<void>;\n has(key: string): Promise<boolean>;\n entries?(): Promise<[string, any][]>;\n clear?(): Promise<void>;\n}\n\n/**\n * An in-memory implementation of the `Store` interface.\n *\n * @remarks\n * Each instance of `MemoryStore` maintains its own isolated key-value map.\n * In a server environment where a single `AiRouter` instance handles multiple\n * concurrent requests, the router's `handle` method automatically creates a new\n * `MemoryStore` for each request to ensure state isolation. This prevents\n * data leakage between different requests.\n */\nexport class MemoryStore implements Store {\n private store = new Map<string, any>();\n\n async get<T>(key: string): Promise<T | undefined> {\n return this.store.get(key);\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n this.store.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async has(key: string): Promise<boolean> {\n return this.store.has(key);\n }\n}\n"],"mappings":";;;AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAOA;AAAA,OACK;;;AChBP,OAAO,YAAY;AAEnB,IAAM,uBAAuB;AAC7B,IAAI;AAAJ,IAAU;AACV,IAAI,WAAW,WAAS;AACtB,MAAI,CAAC,QAAQ,KAAK,SAAS,OAAO;AAChC,WAAO,OAAO,YAAY,QAAQ,oBAAoB;AACtD,WAAO,eAAe,IAAI;AAC1B,iBAAa;AAAA,EACf,WAAW,aAAa,QAAQ,KAAK,QAAQ;AAC3C,WAAO,eAAe,IAAI;AAC1B,iBAAa;AAAA,EACf;AACA,gBAAc;AAChB;AACA,IAAI,SAAS,WAAS;AACpB,WAAU,SAAS,CAAE;AACrB,SAAO,KAAK,SAAS,aAAa,OAAO,UAAU;AACrD;AACA,IAAI,eAAe,CAAC,UAAU,aAAa,cAAc;AACvD,MAAI,QAAQ,KAAM,KAAK,KAAK,MAAO,SAAS,SAAS,IAAK,CAAC,KAAM;AACjE,MAAI,OAAO,KAAK,KAAM,MAAM,OAAO,cAAe,SAAS,MAAM;AACjE,SAAO,CAAC,OAAO,gBAAgB;AAC7B,QAAI,KAAK;AACT,WAAO,MAAM;AACX,UAAI,QAAQ,UAAU,IAAI;AAC1B,UAAI,IAAI;AACR,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M,EAAE,UAAU,GAAG,eAAe,IAAI;AACxC,WAAO;AAAA,MACL,GAAG;AAAA,MACH,UAAU;AAAA,QACR,GAAG;AAAA,QACH,SAAS,eAAe;AAAA,QACxB,MAAM,eAAe;AAAA,QACrB,aAAa,eAAe;AAAA,QAC5B,cAAc;AAAA,MAChB;AAAA,IACF;AAAA,EACF;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA6BF;","names":["tool","path"]}
|
|
1
|
+
{"version":3,"sources":["../src/router.ts","../../../node_modules/nanoid/index.js","../src/helper.ts","../src/store.ts"],"sourcesContent":["import {\n UIMessage,\n createUIMessageStream,\n UIMessageStreamWriter,\n createUIMessageStreamResponse,\n UIDataTypes,\n generateId,\n Tool,\n tool,\n JSONValue,\n ToolCallOptions,\n convertToModelMessages,\n ToolSet,\n DataUIPart,\n pipeUIMessageStreamToResponse,\n readUIMessageStream,\n} from 'ai';\nimport { StreamWriter } from './helper.js';\nimport { UITools } from './types.js';\nimport { z, ZodObject, ZodType } from 'zod';\nimport path from 'path';\nimport { Store, MemoryStore } from './store.js';\n\n/** Result type for ctx.dispatchWorker. */\nexport type DispatchWorkerResult = {\n jobId: string;\n messageId: string;\n status: 'queued';\n};\n\n/** Options for ctx.dispatchWorker. */\nexport type DispatchWorkerOptions = {\n jobId?: string;\n webhookUrl?: string;\n metadata?: Record<string, any>;\n};\n\n/** Derives /workers/trigger URL from env (WORKER_BASE_URL or WORKERS_TRIGGER_API_URL / WORKERS_CONFIG_API_URL). */\nfunction getWorkersTriggerUrl(): string {\n const raw =\n process.env.WORKER_BASE_URL ||\n process.env.WORKERS_TRIGGER_API_URL ||\n process.env.WORKERS_CONFIG_API_URL;\n if (!raw) {\n throw new Error('WORKER_BASE_URL is required for ctx.dispatchWorker. Set it server-side only.');\n }\n const url = new URL(raw);\n url.search = '';\n url.hash = '';\n const pathname = url.pathname || '';\n url.pathname = pathname.replace(/\\/?workers\\/(trigger|config)\\/?$/, '');\n const basePath = url.pathname.replace(/\\/+$/, '');\n url.pathname = `${basePath}/workers/trigger`.replace(/\\/+$/, '');\n return url.toString();\n}\n\n/** Dispatch a worker by ID via the workers trigger API. Inlined so ai-router has no dependency on @microfox/ai-worker. */\nasync function dispatchWorker(\n workerId: string,\n input?: Record<string, unknown>,\n options: DispatchWorkerOptions = {}\n): Promise<DispatchWorkerResult> {\n const jobId =\n options.jobId || `job-${Date.now()}-${Math.random().toString(36).substr(2, 9)}`;\n const triggerUrl = getWorkersTriggerUrl();\n const messageBody = {\n workerId,\n jobId,\n input: input ?? {},\n context: {},\n webhookUrl: options.webhookUrl,\n metadata: options.metadata || {},\n timestamp: new Date().toISOString(),\n };\n const headers: Record<string, string> = { 'Content-Type': 'application/json' };\n const key = process.env.WORKERS_TRIGGER_API_KEY;\n if (key) headers['x-workers-trigger-key'] = key;\n const response = await fetch(triggerUrl, {\n method: 'POST',\n headers,\n body: JSON.stringify({ workerId, body: messageBody }),\n });\n if (!response.ok) {\n const text = await response.text().catch(() => '');\n throw new Error(\n `Failed to trigger worker \"${workerId}\": ${response.status} ${response.statusText}${text ? ` - ${text}` : ''}`\n );\n }\n const data = (await response.json().catch(() => ({}))) as any;\n const messageId = data?.messageId ? String(data.messageId) : `trigger-${jobId}`;\n return { messageId, status: 'queued', jobId };\n}\n\n// Add global logger management\nlet globalLogger: AiLogger | undefined = undefined;\n\n/**\n * Sets a global logger that will be used by all router instances when no instance-specific logger is set.\n * This is useful for debugging across multiple router instances.\n * @param logger The logger to use globally, or undefined to disable global logging\n */\nexport function setGlobalLogger(logger?: AiLogger) {\n globalLogger = logger;\n}\n\n/**\n * Gets the current global logger.\n * @returns The current global logger or undefined if none is set\n */\nexport function getGlobalLogger(): AiLogger | undefined {\n return globalLogger;\n}\n\n// --- Helper Functions ---\n/**\n * Clubs parts based on toolCallId for tool-* types and id for data-* types\n * @param parts Array of parts to club\n * @returns Clubbed parts array\n */\nfunction clubParts(parts: any[]): any[] {\n if (!parts || parts.length === 0) return parts;\n\n const clubbedParts: any[] = [];\n const toolCallIdGroups = new Map<string, any[]>();\n const dataIdGroups = new Map<string, any[]>();\n\n // Group parts by toolCallId for tool-* types and by id for data-* types\n for (const part of parts) {\n if (part.type?.startsWith('tool-') && (part as any).toolCallId) {\n const toolCallId = (part as any).toolCallId;\n if (!toolCallIdGroups.has(toolCallId)) {\n toolCallIdGroups.set(toolCallId, []);\n }\n toolCallIdGroups.get(toolCallId)!.push(part);\n } else if (part.type?.startsWith('data-') && part.id) {\n const id = part.id;\n if (!dataIdGroups.has(id)) {\n dataIdGroups.set(id, []);\n }\n dataIdGroups.get(id)!.push(part);\n } else {\n // For parts that don't match the clubbing criteria, add them directly\n clubbedParts.push(part);\n }\n }\n\n // Add clubbed tool parts\n for (const [toolCallId, toolParts] of toolCallIdGroups) {\n if (toolParts.length === 1) {\n clubbedParts.push(toolParts[0]);\n } else {\n // Merge multiple parts with same toolCallId\n const mergedPart = { ...toolParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < toolParts.length; i++) {\n const currentPart = toolParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'toolCallId') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n // Add clubbed data parts\n for (const [id, dataParts] of dataIdGroups) {\n if (dataParts.length === 1) {\n clubbedParts.push(dataParts[0]);\n } else {\n // Merge multiple parts with same id\n const mergedPart = { ...dataParts[0] };\n // Combine any additional properties from other parts\n for (let i = 1; i < dataParts.length; i++) {\n const currentPart = dataParts[i];\n // Merge properties, giving priority to later parts\n Object.keys(currentPart).forEach((key) => {\n if (key !== 'type' && key !== 'id') {\n mergedPart[key] = currentPart[key];\n }\n });\n }\n clubbedParts.push(mergedPart);\n }\n }\n\n return clubbedParts;\n}\n\n// --- Custom Errors ---\nexport class AiKitError extends Error {\n constructor(message: string) {\n super(message);\n this.name = 'AiKitError';\n }\n}\n\nexport class AgentNotFoundError extends AiKitError {\n constructor(path: string) {\n super(`[AiAgentKit] Agent not found for path: ${path}`);\n this.name = 'AgentNotFoundError';\n }\n}\n\nexport class MaxCallDepthExceededError extends AiKitError {\n constructor(maxDepth: number) {\n super(`[AiAgentKit] Agent call depth limit (${maxDepth}) exceeded.`);\n this.name = 'MaxCallDepthExceededError';\n }\n}\n\nexport class AgentDefinitionMissingError extends AiKitError {\n constructor(path: string) {\n super(\n `[AiAgentKit] agentAsTool: No definition found for \"${path}\". Please define it using '.actAsTool()' or pass a definition as the second argument.`\n );\n this.name = 'AgentDefinitionMissingError';\n }\n}\n\n// --- Dynamic Parameter Support ---\n\n/**\n * Converts a path pattern with dynamic parameters (e.g., \"/users/:id/posts/:postId\")\n * into a RegExp that can match actual paths and extract parameters.\n * @param pattern The path pattern with dynamic parameters\n * @returns A RegExp and parameter names array\n */\nfunction parsePathPattern(pattern: string): {\n regex: RegExp;\n paramNames: string[];\n} {\n const paramNames: string[] = [];\n // Split the pattern by dynamic parameter segments, but keep the segments in the result\n const parts = pattern.split(/(\\/:[^\\/]+)/);\n\n const regexPattern = parts\n .map((part) => {\n if (part.startsWith('/:')) {\n // This is a dynamic segment like \"/:id\"\n paramNames.push(part.substring(2)); // Extract \"id\"\n return '/([^/]+)'; // Replace with a capturing group\n }\n // This is a static segment, escape any special regex characters in it\n return part.replace(/[.*+?^${}()|[\\]\\\\]/g, '\\\\$&');\n })\n .join('');\n\n const regex = new RegExp(`^${regexPattern}$`);\n\n return { regex, paramNames };\n}\n\n/**\n * Extracts dynamic parameters from a path based on a pattern.\n * @param pattern The path pattern with dynamic parameters\n * @param path The actual path to extract parameters from\n * @returns An object with extracted parameters or null if no match\n */\nfunction extractPathParams(\n pattern: string,\n path: string\n): Record<string, string> | null {\n const { regex, paramNames } = parsePathPattern(pattern);\n const match = path.match(regex);\n\n if (!match) {\n return null;\n }\n\n const params: Record<string, string> = {};\n paramNames.forEach((paramName, index) => {\n const value = match[index + 1]; // +1 because match[0] is the full match\n if (value !== undefined) {\n params[paramName] = value;\n }\n });\n\n return params;\n}\n\n/**\n * Checks if a path pattern contains dynamic parameters.\n * @param pattern The path pattern to check\n * @returns True if the pattern contains dynamic parameters\n */\nfunction hasDynamicParams(pattern: string): boolean {\n return /\\/:[^\\/]+/.test(pattern);\n}\n\nexport type AiStreamWriter<\n METADATA = unknown,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = UIMessageStreamWriter<UIMessage<METADATA, PARTS, TOOLS>> &\n Omit<StreamWriter<METADATA, TOOLS>, 'writer'> & {\n generateId: typeof generateId;\n };\n\n// --- Core Types ---\n\n/**\n * The context object passed to every agent, tool, and middleware. It contains\n * all the necessary information and utilities for a handler to perform its work.\n * @template METADATA - The type for custom metadata in UI messages.\n * @template PARTS - The type for custom parts in UI messages.\n * @template TOOLS - The type for custom tools in UI messages.\n * @template ContextState - The type for the shared state object.\n */\nexport type AiContext<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n request: {\n /** The message history for the current request. The user can modify this array to change the message history or manipulate the message history, but beware that in the routing, the messages are passed as a reference and not a copy, making the mutatated value available to all the handlers in the request chain. */\n messages: UIMessage<METADATA, PARTS, TOOLS>[];\n /** Parameters passed from an internal tool or agent call. */\n params: PARAMS;\n [key: string]: any;\n } & METADATA;\n /** A shared, mutable state object that persists for the lifetime of a single request. */\n state: ContextState;\n /** A shared, mutable store object that persists for the lifetime of a single request. */\n store: Store;\n /**\n * Internal execution context for the router. Should not be modified by user code.\n * @internal\n */\n executionContext: {\n handlerPathStack?: string[];\n currentPath?: string;\n callDepth?: number;\n [key: string]: any;\n };\n /**\n * A unique ID for the top-level request, useful for logging and tracing.\n */\n requestId: string;\n /**\n * A structured logger that automatically includes the `requestId` and current handler path.\n */\n logger: AiLogger;\n /**\n * The stream writer to send data back to the end-user's UI.\n * Includes helpers for writing structured data like tool calls and metadata.\n */\n response: AiStreamWriter<Partial<METADATA>, PARTS, TOOLS>;\n /**\n * Provides functions for an agent to dispatch calls to other agents or tools.\n * @internal\n */\n next: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n /**\n * Dispatch a background worker by ID (when @microfox/ai-worker is installed).\n * No need to import the worker module. Sends to the workers trigger API.\n */\n dispatchWorker?: (\n workerId: string,\n input?: Record<string, unknown>,\n options?: DispatchWorkerOptions\n ) => Promise<DispatchWorkerResult>;\n\n _onExecutionStart?: () => void;\n _onExecutionEnd?: () => void;\n};\n\n/** Represents the `next` function in a middleware chain, used to pass control to the next handler. */\nexport type NextFunction = () => Promise<any>;\n/** A function that handles a request for a specific agent path. */\nexport type AiHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n) => Promise<any>;\n\n/** A function that acts as middleware, processing a request and optionally passing control to the next handler. */\nexport type AiMiddleware<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = (\n ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n next: NextFunction\n) => Promise<any>;\n\n// --- Router Implementation ---\n\n/** A simple structured logger interface. */\nexport type AiLogger = {\n log: (...args: any[]) => void;\n warn: (...args: any[]) => void;\n error: (...args: any[]) => void;\n};\n\n/** Internal representation of a registered handler in the router's stack. */\ntype Layer<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> = {\n path: string | RegExp;\n handler: AiMiddleware<METADATA, ContextState, PARAMS, PARTS, TOOLS>;\n isAgent: boolean;\n // Timing for middleware: 'before' runs before agents, 'after' runs after agents\n timing?: 'before' | 'after';\n // Dynamic parameter support\n hasDynamicParams?: boolean;\n paramNames?: string[];\n};\n\nexport type AgentTool<\n INPUT extends JSONValue | unknown | never = any,\n OUTPUT extends JSONValue | unknown | never = any,\n> = Tool<INPUT, OUTPUT> & {\n name: string;\n id: string;\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n};\n\nexport type AgentData = {\n metadata?: Record<string, any> & {\n absolutePath?: string;\n name?: string;\n description?: string;\n toolKey?: string;\n icon?: string;\n parentTitle?: string;\n title?: string;\n hideUI?: boolean;\n };\n [key: string]: any;\n};\n\n/**\n * A composable router for building structured, multi-agent AI applications.\n * It allows you to define agents and tools, compose them together, and handle\n * requests in a predictable, middleware-style pattern.\n *\n * @template KIT_METADATA - The base metadata type for all UI messages in this router.\n * @template PARTS - The base custom parts type for all UI messages.\n * @template TOOLS - The base custom tools type for all UI messages.\n * @template ContextState - The base type for the shared state object.\n */\nexport class AiRouter<\n KIT_METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = {},\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n REGISTERED_TOOLS extends ToolSet = {},\n> {\n private stack: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[] = [];\n public actAsToolDefinitions: Map<string | RegExp, AgentTool<any, any>> =\n new Map();\n private logger?: AiLogger = undefined;\n private _store: Store = new MemoryStore();\n\n /** Configuration options for the router instance. */\n public options: {\n /** The maximum number of agent-to-agent calls allowed in a single request to prevent infinite loops. */\n maxCallDepth: number;\n } = {\n maxCallDepth: 10,\n };\n\n /**\n * Constructs a new AiAgentKit router.\n * @param stack An optional initial stack of layers, used for composing routers.\n * @param options Optional configuration for the router.\n */\n constructor(\n stack?: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>[],\n options?: { maxCallDepth?: number; logger?: AiLogger }\n ) {\n // Remove logger from constructor - it should be set via setLogger\n if (stack) {\n this.stack = stack;\n }\n if (options?.maxCallDepth) {\n this.options.maxCallDepth = options.maxCallDepth;\n }\n }\n\n setStore(store: Store) {\n this._store = store;\n }\n\n /**\n * Sets a logger for this router instance.\n * If no logger is set, the router will fall back to the global logger.\n * @param logger The logger to use for this router instance, or undefined to use global logger\n */\n setLogger(logger?: AiLogger) {\n this.logger = logger;\n }\n\n /**\n * Gets the effective logger for this router instance.\n * Returns instance logger if set, otherwise falls back to global logger.\n * @returns The effective logger or undefined if no logging should occur\n */\n private _getEffectiveLogger(): AiLogger | undefined {\n return this.logger ?? globalLogger;\n }\n\n /**\n * Registers a middleware-style agent that runs for a specific path prefix, regex pattern, or wildcard.\n * Agents can modify the context and must call `next()` to pass control to the next handler in the chain.\n * This method is primarily for middleware. For terminal agents, see `.agent()` on an instance.\n *\n * @param path The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param agents The agent middleware function(s).\n */\n agent<\n const TAgents extends (\n | AiMiddleware<any, any, any, any, any>\n | AiRouter<any, any, any, any, any, any>\n )[],\n >(\n agentPath:\n | string\n | RegExp\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n ...agents: TAgents\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (TAgents[number] extends AiRouter<any, any, any, any, any, infer R>\n ? R\n : {})\n > {\n let prefix: string | RegExp = '/';\n if (typeof agentPath === 'string' || agentPath instanceof RegExp) {\n prefix = agentPath;\n } else {\n agents.unshift(agentPath);\n }\n\n for (const handler of agents) {\n if (typeof handler !== 'function') {\n // Check if it's an AiRouter instance for mounting\n if (handler instanceof AiRouter && typeof prefix === 'string') {\n // Mount the router's stack directly\n const router = handler;\n const mountPath = prefix.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n }\n continue;\n }\n // Check if path has dynamic parameters\n const hasDynamic =\n typeof prefix === 'string' ? hasDynamicParams(prefix) : false;\n const paramNames =\n typeof prefix === 'string' && hasDynamic\n ? parsePathPattern(prefix).paramNames\n : undefined;\n\n this.stack.push({\n path: prefix,\n handler: handler as any,\n isAgent: true, // Mark as an agent\n hasDynamicParams: hasDynamic,\n paramNames: paramNames,\n });\n this.logger?.log(`Agent registered: path=${prefix}`);\n }\n\n return this as any;\n }\n\n /**\n * Registers middleware that runs BEFORE agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n before<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'before', // Mark as before middleware\n });\n }\n return this as any;\n }\n\n /**\n * Registers middleware that runs AFTER agent execution for a specific path prefix, regex pattern, or wildcard.\n * The middleware can modify the context and must call `next()` to pass control to the next handler.\n *\n * @param mountPathArg The path prefix, regex pattern, or \"*\" for wildcard matching.\n * @param handler The middleware function or AiAgentKit router instance to mount.\n */\n after<\n THandler extends\n | AiMiddleware<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n | AiRouter<any, any, any, any, any, any>,\n >(\n mountPathArg: string | RegExp,\n handler: THandler\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS &\n (THandler extends AiRouter<any, any, any, any, any, infer R> ? R : {})\n > {\n if (mountPathArg instanceof RegExp && handler instanceof AiRouter) {\n throw new AiKitError(\n '[AiAgentKit] Mounting a router on a RegExp path is not supported.'\n );\n }\n\n if (handler instanceof AiRouter) {\n const router = handler;\n const mountPath = mountPathArg.toString().replace(/\\/$/, ''); // remove trailing slash\n // Mount routes from the sub-router\n router.stack.forEach((layer) => {\n const layerPath = layer.path.toString();\n // Prevent layer paths starting with '/' from being treated as absolute by join\n const relativeLayerPath = layerPath.startsWith('/')\n ? layerPath.substring(1)\n : layerPath;\n const newPath = path.posix.join(mountPath, relativeLayerPath);\n this.stack.push({ ...layer, path: newPath });\n });\n // Mount tool definitions from the sub-router\n router.actAsToolDefinitions.forEach((value, key) => {\n const keyPath = key.toString();\n const relativeKeyPath = keyPath.startsWith('/')\n ? keyPath.substring(1)\n : keyPath;\n const newKey = path.posix.join(mountPath, relativeKeyPath);\n this.actAsToolDefinitions.set(newKey, value);\n });\n } else {\n // It's a middleware\n this.stack.push({\n path: mountPathArg,\n handler: handler,\n isAgent: false, // Middleware is not a terminal agent\n timing: 'after', // Mark as after middleware\n });\n }\n return this as any;\n }\n\n /**\n * Pre-defines the schema and description for an agent when it is used as a tool by an LLM.\n * This allows `next.agentAsTool()` to create a valid `Tool` object without needing the definition at call time.\n * @param path The path of the agent being defined.\n * @param options The tool definition, including a Zod schema and description.\n */\n actAsTool<\n const TPath extends string | RegExp,\n const TTool extends AgentTool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n >,\n >(\n path: TPath,\n options: TTool\n ): AiRouter<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS,\n REGISTERED_TOOLS & {\n [K in TTool['id']]: Tool<\n z.infer<TTool['inputSchema']>,\n z.infer<TTool['outputSchema']>\n > & {\n metadata: TTool['metadata'] & {\n toolKey: TTool['id'];\n name: TTool['name'];\n description: TTool['description'];\n };\n };\n }\n > {\n this.actAsToolDefinitions.set(path, options);\n this.logger?.log(`[actAsTool] Added definition: at path ${path}`);\n this.logger?.log(\n `[actAsTool] Router now has ${this.actAsToolDefinitions.size} definitions`\n );\n return this as any;\n }\n\n getToolSet(): REGISTERED_TOOLS {\n let allTools = Array.from(this.actAsToolDefinitions.entries()).map(\n ([key, value]) => {\n return {\n ...value,\n metadata: {\n ...value.metadata,\n absolutePath: key,\n },\n } as AgentTool<any, any>;\n }\n ) as AgentTool<any, any>[];\n return allTools.reduce((acc, _tool) => {\n const { inputSchema, outputSchema } = _tool;\n acc[_tool.id] = {\n ...tool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>(\n _tool\n ),\n metadata: {\n ..._tool.metadata,\n toolKey: _tool.id,\n name: _tool.name,\n description: _tool.description,\n },\n } as AgentTool<z.infer<typeof inputSchema>, z.infer<typeof outputSchema>>;\n return acc;\n }, {} as any) as REGISTERED_TOOLS;\n }\n\n getToolDefinition(path: string) {\n let definition = this.actAsToolDefinitions.get(path);\n if (!definition) {\n this.logger?.error(\n `[getToolDefinition] No definition found for path: ${path}`\n );\n throw new AgentDefinitionMissingError(path);\n }\n return definition;\n }\n\n /**\n * Outputs all registered paths, and the middlewares and agents registered on each path.\n * @returns A map of paths to their registered handlers.\n */\n registry(): {\n map: Record<string, { before: any[]; agents: any[]; after: any[] }>;\n tools: REGISTERED_TOOLS;\n } {\n const registryMap: Record<\n string,\n { before: any[]; agents: any[]; after: any[] }\n > = {};\n\n for (const layer of this.stack) {\n const pathKey = layer.path.toString();\n if (!registryMap[pathKey]) {\n registryMap[pathKey] = { before: [], agents: [], after: [] };\n }\n\n if (layer.isAgent) {\n const agentInfo: any = {\n handler: layer.handler.name || 'anonymous',\n };\n const actAsToolDef = this.actAsToolDefinitions.get(layer.path);\n if (actAsToolDef) {\n agentInfo.actAsTool = {\n ...actAsToolDef,\n };\n }\n registryMap[pathKey].agents.push(agentInfo);\n } else {\n const middlewareInfo: any = {\n handler: layer.handler.name || 'anonymous',\n timing: layer.timing || 'middleware',\n };\n if (layer.timing === 'before') {\n registryMap[pathKey].before.push(middlewareInfo);\n } else if (layer.timing === 'after') {\n registryMap[pathKey].after.push(middlewareInfo);\n } else {\n // Legacy middleware without timing (shouldn't happen with new API, but handle gracefully)\n registryMap[pathKey].before.push(middlewareInfo);\n }\n }\n }\n\n return {\n map: registryMap,\n tools: this.getToolSet(),\n };\n }\n\n /**\n * Resolves a path based on the parent path and the requested path.\n * - If path starts with `@/`, it's an absolute path from the root.\n * - Otherwise, it's a relative path.\n * @internal\n */\n private _resolvePath(parentPath: string, newPath: string): string {\n if (newPath.startsWith('@/')) {\n // Absolute path from root, use POSIX normalize for consistency\n return path.posix.normalize(newPath.substring(1));\n }\n // Relative path, use POSIX join to ensure consistent behavior\n const joinedPath = path.posix.join(parentPath, newPath);\n return joinedPath;\n }\n\n /**\n * Creates a new context for an internal agent or tool call.\n * It inherits from the parent context but gets a new logger and call depth.\n * @internal\n */\n private _createSubContext(\n parentCtx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n options: {\n type: 'agent' | 'tool';\n path: string;\n messages?: UIMessage<KIT_METADATA, PARTS, TOOLS>[];\n params: PARAMS;\n }\n ) {\n const parentDepth = parentCtx.executionContext.callDepth ?? 0;\n const newCallDepth = parentDepth + (options.type === 'agent' ? 1 : 0);\n\n const subContext: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > = {\n ...parentCtx,\n // State is passed by reference to allow sub-agents to modify the parent's state.\n // The execution context is a shallow copy to ensure call-specific data is isolated.\n state: parentCtx.state,\n store: parentCtx.store,\n executionContext: {\n ...parentCtx.executionContext,\n currentPath: options.path,\n callDepth: newCallDepth,\n },\n request: {\n ...parentCtx.request,\n messages:\n options.messages ||\n parentCtx.request.messages ||\n ([] as UIMessage<KIT_METADATA, PARTS, TOOLS>[]),\n params: options.params,\n path: options.path, // The path to execute\n },\n logger: this._createLogger(\n parentCtx.requestId,\n options.path,\n newCallDepth\n ),\n next: undefined as any, // Will be replaced right after\n };\n\n // The current path for the new context is the path we are about to execute.\n subContext.executionContext.currentPath = options.path;\n\n subContext.next = new NextHandler<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n >(\n subContext,\n this,\n (parentCtx as any)._onExecutionStart,\n (parentCtx as any)._onExecutionEnd,\n parentCtx.next\n ) as any;\n\n return subContext;\n }\n\n /**\n * Creates a new logger instance with a structured prefix.\n * @internal\n */\n private _createLogger(\n requestId: string,\n path: string | RegExp,\n callDepth: number = 0\n ): AiLogger {\n const effectiveLogger = this._getEffectiveLogger();\n\n // If no logger is available, return a no-op logger\n if (!effectiveLogger) {\n return {\n log: () => { },\n warn: () => { },\n error: () => { },\n };\n }\n\n const indent = ' '.repeat(callDepth);\n const prefix = `${indent}[${path.toString()}]`;\n // Add requestId to every log message for better tracking.\n const fullPrefix = `[${requestId}]${prefix}`;\n return {\n log: (...args: any[]) => effectiveLogger.log(fullPrefix, ...args),\n warn: (...args: any[]) => effectiveLogger.warn(fullPrefix, ...args),\n error: (...args: any[]) => effectiveLogger.error(fullPrefix, ...args),\n };\n }\n\n /**\n * Calculates a specificity score for a layer to enable Express-style routing.\n * Higher score means more specific.\n * - Middleware is less specific than an agent/tool.\n * - Deeper paths are more specific.\n * - Static segments are more specific than dynamic segments.\n * @internal\n */\n private _getSpecificityScore(\n layer: Layer<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ): number {\n const path = layer.path.toString();\n let score = 0;\n\n // Base score on depth. Deeper is more specific.\n score += path.split('/').length * 100;\n\n // More dynamic segments mean less specific.\n score -= (path.match(/:/g) || []).length * 10;\n\n // Regex is less specific than a string path.\n if (layer.path instanceof RegExp) {\n score -= 50;\n }\n\n // Agents/tools are more specific than middleware.\n if (layer.isAgent) {\n score += 1;\n }\n\n return score;\n }\n\n /**\n * The core execution engine. It finds all matching layers for a given path\n * and runs them in a middleware-style chain.\n * @internal\n */\n private async _execute(\n path: string,\n ctx: AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n isInternalCall = false\n ) {\n // The context's `currentPath` is now the single source of truth.\n // No more stack manipulation is needed here.\n try {\n const normalizedPath =\n path.length > 1 && path.endsWith('/') ? path.slice(0, -1) : path;\n\n ctx.logger.log(`Executing path. isInternalCall=${isInternalCall}`);\n const layersToRun = this.stack.filter((layer) => {\n let shouldRun = false;\n\n // Handle RegExp paths. For internal calls, we demand an exact match.\n if (layer.path instanceof RegExp) {\n if (isInternalCall) {\n const exactRegex = new RegExp(`^${layer.path.source}$`);\n shouldRun = exactRegex.test(normalizedPath);\n } else {\n shouldRun = layer.path.test(normalizedPath);\n }\n } else if (typeof layer.path === 'string') {\n const layerPath = layer.path;\n\n // Wildcard middleware only runs for external calls.\n if (layerPath === '*') {\n return !isInternalCall;\n }\n\n const normalizedLayerPath =\n layerPath.length > 1 && layerPath.endsWith('/')\n ? layerPath.slice(0, -1)\n : layerPath;\n\n const isExactMatch = normalizedPath === normalizedLayerPath;\n\n // Check for dynamic parameters in the layer path\n const hasDynamic = hasDynamicParams(normalizedLayerPath);\n\n if (hasDynamic) {\n // Use extractPathParams to check if the path matches the pattern\n const extractedParams = extractPathParams(normalizedLayerPath, normalizedPath);\n if (extractedParams !== null) {\n shouldRun = true;\n // Merge extracted params into ctx.request.params\n ctx.request.params = {\n ...ctx.request.params,\n ...extractedParams,\n };\n }\n } else if (isInternalCall) {\n // --- Internal Call Logic ---\n // For internal calls, we only consider exact matches for all layer types.\n shouldRun = isExactMatch;\n } else {\n // --- External Call Logic ---\n if (layer.isAgent) {\n // Agents are only matched exactly (or by dynamic params, handled above).\n shouldRun = isExactMatch;\n } else {\n // Middlewares are matched by prefix.\n shouldRun = normalizedPath.startsWith(normalizedLayerPath);\n }\n }\n }\n\n if (shouldRun) {\n ctx.logger.log(\n `[AiAgentKit][_execute] Layer MATCH: path=${normalizedPath}, layer.path=${layer.path}, isAgent=${layer.isAgent}, isInternal=${isInternalCall}`\n );\n }\n return shouldRun;\n });\n\n // Separate layers into before, agents, and after\n const beforeLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'before'\n );\n const agentLayers = layersToRun.filter((l) => l.isAgent);\n const afterLayers = layersToRun.filter(\n (l) => !l.isAgent && l.timing === 'after'\n );\n\n // Sort each group by specificity (most general first) to ensure correct execution order.\n beforeLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n agentLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n afterLayers.sort(\n (a, b) => this._getSpecificityScore(a) - this._getSpecificityScore(b)\n );\n\n // Combine in order: before, agents, after\n const orderedLayers = [...beforeLayers, ...agentLayers, ...afterLayers];\n\n const layerDescriptions = orderedLayers.map((l) => {\n const type = l.isAgent\n ? 'agent'\n : l.timing === 'before'\n ? 'before'\n : l.timing === 'after'\n ? 'after'\n : 'middleware';\n return `${l.path.toString()} (${type})`;\n });\n ctx.logger.log(\n `Found ${orderedLayers.length} layers to run: [${layerDescriptions.join(\n ', '\n )}]`\n );\n\n if (!agentLayers.length && !beforeLayers.length && !afterLayers.length) {\n const errorMsg = `No agent or tool found for path: ${normalizedPath}`;\n ctx.logger.error(errorMsg);\n throw new AgentNotFoundError(normalizedPath);\n }\n\n // A more robust, explicit dispatcher to avoid promise chain issues.\n const dispatch = async (index: number): Promise<any> => {\n const layer = orderedLayers[index];\n if (!layer) {\n // End of the chain\n return;\n }\n\n const next = () => dispatch(index + 1);\n\n const layerPath =\n typeof layer.path === 'string' ? layer.path : layer.path.toString();\n\n const layerType = layer.isAgent\n ? 'agent'\n : layer.timing === 'before'\n ? 'before'\n : layer.timing === 'after'\n ? 'after'\n : 'middleware';\n ctx.logger.log(`-> Running ${layerType}: ${layerPath}`);\n\n try {\n if (ctx._onExecutionStart) {\n ctx._onExecutionStart();\n }\n // The handler is an async function, so we can await it directly.\n // The original Promise wrapper was redundant and could hide issues.\n const result = await layer.handler(ctx, next);\n // Agents typically don't call next(), so \"after\" middlewares would never run.\n // After an agent completes, explicitly continue the chain so .after() runs.\n if (layer.isAgent) {\n await next();\n }\n\n // if (!isInternalCall) {\n // console.log('toolDefinition', result);\n // const toolDefinition = this.actAsToolDefinitions.get(path);\n // if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n // ctx.response.writeCustomTool({\n // toolName: toolDefinition.id as string,\n // toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n // output: result,\n // });\n // }\n // }\n ctx.logger.log(`<- Finished ${layerType}: ${layerPath}`);\n return result;\n } catch (err) {\n ctx.logger.error(\n `Error in ${layerType} layer for path: ${layerPath}`,\n err\n );\n throw err;\n } finally {\n if (ctx._onExecutionEnd) {\n ctx._onExecutionEnd();\n }\n }\n };\n\n return await dispatch(0);\n } finally {\n // No-op. Stack is managed by context creation/destruction.\n }\n }\n\n private pendingExecutions = 0;\n\n /**\n * The main public entry point for the router. It handles an incoming request,\n * sets up the response stream, creates the root context, and starts the execution chain.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A standard `Response` object containing the rich UI stream.\n */\n handle(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Response {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n // --- End Execution Lifecycle Management ---\n\n return createUIMessageStreamResponse({\n stream: self.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n ),\n });\n }\n\n handleStream(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >,\n executionCompletionPromise: Promise<void>,\n executionCompletionResolver: (() => void) | null\n ) {\n const self = this;\n return createUIMessageStream({\n originalMessages: initialContext.request.messages,\n execute: async ({ writer }) => {\n const streamWriter = new StreamWriter<KIT_METADATA, TOOLS>(writer);\n const requestId = generateId();\n\n // If the configured store is a MemoryStore, create a new one for each request\n // to prevent state leakage between concurrent requests. If it's a different\n // type of store, we assume it's designed to be shared.\n const store =\n self._store instanceof MemoryStore ? new MemoryStore() : self._store;\n\n const ctx: AiContext<\n KIT_METADATA,\n ContextState,\n PARAMS,\n PARTS,\n TOOLS\n > & {\n _onExecutionStart: () => void;\n _onExecutionEnd: () => void;\n } = {\n ...initialContext,\n request: {\n ...initialContext.request,\n path: path, // Set the initial path for the root context\n },\n state: {} as any,\n store: store,\n executionContext: { currentPath: path, callDepth: 0 },\n requestId: requestId,\n logger: self._createLogger(requestId, path, 0),\n response: {\n ...streamWriter.writer,\n writeMessageMetadata: streamWriter.writeMessageMetadata,\n writeCustomTool: streamWriter.writeCustomTool,\n writeObjectAsTool: streamWriter.writeObjectAsTool,\n generateId: generateId,\n },\n next: undefined as any, // Will be replaced right after\n dispatchWorker,\n _onExecutionStart: () => {\n self.pendingExecutions++;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution started. Pending: ${self.pendingExecutions}`\n );\n },\n _onExecutionEnd: () => {\n self.pendingExecutions--;\n self.logger?.log(\n `[AiAgentKit][lifecycle] Execution ended. Pending: ${self.pendingExecutions}`\n );\n if (self.pendingExecutions === 0 && executionCompletionResolver) {\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions finished. Resolving promise.`\n );\n executionCompletionResolver();\n }\n },\n };\n ctx.next = new NextHandler(\n ctx,\n self,\n ctx._onExecutionStart,\n ctx._onExecutionEnd\n ) as any;\n\n ctx._onExecutionStart();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain started.`\n );\n\n // Fire off the main execution chain. We don't await it here because, in a streaming\n // context, the await might resolve prematurely when the agent yields control.\n // Instead, we catch errors and use .finally() to reliably mark the end of this\n // specific execution, while the main function body waits on the lifecycle promise.\n // self\n // ._execute(path, ctx)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // // Optionally, you could write an error message to the stream here.\n // })\n // .finally(() => {\n // ctx._onExecutionEnd();\n // });\n\n try {\n const response = await self._execute(path, ctx);\n const toolDefinition = this.actAsToolDefinitions.get(path);\n if (toolDefinition && !toolDefinition.metadata?.hideUI) {\n ctx.response.writeCustomTool({\n toolName: toolDefinition.id as string,\n toolCallId: toolDefinition.id + '-' + ctx.response.generateId(),\n output: response,\n });\n }\n return response;\n } catch (err) {\n ctx.logger.error('Unhandled error in main execution chain', err);\n } finally {\n ctx._onExecutionEnd();\n self.logger?.log(\n `[AiAgentKit][lifecycle] Main execution chain finished.`\n );\n }\n\n // ctx.next\n // .callAgent(path, initialContext.request.params)\n // .catch((err) => {\n // ctx.logger.error(\"Unhandled error in main execution chain\", err);\n // });\n\n // Wait for the promise that resolves only when all executions (the main one\n // and all sub-calls) have completed.\n await executionCompletionPromise;\n self.logger?.log(\n `[AiAgentKit][lifecycle] All executions truly finished. Stream can be safely closed.`\n );\n },\n });\n }\n\n /**\n * Handles an incoming request and returns a promise that resolves with the full,\n * non-streamed response. This is useful for environments where streaming is not\n * desired or for testing.\n *\n * @param path The path of the agent or tool to execute.\n * @param initialContext The initial context for the request, typically containing messages.\n * @returns A `Promise<Response>` that resolves with the final JSON response.\n */\n async toAwaitResponse(\n path: string,\n initialContext: Omit<\n AiContext<KIT_METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n | 'state'\n | 'response'\n | 'next'\n | 'requestId'\n | 'logger'\n | 'executionContext'\n | 'store'\n >\n ): Promise<Response> {\n this.logger?.log(`Handling request for path: ${path}`);\n const self = this; // Reference to the router instance\n\n // --- Execution Lifecycle Management ---\n let executionCompletionResolver: (() => void) | null = null;\n const executionCompletionPromise = new Promise<void>((resolve) => {\n executionCompletionResolver = resolve;\n });\n\n const stream = this.handleStream(\n path,\n initialContext,\n executionCompletionPromise,\n executionCompletionResolver\n );\n\n const messageStream = readUIMessageStream({\n stream,\n onError: (error) => {\n this.logger?.error('Error reading UI message stream', error);\n },\n });\n\n let finalMessages: UIMessage[] = [];\n const thisMessageId = generateId();\n for await (const message of messageStream) {\n if (message.id?.length > 0) {\n finalMessages.push(message);\n } else if (finalMessages.find((m) => m.id === thisMessageId)) {\n finalMessages = finalMessages.map((m) =>\n m.id === thisMessageId\n ? {\n ...m,\n metadata: {\n ...(m.metadata ?? {}),\n ...(message.metadata ?? {}),\n },\n parts: clubParts([\n ...(m.parts ?? []),\n ...(message.parts ?? []),\n ]),\n }\n : m\n );\n } else {\n finalMessages.push({\n ...message,\n id: thisMessageId,\n });\n }\n }\n const responseBody = JSON.stringify(finalMessages);\n return new Response(responseBody, {\n headers: { 'Content-Type': 'application/json' },\n });\n }\n}\n\nexport type AiRouterType = typeof AiRouter;\n\nclass NextHandler<\n METADATA extends Record<string, any> = Record<string, any>,\n ContextState extends Record<string, any> = Record<string, any>,\n PARAMS extends Record<string, any> = Record<string, any>,\n PARTS extends UIDataTypes = UIDataTypes,\n TOOLS extends UITools = UITools,\n> {\n public maxCallDepth: number;\n\n constructor(\n private ctx: AiContext<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private router: AiRouter<METADATA, ContextState, PARAMS, PARTS, TOOLS>,\n private onExecutionStart: () => void,\n private onExecutionEnd: () => void,\n parentNext?: NextHandler<METADATA, ContextState, PARAMS, PARTS, TOOLS>\n ) {\n this.maxCallDepth = this.router.options.maxCallDepth;\n }\n\n async callAgent(\n agentPath: string,\n params?: Record<string, any>,\n options?: {\n streamToUI?: boolean;\n }\n ): Promise<{ ok: true; data: any } | { ok: false; error: Error }> {\n this.onExecutionStart();\n try {\n const currentDepth = this.ctx.executionContext.callDepth ?? 0;\n if (currentDepth >= this.maxCallDepth) {\n const err = new MaxCallDepthExceededError(this.maxCallDepth);\n this.ctx.logger.error(`[callAgent] Aborting. ${err.message}`);\n throw err;\n }\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n this.ctx.logger.log(`Calling agent: resolvedPath='${resolvedPath}'`);\n\n const subContext = (this.router as any)._createSubContext(this.ctx, {\n type: 'agent',\n path: resolvedPath,\n params: params ?? ({} as PARAMS),\n messages: this.ctx.request.messages,\n });\n\n const definition = this.router.actAsToolDefinitions.get(resolvedPath);\n const toolCallId = definition?.id + '-' + this.ctx.response.generateId();\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n input: subContext.request.params,\n });\n }\n\n const data = await (this.router as any)._execute(\n resolvedPath,\n subContext,\n true\n );\n\n if (options?.streamToUI && definition) {\n this.ctx.response.writeCustomTool({\n toolName: definition?.id,\n toolCallId: toolCallId,\n output: data,\n });\n }\n\n return { ok: true, data };\n } catch (error: any) {\n this.ctx.logger.error(`[callAgent] Error:`, error);\n return { ok: false, error };\n } finally {\n this.onExecutionEnd();\n }\n }\n\n agentAsTool<INPUT extends JSONValue | unknown | never = any, OUTPUT = any>(\n agentPath: string,\n schemaControl?: Record<string, any> & { disableAllInputs?: boolean }\n ) {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath\n );\n\n const definition = this.getToolDefinition(agentPath);\n\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n throw new AgentDefinitionMissingError(resolvedPath);\n }\n\n const originalSchema = definition.inputSchema as ZodObject<any> | undefined;\n let finalSchema = originalSchema;\n const fixedParams: Record<string, any> = {};\n\n if (schemaControl) {\n if (schemaControl.disableAllInputs) {\n finalSchema = z.object({});\n } else if (originalSchema) {\n let isPickMode = false;\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n isPickMode = true;\n break;\n }\n }\n\n if (isPickMode) {\n const pickShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (schemaControl[key] === true) {\n pickShape[key] = true;\n } else {\n fixedParams[key] = schemaControl[key];\n }\n }\n finalSchema = originalSchema.pick(pickShape);\n } else {\n // Omit mode\n const omitShape: Record<string, true> = {};\n for (const key in schemaControl) {\n if (key !== 'disableAllInputs') {\n fixedParams[key] = schemaControl[key];\n omitShape[key] = true;\n }\n }\n finalSchema = originalSchema.omit(omitShape);\n }\n }\n }\n\n const { id, metadata, ...restDefinition } = definition;\n\n (restDefinition as { inputSchema?: unknown }).inputSchema = finalSchema;\n\n return {\n [id]: {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n execute: async (params: any, options: any) => {\n const result = await this.callAgent(agentPath, params, options);\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n },\n } as Tool<INPUT, OUTPUT>,\n };\n }\n\n getToolDefinition(\n agentPath: string | RegExp\n ): AgentTool<any, any> | undefined {\n const parentPath = this.ctx.executionContext.currentPath || '/';\n const resolvedPath = (this.router as any)._resolvePath(\n parentPath,\n agentPath.toString()\n );\n let preDefined;\n const pathsToTry = [resolvedPath];\n // If the agentPath starts with '/', it's an absolute path from root, so also try it directly\n if (typeof agentPath === 'string' && agentPath.startsWith('/')) {\n pathsToTry.unshift(agentPath);\n }\n for (const pathToTry of pathsToTry) {\n for (const [key, value] of (this.router as any).actAsToolDefinitions) {\n if (typeof key === 'string') {\n // Check for exact match first\n if (key === pathToTry) {\n preDefined = value;\n break;\n }\n // Then check for dynamic path parameters\n if (extractPathParams(key, pathToTry) !== null) {\n preDefined = value;\n break;\n }\n }\n // Basic RegExp match\n if (key instanceof RegExp && key.test(pathToTry)) {\n preDefined = value;\n break;\n }\n }\n if (preDefined) break;\n }\n\n const definition = preDefined;\n if (!definition) {\n this.ctx.logger.error(\n `[agentAsTool] No definition found for agent at resolved path: ${resolvedPath}`\n );\n return undefined;\n }\n const { metadata, ...restDefinition } = definition;\n return {\n ...restDefinition,\n metadata: {\n ...metadata,\n toolKey: restDefinition.id,\n name: restDefinition.name,\n description: restDefinition.description,\n absolutePath: resolvedPath,\n },\n } as AgentTool<any, any>;\n }\n\n\n /** \n * Deprecated execute style for L1402\n * execute: (params: any, options: any) => {\n const finalParams = { ...params, ...fixedParams };\n \n const executeInternal = async () => {\n const result = await this.callAgent(\n agentPath,\n finalParams,\n options\n );\n if (!result.ok) {\n throw result.error;\n }\n return result.data;\n };\n \n const newPromise = this.router.toolExecutionPromise.then(\n executeInternal,\n executeInternal\n );\n this.router.toolExecutionPromise = newPromise;\n return newPromise;\n *\n */\n\n}\n","import crypto from 'crypto'\nimport { urlAlphabet } from './url-alphabet/index.js'\nconst POOL_SIZE_MULTIPLIER = 128\nlet pool, poolOffset\nlet fillPool = bytes => {\n if (!pool || pool.length < bytes) {\n pool = Buffer.allocUnsafe(bytes * POOL_SIZE_MULTIPLIER)\n crypto.randomFillSync(pool)\n poolOffset = 0\n } else if (poolOffset + bytes > pool.length) {\n crypto.randomFillSync(pool)\n poolOffset = 0\n }\n poolOffset += bytes\n}\nlet random = bytes => {\n fillPool((bytes |= 0))\n return pool.subarray(poolOffset - bytes, poolOffset)\n}\nlet customRandom = (alphabet, defaultSize, getRandom) => {\n let mask = (2 << (31 - Math.clz32((alphabet.length - 1) | 1))) - 1\n let step = Math.ceil((1.6 * mask * defaultSize) / alphabet.length)\n return (size = defaultSize) => {\n let id = ''\n while (true) {\n let bytes = getRandom(step)\n let i = step\n while (i--) {\n id += alphabet[bytes[i] & mask] || ''\n if (id.length === size) return id\n }\n }\n }\n}\nlet customAlphabet = (alphabet, size = 21) =>\n customRandom(alphabet, size, random)\nlet nanoid = (size = 21) => {\n fillPool((size |= 0))\n let id = ''\n for (let i = poolOffset - size; i < poolOffset; i++) {\n id += urlAlphabet[pool[i] & 63]\n }\n return id\n}\nexport { nanoid, customAlphabet, customRandom, urlAlphabet, random }\n","import {\n GenerateObjectResult,\n UIDataTypes,\n UIMessage,\n UIMessageStreamWriter,\n} from 'ai';\nimport { UITools } from './types.js';\nimport { customAlphabet } from 'nanoid';\n\nexport const findLastElement = <T>(array: T[]) => {\n return array[array.length - 1];\n};\n\nexport const findFirstElement = <T>(array: T[]) => {\n return array[0];\n};\n\nexport class StreamWriter<METADATA, TOOLS extends UITools> {\n public writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>;\n constructor(writer: UIMessageStreamWriter<UIMessage<METADATA, any, TOOLS>>) {\n this.writer = writer;\n }\n generateId = () => {\n return customAlphabet('1234567890abcdefghijklmnopqrstuvwxyz', 10)();\n };\n writeMessageMetadata = <NEW_METADATA extends METADATA>(\n metadata: NEW_METADATA\n ) => {\n return this.writer.write({\n type: 'message-metadata' as const,\n messageMetadata: metadata as NEW_METADATA,\n });\n };\n writeCustomTool = <K extends keyof TOOLS>(tool: {\n toolCallId?: string;\n toolName: K;\n inputTextDelta?: string[];\n input?: any;\n output?: any;\n }) => {\n const toolCallId =\n tool.toolCallId || tool.toolName?.toString() + '-' + this.generateId();\n if ('input' in tool && tool.input) {\n this.writer.write({\n type: 'tool-input-available' as const,\n input: tool.input,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n }\n if (\n (tool.inputTextDelta && tool.inputTextDelta.length > 0) ||\n ('output' in tool && tool.output)\n ) {\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n if (tool.inputTextDelta) {\n for (const delta of tool.inputTextDelta) {\n this.writer.write({\n type: 'tool-input-delta' as const,\n toolCallId: toolCallId,\n inputTextDelta: delta,\n });\n }\n }\n }\n if ('output' in tool && tool.output) {\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.output,\n });\n }\n };\n writeObjectAsTool = <K extends keyof TOOLS>(tool: {\n toolName: K;\n result?: GenerateObjectResult<TOOLS[K]['output']>;\n input?: GenerateObjectResult<TOOLS[K]['input']>;\n }) => {\n if (!tool.result?.object) {\n throw new Error('No object found in the GenerateObjectResult');\n }\n\n const toolCallId = tool.toolName.toString() + '-' + this.generateId();\n\n this.writer.write({\n type: 'tool-input-start' as const,\n toolCallId: toolCallId,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-input-available' as const,\n toolCallId: toolCallId,\n input:\n (tool.input ?? tool.result)\n ? {\n usage: tool.result?.usage,\n warnings: tool.result?.warnings,\n finishReason: tool.result?.finishReason,\n }\n : undefined,\n toolName: tool.toolName as string,\n });\n\n this.writer.write({\n type: 'tool-output-available' as const,\n toolCallId: toolCallId,\n output: tool.result?.object,\n });\n };\n}\n\nexport const getTextParts = (message: UIMessage | null | undefined) => {\n if (!message) return [];\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text);\n};\n\nexport const getTextPartsContent = (message: UIMessage | null | undefined) => {\n if (!message) return '';\n return message.parts\n .filter((part) => part.type === 'text')\n .map((part) => part.text)\n .join('')\n .trim();\n};\n\nexport const findLastMessageWith = <T>(\n message: UIMessage[] | null | undefined,\n filters: {\n role?: 'user' | 'assistant' | 'system';\n metadata?: Record<string, any>;\n }\n) => {\n if (!message) return null;\n return message\n .filter((m) => {\n if (filters.role && m.role !== filters.role) return false;\n if (filters.metadata) {\n for (const key in filters.metadata) {\n }\n }\n return true;\n })\n .pop();\n};\n","export interface Store {\n get<T>(key: string): Promise<T | undefined>;\n set<T>(key: string, value: T): Promise<void>;\n delete(key: string): Promise<void>;\n has(key: string): Promise<boolean>;\n entries?(): Promise<[string, any][]>;\n clear?(): Promise<void>;\n}\n\n/**\n * An in-memory implementation of the `Store` interface.\n *\n * @remarks\n * Each instance of `MemoryStore` maintains its own isolated key-value map.\n * In a server environment where a single `AiRouter` instance handles multiple\n * concurrent requests, the router's `handle` method automatically creates a new\n * `MemoryStore` for each request to ensure state isolation. This prevents\n * data leakage between different requests.\n */\nexport class MemoryStore implements Store {\n private store = new Map<string, any>();\n\n async get<T>(key: string): Promise<T | undefined> {\n return this.store.get(key);\n }\n\n async set<T>(key: string, value: T): Promise<void> {\n this.store.set(key, value);\n }\n\n async delete(key: string): Promise<void> {\n this.store.delete(key);\n }\n\n async has(key: string): Promise<boolean> {\n return this.store.has(key);\n }\n}\n"],"mappings":";;;AAAA;AAAA,EAEE;AAAA,EAEA;AAAA,EAEA;AAAA,EAEA;AAAA,EAOA;AAAA,OACK;;;AChBP,OAAO,YAAY;AAEnB,IAAM,uBAAuB;AAC7B,IAAI;AAAJ,IAAU;AACV,IAAI,WAAW,WAAS;AACtB,MAAI,CAAC,QAAQ,KAAK,SAAS,OAAO;AAChC,WAAO,OAAO,YAAY,QAAQ,oBAAoB;AACtD,WAAO,eAAe,IAAI;AAC1B,iBAAa;AAAA,EACf,WAAW,aAAa,QAAQ,KAAK,QAAQ;AAC3C,WAAO,eAAe,IAAI;AAC1B,iBAAa;AAAA,EACf;AACA,gBAAc;AAChB;AACA,IAAI,SAAS,WAAS;AACpB,WAAU,SAAS,CAAE;AACrB,SAAO,KAAK,SAAS,aAAa,OAAO,UAAU;AACrD;AACA,IAAI,eAAe,CAAC,UAAU,aAAa,cAAc;AACvD,MAAI,QAAQ,KAAM,KAAK,KAAK,MAAO,SAAS,SAAS,IAAK,CAAC,KAAM;AACjE,MAAI,OAAO,KAAK,KAAM,MAAM,OAAO,cAAe,SAAS,MAAM;AACjE,SAAO,CAAC,OAAO,gBAAgB;AAC7B,QAAI,KAAK;AACT,WAAO,MAAM;AACX,UAAI,QAAQ,UAAU,IAAI;AAC1B,UAAI,IAAI;AACR,aAAO,KAAK;AACV,cAAM,SAAS,MAAM,CAAC,IAAI,IAAI,KAAK;AACnC,YAAI,GAAG,WAAW,KAAM,QAAO;AAAA,MACjC;AAAA,IACF;AAAA,EACF;AACF;AACA,IAAI,iBAAiB,CAAC,UAAU,OAAO,OACrC,aAAa,UAAU,MAAM,MAAM;;;AC1B9B,IAAM,kBAAkB,CAAI,UAAe;AAChD,SAAO,MAAM,MAAM,SAAS,CAAC;AAC/B;AAEO,IAAM,mBAAmB,CAAI,U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