zeitlich 0.1.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/LICENSE +21 -0
- package/README.md +494 -0
- package/dist/index.d.mts +152 -0
- package/dist/index.d.ts +152 -0
- package/dist/index.js +1623 -0
- package/dist/index.js.map +1 -0
- package/dist/index.mjs +1582 -0
- package/dist/index.mjs.map +1 -0
- package/dist/workflow-DeVGEXSc.d.mts +1201 -0
- package/dist/workflow-DeVGEXSc.d.ts +1201 -0
- package/dist/workflow.d.mts +4 -0
- package/dist/workflow.d.ts +4 -0
- package/dist/workflow.js +762 -0
- package/dist/workflow.js.map +1 -0
- package/dist/workflow.mjs +734 -0
- package/dist/workflow.mjs.map +1 -0
- package/package.json +92 -0
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"sources":["../src/tools/task/tool.ts","../src/tools/task/handler.ts","../src/lib/subagent-support.ts","../src/lib/session.ts","../src/lib/types.ts","../src/lib/state-manager.ts","../src/lib/prompt-manager.ts","../src/lib/tool-registry.ts","../src/lib/tool-router.ts","../src/tools/ask-user-question/tool.ts","../src/tools/glob/tool.ts","../src/tools/grep/tool.ts","../src/tools/read/tool.ts","../src/tools/write/tool.ts","../src/tools/edit/tool.ts","../src/lib/filesystem/types.ts","../src/lib/filesystem/tree-builder.ts","../src/lib/filesystem/providers/base.ts","../node_modules/uuid/dist/esm-node/stringify.js","../node_modules/uuid/dist/esm-node/rng.js","../node_modules/uuid/dist/esm-node/native.js","../node_modules/uuid/dist/esm-node/v4.js","../src/lib/thread-manager.ts","../src/activities.ts","../src/plugin.ts","../src/lib/model-invoker.ts","../src/tools/ask-user-question/handler.ts","../src/tools/glob/handler.ts","../src/tools/grep/handler.ts","../src/tools/read/handler.ts","../src/tools/write/handler.ts","../src/tools/edit/handler.ts"],"names":["z","workflowInfo","uuid4","executeChild","proxyActivities","results","minimatch","crypto","HumanMessage","AIMessage","ToolMessage","mapStoredMessageToChatMessage","Simpl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,qBAAA,CAAA;AAEJ,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,CAAA,EAAG,OAAO,CAAA,IAAA,EAAO,SAAS,CAAA,CAAA;AAAA,QACnC,MAAA,EAAQ;AAAA,UACN,IAAA,EAAM,SAAA;AAAA,UACN,OAAA,EAAS,IAAA;AAAA,UACT;AAAA;AACF,OACF;AAAA,IACF,SAAS,KAAA,EAAO;AACd,MAAA,MAAM,OAAA,GAAU,KAAA,YAAiB,KAAA,GAAQ,KAAA,CAAM,OAAA,GAAU,eAAA;AACzD,MAAA,OAAO;AAAA,QACL,OAAA,EAAS,CAAA,oBAAA,EAAuB,SAAS,CAAA,GAAA,EAAM,OAAO,CAAA,CAAA;AAAA,QACtD,MAAA,EAAQ;AAAA,UACN,IAAA,EAAM,SAAA;AAAA,UACN,OAAA,EAAS,KAAA;AAAA,UACT,YAAA,EAAc;AAAA;AAChB,OACF;AAAA,IACF;AAAA,EACF,CAAA;AACF","file":"index.js","sourcesContent":["import z from \"zod\";\nimport type { SubagentConfig } from \"../../lib/types\";\n\nconst TASK_TOOL = \"Task\" as const;\n\n/**\n * Builds the tool description with available subagent information\n */\nfunction buildTaskDescription(subagents: SubagentConfig[]): string {\n const subagentList = subagents\n .map((s) => `- **${s.name}**: ${s.description}`)\n .join(\"\\n\");\n\n return `Launch a new agent to handle complex, multi-step tasks autonomously.\n\nThe ${TASK_TOOL} tool launches specialized agents (subprocesses) that autonomously handle complex tasks. Each agent type has specific capabilities and tools available to it.\n\nAvailable agent types:\n\n${subagentList}\n\nWhen using the ${TASK_TOOL} tool, you must specify a subagent parameter to select which agent type to use.\n\nUsage notes:\n\n- Always include a short description (3-5 words) summarizing what the agent will do\n- Launch multiple agents concurrently whenever possible, to maximize performance; to do that, use a single message with multiple tool uses\n- When the agent is done, it will return a single message back to you. The result returned by the agent is not visible to the user. To show the user the result, you should send a text message back to the user with a concise summary of the result.\n- Each invocation starts fresh - provide a detailed task description with all necessary context.\n- Provide clear, detailed prompts so the agent can work autonomously and return exactly the information you need.\n- The agent's outputs should generally be trusted\n- Clearly tell the agent what type of work you expect since it is not aware of the user's intent\n- If the agent description mentions that it should be used proactively, then you should try your best to use it without the user having to ask for it first. Use your judgement.`;\n}\n\n/**\n * Creates a Task tool configured with the available subagents.\n *\n * @param subagents - Array of subagent configurations (must have at least one)\n * @returns A tool definition with dynamic schema based on available subagents\n *\n * @example\n * const taskTool = createTaskTool([\n * {\n * name: \"researcher\",\n * description: \"Researches topics and gathers information\",\n * workflowType: \"researcherWorkflow\",\n * resultSchema: z.object({ findings: z.string() }),\n * },\n * ]);\n */\nexport function createTaskTool<T extends SubagentConfig[]>(\n subagents: T\n): {\n name: typeof TASK_TOOL;\n description: string;\n schema: z.ZodObject<{\n subagent: z.ZodEnum<Record<string, string>>;\n description: z.ZodString;\n prompt: z.ZodString;\n }>;\n} {\n if (subagents.length === 0) {\n throw new Error(\"createTaskTool requires at least one subagent\");\n }\n\n const names = subagents.map((s) => s.name);\n\n return {\n name: TASK_TOOL,\n description: buildTaskDescription(subagents),\n schema: z.object({\n subagent: z.enum(names).describe(\"The type of subagent to launch\"),\n description: z\n .string()\n .describe(\"A short (3-5 word) description of the task\"),\n prompt: z.string().describe(\"The task for the agent to perform\"),\n }),\n } as const;\n}\n\n/**\n * Infer the schema type for a task tool created with specific subagents\n */\nexport type TaskToolSchemaType<T extends SubagentConfig[]> = z.infer<\n ReturnType<typeof createTaskTool<T>>[\"schema\"]\n>;\n\n/**\n * Generic task tool schema type (when subagent names are not known at compile time)\n */\nexport type GenericTaskToolSchemaType = {\n subagent: string;\n description: string;\n prompt: string;\n};\n","import { executeChild, workflowInfo, uuid4 } from \"@temporalio/workflow\";\nimport type { ToolHandlerResponse } from \"../../lib/tool-router\";\nimport type { SubagentConfig, SubagentInput } from \"../../lib/types\";\nimport type { GenericTaskToolSchemaType } from \"./tool\";\n\n/**\n * Result from a task handler execution\n */\nexport interface TaskHandlerResult<TResult = unknown> {\n /** The validated result from the child workflow */\n result: TResult;\n /** The child workflow ID (for reference/debugging) */\n childWorkflowId: string;\n}\n\n/**\n * Creates a Task tool handler that spawns child workflows for configured subagents.\n *\n * @param subagents - Array of subagent configurations\n * @returns A tool handler function that can be used with the tool router\n *\n * @example\n * const taskHandler = createTaskHandler([\n * {\n * name: \"researcher\",\n * description: \"Researches topics\",\n * workflowType: \"researcherWorkflow\",\n * resultSchema: z.object({ findings: z.string() }),\n * },\n * ]);\n */\nexport function createTaskHandler(subagents: SubagentConfig[]) {\n const { workflowId: parentWorkflowId, taskQueue: parentTaskQueue } =\n workflowInfo();\n\n return async (\n args: GenericTaskToolSchemaType,\n _toolCallId: string\n ): Promise<ToolHandlerResponse<TaskHandlerResult>> => {\n const config = subagents.find((s) => s.name === args.subagent);\n\n if (!config) {\n throw new Error(\n `Unknown subagent: ${args.subagent}. Available: ${subagents.map((s) => s.name).join(\", \")}`\n );\n }\n\n const childWorkflowId = `${parentWorkflowId}-${args.subagent}-${uuid4()}`;\n\n // Execute the child workflow\n const childResult = await executeChild(config.workflowType, {\n workflowId: childWorkflowId,\n args: [{ prompt: args.prompt } satisfies SubagentInput],\n taskQueue: config.taskQueue ?? parentTaskQueue,\n });\n\n // Validate result if schema provided, otherwise pass through as-is\n const validated = config.resultSchema\n ? config.resultSchema.parse(childResult)\n : childResult;\n\n // Format content - stringify objects, pass strings through\n const content =\n typeof validated === \"string\"\n ? validated\n : JSON.stringify(validated, null, 2);\n\n return {\n content,\n result: {\n result: validated,\n childWorkflowId,\n },\n };\n };\n}\n","import type { SubagentConfig } from \"./types\";\nimport type { ToolMap, ToolDefinition } from \"./tool-registry\";\nimport { createTaskTool } from \"../tools/task/tool\";\nimport { createTaskHandler } from \"../tools/task/handler\";\nimport type { ToolHandler } from \"./tool-router\";\nimport type { GenericTaskToolSchemaType } from \"../tools/task/tool\";\nimport type { TaskHandlerResult } from \"../tools/task/handler\";\n\n/**\n * Configuration for subagent support\n */\nexport interface SubagentSupportConfig {\n /** Array of subagent configurations */\n subagents: SubagentConfig[];\n}\n\n/**\n * Result from withSubagentSupport - contains enhanced tools and the task handler\n */\nexport interface SubagentSupportResult<T extends ToolMap> {\n /** Combined tools (user tools + Task tool) */\n tools: T & { Task: ReturnType<typeof createTaskTool> };\n /** Task handler to be added to the tool router handlers */\n taskHandler: ToolHandler<GenericTaskToolSchemaType, TaskHandlerResult>;\n}\n\n/**\n * Adds subagent support to a tool map by including the Task tool and handler.\n *\n * Use this when you want to enable subagent spawning in your workflow.\n * The returned tools should be passed to createToolRegistry, and the\n * taskHandler should be included in your tool router handlers.\n *\n * @param userTools - Your workflow's existing tools\n * @param config - Subagent configuration\n * @returns Combined tools and the task handler\n *\n * @example\n * const { tools, taskHandler } = withSubagentSupport(\n * { AskUserQuestion: askUserQuestionTool },\n * {\n * subagents: [\n * {\n * name: \"researcher\",\n * description: \"Researches and gathers information\",\n * workflowType: \"researcherWorkflow\",\n * resultSchema: z.object({ findings: z.string() }),\n * },\n * ],\n * }\n * );\n *\n * const toolRegistry = createToolRegistry(tools);\n * const toolRouter = createToolRouter(\n * { registry: toolRegistry, threadId, appendToolResult },\n * {\n * AskUserQuestion: handleAskUserQuestion,\n * Task: taskHandler,\n * }\n * );\n */\nexport function withSubagentSupport<T extends ToolMap>(\n userTools: T,\n config: SubagentSupportConfig\n): SubagentSupportResult<T> {\n if (config.subagents.length === 0) {\n throw new Error(\"withSubagentSupport requires at least one subagent\");\n }\n\n const taskTool = createTaskTool(config.subagents);\n const taskHandler = createTaskHandler(config.subagents);\n\n return {\n tools: {\n ...userTools,\n Task: taskTool,\n } as T & { Task: ReturnType<typeof createTaskTool> },\n taskHandler,\n };\n}\n\n/**\n * Type guard to check if a tool map includes the Task tool\n */\nexport function hasTaskTool(\n tools: ToolMap\n): tools is ToolMap & { Task: ToolDefinition } {\n return \"Task\" in tools;\n}\n","import { proxyActivities } from \"@temporalio/workflow\";\nimport type { ZeitlichSharedActivities } from \"../activities\";\nimport type {\n ZeitlichAgentConfig,\n RunAgentActivity,\n SessionStartHook,\n SessionEndHook,\n SessionExitReason,\n} from \"./types\";\nimport { type AgentStateManager, type JsonSerializable } from \"./state-manager\";\nimport type { PromptManager } from \"./prompt-manager\";\nimport type { RawToolCall, ToolMap, ToolRegistry } from \"./tool-registry\";\nimport type { ToolRouter } from \"./tool-router\";\nimport type { StoredMessage } from \"@langchain/core/messages\";\n\n// Re-export subagent support for easy access\nexport { withSubagentSupport } from \"./subagent-support\";\nexport type {\n SubagentSupportConfig,\n SubagentSupportResult,\n} from \"./subagent-support\";\n\nexport interface ZeitlichSession {\n runSession<T extends JsonSerializable<T>>(\n prompt: string,\n stateManager: AgentStateManager<T>\n ): Promise<StoredMessage | null>;\n}\n\n/**\n * Session-level hooks for lifecycle events\n */\nexport interface SessionLifecycleHooks {\n /** Called when session starts */\n onSessionStart?: SessionStartHook;\n /** Called when session ends */\n onSessionEnd?: SessionEndHook;\n}\n\nexport const createSession = async <\n T extends ToolMap,\n TResults extends Record<string, unknown>,\n>(\n { threadId, agentName, maxTurns = 50, metadata = {} }: ZeitlichAgentConfig,\n {\n runAgent,\n promptManager,\n toolRouter,\n toolRegistry,\n hooks = {},\n }: {\n /** Workflow-specific runAgent activity (with tools pre-bound) */\n runAgent: RunAgentActivity;\n promptManager: PromptManager;\n toolRouter: ToolRouter<T, TResults>;\n toolRegistry: ToolRegistry<T>;\n /** Session lifecycle hooks */\n hooks?: SessionLifecycleHooks;\n }\n): Promise<ZeitlichSession> => {\n const { initializeThread, appendHumanMessage, parseToolCalls } =\n proxyActivities<ZeitlichSharedActivities>({\n startToCloseTimeout: \"30m\",\n retry: {\n maximumAttempts: 6,\n initialInterval: \"5s\",\n maximumInterval: \"15m\",\n backoffCoefficient: 4,\n },\n heartbeatTimeout: \"5m\",\n });\n\n // Helper to call session end hook\n const callSessionEnd = async (\n exitReason: SessionExitReason,\n turns: number\n ): Promise<void> => {\n if (hooks.onSessionEnd) {\n await hooks.onSessionEnd({\n threadId,\n agentName,\n exitReason,\n turns,\n metadata,\n });\n }\n };\n\n return {\n runSession: async (\n prompt: string,\n stateManager\n ): Promise<StoredMessage | null> => {\n if (hooks.onSessionStart) {\n await hooks.onSessionStart({\n threadId,\n agentName,\n metadata,\n });\n }\n\n await initializeThread(threadId);\n await appendHumanMessage(\n threadId,\n await promptManager.buildContextMessage(prompt)\n );\n\n let exitReason: SessionExitReason = \"completed\";\n\n try {\n while (\n stateManager.isRunning() &&\n !stateManager.isTerminal() &&\n stateManager.getTurns() < maxTurns\n ) {\n stateManager.incrementTurns();\n const currentTurn = stateManager.getTurns();\n\n const { message, stopReason } = await runAgent(\n {\n threadId,\n agentName,\n metadata,\n },\n {\n systemPrompt: await promptManager.getSystemPrompt(),\n }\n );\n\n if (stopReason === \"end_turn\") {\n stateManager.complete();\n exitReason = \"completed\";\n return message;\n }\n\n const rawToolCalls: RawToolCall[] = await parseToolCalls(message);\n const parsedToolCalls = rawToolCalls.map((tc: RawToolCall) =>\n toolRegistry.parseToolCall(tc)\n );\n\n // Hooks can call stateManager.waitForInput() to pause the session\n await toolRouter.processToolCalls(parsedToolCalls, {\n turn: currentTurn,\n });\n\n if (stateManager.getStatus() === \"WAITING_FOR_INPUT\") {\n exitReason = \"waiting_for_input\";\n break;\n }\n }\n\n // Check if we hit max turns\n if (stateManager.getTurns() >= maxTurns && stateManager.isRunning()) {\n exitReason = \"max_turns\";\n }\n } catch (error) {\n exitReason = \"failed\";\n throw error;\n } finally {\n // SessionEnd hook - always called\n await callSessionEnd(exitReason, stateManager.getTurns());\n }\n\n return null;\n },\n };\n};\n","import type { ToolMessageContent } from \"./thread-manager\";\nimport type { ParsedToolCallUnion, ToolMap } from \"./tool-registry\";\n\nimport type { StoredMessage } from \"@langchain/core/messages\";\nimport type { z } from \"zod\";\n\n/**\n * Agent execution status\n */\nexport type AgentStatus =\n | \"RUNNING\"\n | \"WAITING_FOR_INPUT\"\n | \"COMPLETED\"\n | \"FAILED\"\n | \"CANCELLED\";\n\n/**\n * Base state that all agents must have\n */\nexport interface BaseAgentState {\n status: AgentStatus;\n version: number;\n turns: number;\n}\n\n/**\n * File representation for agent workflows\n */\nexport interface AgentFile {\n /** Database/S3 file ID */\n id: string;\n /** Virtual path for agent (e.g., \"evidence/invoice.pdf\") */\n path: string;\n /** Original filename */\n filename: string;\n /** Generic description for prompt */\n description?: string;\n /** MIME type of the file */\n mimeType?: string;\n}\n\n/**\n * Agent response from LLM invocation\n */\nexport interface AgentResponse {\n message: StoredMessage;\n stopReason: string | null;\n usage?: {\n input_tokens?: number;\n output_tokens?: number;\n total_tokens?: number;\n };\n}\n\n/**\n * Configuration for a Zeitlich agent session\n */\nexport interface ZeitlichAgentConfig {\n threadId: string;\n agentName: string;\n metadata?: Record<string, unknown>;\n maxTurns?: number;\n}\n\n/**\n * Configuration passed to runAgent activity\n */\nexport interface RunAgentConfig {\n threadId: string;\n agentName: string;\n metadata?: Record<string, unknown>;\n}\n\n/**\n * Type signature for workflow-specific runAgent activity\n */\nexport type RunAgentActivity = (\n config: RunAgentConfig,\n invocationConfig: InvocationConfig\n) => Promise<AgentResponse>;\n\n/**\n * Per-invocation configuration passed to runAgent\n */\nexport interface InvocationConfig {\n systemPrompt: string;\n}\n\n/**\n * Configuration for appending a tool result\n */\nexport interface ToolResultConfig {\n threadId: string;\n toolCallId: string;\n /** Content for the tool message (string or complex content parts) */\n content: ToolMessageContent;\n}\n\n// ============================================================================\n// Subagent Configuration\n// ============================================================================\n\n/**\n * Configuration for a subagent that can be spawned by the parent workflow.\n *\n * @template TResult - Zod schema type for validating the child workflow's result\n */\nexport interface SubagentConfig<TResult extends z.ZodType = z.ZodType> {\n /** Identifier used in Task tool's subagent parameter */\n name: string;\n /** Description shown to the parent agent explaining what this subagent does */\n description: string;\n /** Temporal workflow type name (used with executeChild) */\n workflowType: string;\n /** Optional task queue - defaults to parent's queue if not specified */\n taskQueue?: string;\n /** Optional Zod schema to validate the child workflow's result. If omitted, result is passed through as-is. */\n resultSchema?: TResult;\n}\n\n/**\n * Input passed to child workflows when spawned as subagents\n */\nexport interface SubagentInput {\n /** The prompt/task from the parent agent */\n prompt: string;\n}\n\n// ============================================================================\n// Session Lifecycle Hooks\n// ============================================================================\n\n/**\n * Exit reasons for session termination\n */\nexport type SessionExitReason =\n | \"completed\"\n | \"max_turns\"\n | \"waiting_for_input\"\n | \"failed\"\n | \"cancelled\";\n\n/**\n * Context for PreToolUse hook - called before tool execution\n */\nexport interface PreToolUseHookContext<T extends ToolMap> {\n /** The tool call about to be executed */\n toolCall: ParsedToolCallUnion<T>;\n /** Thread identifier */\n threadId: string;\n /** Current turn number */\n turn: number;\n}\n\n/**\n * Result from PreToolUse hook - can block or modify execution\n */\nexport interface PreToolUseHookResult {\n /** Skip this tool call entirely */\n skip?: boolean;\n /** Modified args to use instead (must match schema) */\n modifiedArgs?: unknown;\n}\n\n/**\n * PreToolUse hook - called before tool execution, can block or modify\n */\nexport type PreToolUseHook<T extends ToolMap> = (\n ctx: PreToolUseHookContext<T>\n) => PreToolUseHookResult | Promise<PreToolUseHookResult>;\n\n/**\n * Context for PostToolUse hook - called after successful tool execution\n */\nexport interface PostToolUseHookContext<T extends ToolMap, TResult = unknown> {\n /** The tool call that was executed */\n toolCall: ParsedToolCallUnion<T>;\n /** The result from the tool handler */\n result: TResult;\n /** Thread identifier */\n threadId: string;\n /** Current turn number */\n turn: number;\n /** Execution duration in milliseconds */\n durationMs: number;\n}\n\n/**\n * PostToolUse hook - called after successful tool execution\n */\nexport type PostToolUseHook<T extends ToolMap, TResult = unknown> = (\n ctx: PostToolUseHookContext<T, TResult>\n) => void | Promise<void>;\n\n/**\n * Context for PostToolUseFailure hook - called when tool execution fails\n */\nexport interface PostToolUseFailureHookContext<T extends ToolMap> {\n /** The tool call that failed */\n toolCall: ParsedToolCallUnion<T>;\n /** The error that occurred */\n error: Error;\n /** Thread identifier */\n threadId: string;\n /** Current turn number */\n turn: number;\n}\n\n/**\n * Result from PostToolUseFailure hook - can recover from errors\n */\nexport interface PostToolUseFailureHookResult {\n /** Provide a fallback result instead of throwing */\n fallbackContent?: ToolMessageContent;\n /** Whether to suppress the error (still logs, but continues) */\n suppress?: boolean;\n}\n\n/**\n * PostToolUseFailure hook - called when tool execution fails\n */\nexport type PostToolUseFailureHook<T extends ToolMap> = (\n ctx: PostToolUseFailureHookContext<T>\n) => PostToolUseFailureHookResult | Promise<PostToolUseFailureHookResult>;\n\n/**\n * Context for SessionStart hook - called when session begins\n */\nexport interface SessionStartHookContext {\n /** Thread identifier */\n threadId: string;\n /** Name of the agent */\n agentName: string;\n /** Session metadata */\n metadata: Record<string, unknown>;\n}\n\n/**\n * SessionStart hook - called when session begins\n */\nexport type SessionStartHook = (\n ctx: SessionStartHookContext\n) => void | Promise<void>;\n\n/**\n * Context for SessionEnd hook - called when session ends\n */\nexport interface SessionEndHookContext {\n /** Thread identifier */\n threadId: string;\n /** Name of the agent */\n agentName: string;\n /** Reason the session ended */\n exitReason: SessionExitReason;\n /** Total turns executed */\n turns: number;\n /** Session metadata */\n metadata: Record<string, unknown>;\n}\n\n/**\n * SessionEnd hook - called when session ends\n */\nexport type SessionEndHook = (\n ctx: SessionEndHookContext\n) => void | Promise<void>;\n\n/**\n * Combined hooks interface for session lifecycle\n */\nexport interface SessionHooks<T extends ToolMap, TResult = unknown> {\n /** Called before each tool execution - can block or modify */\n onPreToolUse?: PreToolUseHook<T>;\n /** Called after each successful tool execution */\n onPostToolUse?: PostToolUseHook<T, TResult>;\n /** Called when tool execution fails */\n onPostToolUseFailure?: PostToolUseFailureHook<T>;\n /** Called when session starts */\n onSessionStart?: SessionStartHook;\n /** Called when session ends */\n onSessionEnd?: SessionEndHook;\n}\n\n/**\n * Helper to check if status is terminal\n */\nexport function isTerminalStatus(status: AgentStatus): boolean {\n return (\n status === \"COMPLETED\" || status === \"FAILED\" || status === \"CANCELLED\"\n );\n}\n","import {\n type AgentStatus,\n type BaseAgentState,\n isTerminalStatus,\n} from \"./types\";\n\n/**\n * JSON primitive types that Temporal can serialize\n */\nexport type JsonPrimitive = string | number | boolean | null | undefined;\n\n/**\n * JSON-serializable value (recursive type for Temporal compatibility)\n */\nexport type JsonValue =\n | JsonPrimitive\n | JsonValue[]\n | { [key: string]: JsonValue };\n\n/**\n * Type constraint ensuring T only contains JSON-serializable values.\n * Use this for custom state to ensure Temporal workflow compatibility.\n *\n * Allows: primitives, arrays, plain objects, and JsonValue\n * Rejects: functions, symbols, undefined, class instances with methods\n */\nexport type JsonSerializable<T> = {\n [K in keyof T]: T[K] extends JsonValue\n ? T[K]\n : T[K] extends JsonPrimitive\n ? T[K]\n : T[K] extends (infer U)[]\n ? U extends JsonValue\n ? T[K]\n : JsonSerializable<U>[]\n : T[K] extends object\n ? JsonSerializable<T[K]>\n : never;\n};\n\n/**\n * Configuration for creating an agent state manager\n */\nexport interface AgentStateManagerConfig<\n TCustom extends JsonSerializable<TCustom>,\n> {\n /** Initial values for custom state keys */\n initialState: TCustom;\n}\n\n/**\n * Full state type combining base state with custom state\n */\nexport type AgentState<TCustom extends JsonSerializable<TCustom>> =\n BaseAgentState & TCustom;\n\n/**\n * Agent state manager interface\n * Note: Temporal handlers must be set up in the workflow file due to\n * Temporal's workflow isolation requirements. This manager provides\n * the state and helpers needed for those handlers.\n */\nexport interface AgentStateManager<TCustom extends JsonSerializable<TCustom>> {\n /** Get current status */\n getStatus(): AgentStatus;\n /** Check if agent is running */\n isRunning(): boolean;\n /** Check if agent is in terminal state */\n isTerminal(): boolean;\n /** Get current state version */\n getVersion(): number;\n\n /** Set status to RUNNING */\n run(): void;\n /** Set status to WAITING_FOR_INPUT */\n waitForInput(): void;\n /** Set status to COMPLETED */\n complete(): void;\n /** Set status to FAILED */\n fail(): void;\n /** Set status to CANCELLED */\n cancel(): void;\n\n /** Increment state version (call after state changes) */\n incrementVersion(): void;\n\n /** Increment turns (call after each turn) */\n incrementTurns(): void;\n\n /** Get current turns */\n getTurns(): number;\n\n /** Get a custom state value by key */\n get<K extends keyof TCustom>(key: K): TCustom[K];\n\n /** Set a custom state value by key */\n set<K extends keyof TCustom>(key: K, value: TCustom[K]): void;\n\n /** Get full state for query handler */\n getCurrentState(): AgentState<TCustom>;\n\n /** Check if should return from waitForStateChange */\n shouldReturnFromWait(lastKnownVersion: number): boolean;\n}\n\n/**\n * Creates an agent state manager for tracking workflow state.\n *\n * The manager owns all state internally:\n * - Default state: status, version (from BaseAgentState)\n * - Custom state: provided via initialState config\n *\n * Note: Due to Temporal's workflow isolation, handlers must be set up\n * in the workflow file using defineQuery/defineUpdate and setHandler.\n * This manager provides the state and logic needed for those handlers.\n */\nexport function createAgentStateManager<\n TCustom extends JsonSerializable<TCustom> = Record<string, never>,\n>(config?: AgentStateManagerConfig<TCustom>): AgentStateManager<TCustom> {\n // Default state (BaseAgentState fields)\n let status: AgentStatus = \"RUNNING\";\n let version = 0;\n let turns = 0;\n\n // Custom state\n const customState = { ...(config?.initialState ?? ({} as TCustom)) };\n\n function buildState(): AgentState<TCustom> {\n return {\n status,\n version,\n turns,\n ...customState,\n } as AgentState<TCustom>;\n }\n\n return {\n getStatus(): AgentStatus {\n return status;\n },\n\n isRunning(): boolean {\n return status === \"RUNNING\";\n },\n\n isTerminal(): boolean {\n return isTerminalStatus(status);\n },\n\n getTurns(): number {\n return turns;\n },\n\n getVersion(): number {\n return version;\n },\n\n run(): void {\n status = \"RUNNING\";\n version++;\n },\n\n waitForInput(): void {\n status = \"WAITING_FOR_INPUT\";\n version++;\n },\n\n complete(): void {\n status = \"COMPLETED\";\n version++;\n },\n\n fail(): void {\n status = \"FAILED\";\n version++;\n },\n\n cancel(): void {\n status = \"CANCELLED\";\n version++;\n },\n\n incrementVersion(): void {\n version++;\n },\n\n incrementTurns(): void {\n turns++;\n },\n\n get<K extends keyof TCustom>(key: K): TCustom[K] {\n return customState[key];\n },\n\n set<K extends keyof TCustom>(key: K, value: TCustom[K]): void {\n customState[key] = value;\n version++;\n },\n\n getCurrentState(): AgentState<TCustom> {\n return buildState();\n },\n\n shouldReturnFromWait(lastKnownVersion: number): boolean {\n return version > lastKnownVersion || isTerminalStatus(status);\n },\n };\n}\n\n/**\n * Handler names used across agents\n */\nexport const AGENT_HANDLER_NAMES = {\n getAgentState: \"getAgentState\",\n waitForStateChange: \"waitForStateChange\",\n addMessage: \"addMessage\",\n} as const;\n","import type { MessageContent } from \"@langchain/core/messages\";\n\n/**\n * Configuration for creating a prompt manager\n */\nexport interface PromptManagerConfig<TContext = unknown> {\n /**\n * Base system prompt (e.g., Auditron identity).\n * Can be a static string or async function.\n */\n baseSystemPrompt: string | (() => string | Promise<string>);\n /**\n * Agent-specific instructions prompt.\n * Can be a static string or async function.\n */\n instructionsPrompt: string | (() => string | Promise<string>);\n /**\n * Build context message content from agent-specific context.\n * Returns MessageContent array for the initial HumanMessage.\n */\n buildContextMessage: (\n context: TContext\n ) => MessageContent | Promise<MessageContent>;\n}\n\n/**\n * Prompt manager interface\n */\nexport interface PromptManager<TContext = unknown> {\n /**\n * Get the full system prompt (base + instructions combined).\n */\n getSystemPrompt(): Promise<string>;\n /**\n * Build the initial context message content.\n */\n buildContextMessage(context: TContext): Promise<MessageContent>;\n}\n\n/**\n * Creates a prompt manager for handling system prompts and context messages.\n *\n */\nexport function createPromptManager<TContext = unknown>(\n config: PromptManagerConfig<TContext>\n): PromptManager<TContext> {\n const { baseSystemPrompt, instructionsPrompt, buildContextMessage } = config;\n\n async function resolvePrompt(\n prompt: string | (() => string | Promise<string>)\n ): Promise<string> {\n if (typeof prompt === \"function\") {\n return prompt();\n }\n return prompt;\n }\n\n return {\n async getSystemPrompt(): Promise<string> {\n const base = await resolvePrompt(baseSystemPrompt);\n const instructions = await resolvePrompt(instructionsPrompt);\n return [base, instructions].join(\"\\n\");\n },\n\n async buildContextMessage(context: TContext): Promise<MessageContent> {\n return buildContextMessage(context);\n },\n };\n}\n","import type {\n MessageStructure,\n MessageToolDefinition,\n} from \"@langchain/core/messages\";\nimport type { z } from \"zod\";\n\n/**\n * A tool definition with a name, description, and Zod schema for arguments.\n */\nexport interface ToolDefinition<\n TName extends string = string,\n TSchema extends z.ZodType = z.ZodType,\n> {\n name: TName;\n description: string;\n schema: TSchema;\n strict?: boolean;\n max_uses?: number;\n}\n\n/**\n * A map of tool keys to tool definitions.\n */\nexport type ToolMap = Record<string, ToolDefinition>;\n\n/**\n * Converts a ToolMap to MessageStructure-compatible tools type.\n * Maps each tool's name to a MessageToolDefinition with inferred input type from the schema.\n */\nexport type ToolMapToMessageTools<T extends ToolMap> = {\n [K in keyof T as T[K][\"name\"]]: MessageToolDefinition<\n z.infer<T[K][\"schema\"]>\n >;\n};\n\n/**\n * Creates a MessageStructure type from a ToolMap.\n * This allows typed tool_calls on AIMessage when using parseToolCalls.\n */\nexport type ToolMapToMessageStructure<T extends ToolMap> = MessageStructure<\n ToolMapToMessageTools<T>\n>;\n\n/**\n * Extract the tool names from a tool map (uses the tool's name property, not the key).\n */\nexport type ToolNames<T extends ToolMap> = T[keyof T][\"name\"];\n\n/**\n * A raw tool call as received from the LLM before parsing.\n */\nexport interface RawToolCall {\n id?: string;\n name: string;\n args: unknown;\n}\n\n/**\n * A parsed tool call with validated arguments for a specific tool.\n */\nexport interface ParsedToolCall<\n TName extends string = string,\n TArgs = unknown,\n> {\n id: string;\n name: TName;\n args: TArgs;\n}\n\n/**\n * Union type of all possible parsed tool calls from a tool map.\n */\nexport type ParsedToolCallUnion<T extends ToolMap> = {\n [K in keyof T]: ParsedToolCall<T[K][\"name\"], z.infer<T[K][\"schema\"]>>;\n}[keyof T];\n\n/**\n * The tool registry interface with full type inference.\n */\nexport interface ToolRegistry<T extends ToolMap> {\n /**\n * Parse and validate a raw tool call against the registry.\n * Returns a typed tool call with validated arguments.\n */\n parseToolCall(toolCall: RawToolCall): ParsedToolCallUnion<T>;\n\n /**\n * Get the list of all tools in the registry.\n */\n getToolList(): T[keyof T][];\n\n /**\n * Get a specific tool by its key in the registry.\n */\n getTool<K extends keyof T>(name: K): T[K];\n\n /**\n * Check if a tool with the given name exists in the registry.\n */\n hasTool(name: string): boolean;\n\n /**\n * Get all tool names in the registry.\n */\n getToolNames(): ToolNames<T>[];\n}\n\n/**\n * Creates a type-safe tool registry for parsing and managing tool definitions.\n *\n * @example\n * const registry = createToolRegistry({\n * AssessAttribute: assessAttributeTool,\n * AskUserQuestion: userInteractionTool,\n * });\n *\n * const toolCalls = message.tool_calls.map(tc => registry.parseToolCall(tc));\n * const tools = registry.getToolList();\n */\nexport function createToolRegistry<T extends ToolMap>(\n tools: T\n): ToolRegistry<T> {\n const toolMap = new Map<string, T[keyof T]>();\n\n for (const [_key, tool] of Object.entries(tools)) {\n toolMap.set(tool.name, tool as T[keyof T]);\n }\n\n return {\n parseToolCall(toolCall: RawToolCall): ParsedToolCallUnion<T> {\n const tool = toolMap.get(toolCall.name);\n\n if (!tool) {\n throw new Error(`Tool ${toolCall.name} not found`);\n }\n\n // Parse and validate args using the tool's schema\n const parsedArgs = tool.schema.parse(toolCall.args);\n\n return {\n id: toolCall.id ?? \"\",\n name: toolCall.name,\n args: parsedArgs,\n } as ParsedToolCallUnion<T>;\n },\n\n getToolList(): T[keyof T][] {\n return Object.values(tools) as T[keyof T][];\n },\n\n getTool<K extends keyof T>(name: K): T[K] {\n return tools[name];\n },\n\n hasTool(name: string): boolean {\n return toolMap.has(name);\n },\n\n getToolNames(): ToolNames<T>[] {\n return Array.from(toolMap.keys()) as ToolNames<T>[];\n },\n };\n}\n","import type { ToolMessageContent } from \"./thread-manager\";\nimport type {\n ParsedToolCall,\n ParsedToolCallUnion,\n ToolMap,\n ToolNames,\n ToolRegistry,\n} from \"./tool-registry\";\nimport type {\n ToolResultConfig,\n PreToolUseHook,\n PostToolUseHook,\n PostToolUseFailureHook,\n} from \"./types\";\n\nimport type { z } from \"zod\";\n\nexport type { ToolMessageContent };\n\n/**\n * Function signature for appending tool results to a thread.\n */\nexport type AppendToolResultFn = (config: ToolResultConfig) => Promise<void>;\n\n/**\n * The response from a tool handler.\n * Contains the content for the tool message and the result to return from processToolCalls.\n */\nexport interface ToolHandlerResponse<TResult> {\n /** Content for the tool message added to the thread */\n content: ToolMessageContent;\n /** Result returned from processToolCalls */\n result: TResult;\n}\n\n/**\n * A handler function for a specific tool.\n * Receives the parsed args and tool call ID, returns a response with content and result.\n */\nexport type ToolHandler<TArgs, TResult> = (\n args: TArgs,\n toolCallId: string\n) => ToolHandlerResponse<TResult> | Promise<ToolHandlerResponse<TResult>>;\n\n/**\n * Activity-compatible tool handler that always returns a Promise.\n * Use this for tool handlers registered as Temporal activities.\n */\nexport type ActivityToolHandler<TArgs, TResult> = (\n args: TArgs,\n toolCallId: string\n) => Promise<ToolHandlerResponse<TResult>>;\n\n/**\n * Extract the args type for a specific tool name from a tool map.\n */\nexport type ToolArgs<T extends ToolMap, TName extends ToolNames<T>> = z.infer<\n Extract<T[keyof T], { name: TName }>[\"schema\"]\n>;\n\n/**\n * A map of tool handlers keyed by tool name with typed results.\n * Each handler receives the properly typed args for that tool.\n */\nexport type ToolHandlerMap<\n T extends ToolMap,\n TResults extends Record<ToolNames<T>, unknown>,\n> = {\n [TName in ToolNames<T>]: ToolHandler<ToolArgs<T, TName>, TResults[TName]>;\n};\n\n/**\n * Extract the ToolMap type from a ToolRegistry instance type.\n */\nexport type InferToolMap<T> = T extends ToolRegistry<infer U> ? U : never;\n\n/**\n * The result of processing a tool call.\n */\nexport interface ToolCallResult<\n TName extends string = string,\n TResult = unknown,\n> {\n toolCallId: string;\n name: TName;\n result: TResult;\n}\n\n/**\n * Union of all possible tool call results based on handler return types.\n */\nexport type ToolCallResultUnion<TResults extends Record<string, unknown>> = {\n [TName in keyof TResults & string]: ToolCallResult<TName, TResults[TName]>;\n}[keyof TResults & string];\n\n/**\n * Tool-specific hooks for the router\n */\nexport interface ToolRouterHooks<T extends ToolMap, TResult = unknown> {\n /** Called before each tool execution - can block or modify */\n onPreToolUse?: PreToolUseHook<T>;\n /** Called after each successful tool execution */\n onPostToolUse?: PostToolUseHook<T, TResult>;\n /** Called when tool execution fails */\n onPostToolUseFailure?: PostToolUseFailureHook<T>;\n}\n\n/**\n * Options for tool router.\n */\nexport interface ToolRouterOptions<T extends ToolMap, TResult = unknown> {\n /** Tool registry - used for type inference */\n registry: ToolRegistry<T>;\n /** Thread ID for appending tool results */\n threadId: string;\n /** Function to append tool results to the thread (called automatically after each handler) */\n appendToolResult: AppendToolResultFn;\n /** Whether to process tools in parallel (default: true) */\n parallel?: boolean;\n /** Lifecycle hooks for tool execution */\n hooks?: ToolRouterHooks<T, TResult>;\n}\n\n/**\n * Context passed to processToolCalls for hook execution\n */\nexport interface ProcessToolCallsContext {\n /** Current turn number (for hooks) */\n turn?: number;\n}\n\n/**\n * The tool router interface with full type inference for both args and results.\n */\nexport interface ToolRouter<\n T extends ToolMap,\n TResults extends Record<string, unknown>,\n> {\n /**\n * Process all tool calls using the registered handlers.\n * Returns typed results based on handler return types.\n * @param toolCalls - Array of parsed tool calls to process\n * @param context - Optional context including turn number for hooks\n */\n processToolCalls(\n toolCalls: ParsedToolCallUnion<T>[],\n context?: ProcessToolCallsContext\n ): Promise<ToolCallResultUnion<TResults>[]>;\n\n /**\n * Process tool calls matching a specific name with a custom handler.\n */\n processToolCallsByName<TName extends ToolNames<T>, TResult>(\n toolCalls: ParsedToolCallUnion<T>[],\n toolName: TName,\n handler: ToolHandler<ToolArgs<T, TName>, TResult>\n ): Promise<ToolCallResult<TName, TResult>[]>;\n\n /**\n * Filter tool calls by name.\n */\n filterByName<TName extends ToolNames<T>>(\n toolCalls: ParsedToolCallUnion<T>[],\n name: TName\n ): ParsedToolCall<TName, ToolArgs<T, TName>>[];\n\n /**\n * Check if any tool call matches the given name.\n */\n hasToolCall(toolCalls: ParsedToolCallUnion<T>[], name: ToolNames<T>): boolean;\n\n /**\n * Filter results by tool name.\n */\n getResultsByName<TName extends ToolNames<T> & keyof TResults>(\n results: ToolCallResultUnion<TResults>[],\n name: TName\n ): ToolCallResult<TName, TResults[TName]>[];\n}\n\n/**\n * Infer result types from a handler map.\n * Uses `any` for args due to function contravariance - handlers with specific\n * args types won't extend ToolHandler<unknown, R>.\n */\nexport type InferHandlerResults<H> = {\n // eslint-disable-next-line @typescript-eslint/no-explicit-any\n [K in keyof H & string]: H[K] extends ToolHandler<any, infer R>\n ? Awaited<R>\n : never;\n};\n\n/**\n * Creates a tool router for declarative tool call processing.\n * ToolMap type is inferred from options.registry, result types from handlers.\n *\n * @example\n * const router = createToolRouter(\n * {\n * registry: controlTestToolRegistry,\n * threadId,\n * appendToolResult,\n * hooks: {\n * onPreToolUse: (ctx) => { console.log('Before:', ctx.toolCall.name); },\n * onPostToolUse: (ctx) => { console.log('After:', ctx.toolCall.name, ctx.durationMs); },\n * },\n * },\n * {\n * AskUserQuestion: async (args, toolCallId) => ({ content: '...', result: {...} }),\n * // ... other handlers\n * },\n * );\n *\n * const results = await router.processToolCalls(toolCalls, { turn: 1 });\n * // results[0].result is typed based on handler return types\n */\nexport function createToolRouter<\n T extends ToolMap,\n THandlers extends {\n [TName in ToolNames<T>]: ToolHandler<ToolArgs<T, TName>, unknown>;\n },\n>(\n options: ToolRouterOptions<\n T,\n ToolCallResultUnion<InferHandlerResults<THandlers>>\n >,\n handlers: THandlers\n): ToolRouter<T, InferHandlerResults<THandlers>> {\n const { parallel = true, threadId, appendToolResult, hooks } = options;\n\n type TResults = InferHandlerResults<THandlers>;\n\n async function processToolCall(\n toolCall: ParsedToolCallUnion<T>,\n turn: number\n ): Promise<ToolCallResultUnion<TResults> | null> {\n const startTime = Date.now();\n\n // PreToolUse hook - can skip or modify args\n let effectiveArgs: unknown = toolCall.args;\n if (hooks?.onPreToolUse) {\n const preResult = await hooks.onPreToolUse({\n toolCall,\n threadId,\n turn,\n });\n if (preResult?.skip) {\n // Skip this tool call - append a skip message and return null\n await appendToolResult({\n threadId,\n toolCallId: toolCall.id,\n content: JSON.stringify({\n skipped: true,\n reason: \"Skipped by PreToolUse hook\",\n }),\n });\n return null;\n }\n if (preResult?.modifiedArgs !== undefined) {\n effectiveArgs = preResult.modifiedArgs;\n }\n }\n\n const handler = handlers[toolCall.name as keyof THandlers];\n let result: unknown;\n let content: ToolMessageContent;\n\n try {\n if (handler) {\n // Use effective args (potentially modified by PreToolUse hook)\n // Cast is safe: either original args or modified args that must match schema\n const response = await handler(\n effectiveArgs as Parameters<typeof handler>[0],\n toolCall.id\n );\n result = response.result;\n content = response.content;\n } else {\n result = { error: `Unknown tool: ${toolCall.name}` };\n content = JSON.stringify(result, null, 2);\n }\n } catch (error) {\n // PostToolUseFailure hook - can recover from errors\n if (hooks?.onPostToolUseFailure) {\n const failureResult = await hooks.onPostToolUseFailure({\n toolCall,\n error: error instanceof Error ? error : new Error(String(error)),\n threadId,\n turn,\n });\n if (failureResult?.fallbackContent !== undefined) {\n content = failureResult.fallbackContent;\n result = { error: String(error), recovered: true };\n } else if (failureResult?.suppress) {\n content = JSON.stringify({ error: String(error), suppressed: true });\n result = { error: String(error), suppressed: true };\n } else {\n throw error;\n }\n } else {\n throw error;\n }\n }\n\n // Automatically append tool result to thread\n await appendToolResult({ threadId, toolCallId: toolCall.id, content });\n\n const toolResult = {\n toolCallId: toolCall.id,\n name: toolCall.name,\n result,\n } as ToolCallResultUnion<TResults>;\n\n // PostToolUse hook - called after successful execution\n if (hooks?.onPostToolUse) {\n const durationMs = Date.now() - startTime;\n await hooks.onPostToolUse({\n toolCall,\n result: toolResult,\n threadId,\n turn,\n durationMs,\n });\n }\n\n return toolResult;\n }\n\n return {\n async processToolCalls(\n toolCalls: ParsedToolCallUnion<T>[],\n context?: ProcessToolCallsContext\n ): Promise<ToolCallResultUnion<TResults>[]> {\n if (toolCalls.length === 0) {\n return [];\n }\n\n const turn = context?.turn ?? 0;\n\n if (parallel) {\n const results = await Promise.all(\n toolCalls.map((tc) => processToolCall(tc, turn))\n );\n // Filter out null results (skipped tool calls)\n return results.filter(\n (r): r is NonNullable<typeof r> => r !== null\n ) as ToolCallResultUnion<TResults>[];\n }\n\n // Sequential processing\n const results: ToolCallResultUnion<TResults>[] = [];\n for (const toolCall of toolCalls) {\n const result = await processToolCall(toolCall, turn);\n if (result !== null) {\n results.push(result);\n }\n }\n return results;\n },\n\n async processToolCallsByName<TName extends ToolNames<T>, TResult>(\n toolCalls: ParsedToolCallUnion<T>[],\n toolName: TName,\n handler: ToolHandler<ToolArgs<T, TName>, TResult>\n ): Promise<ToolCallResult<TName, TResult>[]> {\n const matchingCalls = toolCalls.filter((tc) => tc.name === toolName);\n\n if (matchingCalls.length === 0) {\n return [];\n }\n\n const processOne = async (\n toolCall: ParsedToolCallUnion<T>\n ): Promise<ToolCallResult<TName, TResult>> => {\n const response = await handler(\n toolCall.args as ToolArgs<T, TName>,\n toolCall.id\n );\n\n // Automatically append tool result to thread\n await appendToolResult({\n threadId,\n toolCallId: toolCall.id,\n content: response.content,\n });\n\n return {\n toolCallId: toolCall.id,\n name: toolCall.name as TName,\n result: response.result,\n };\n };\n\n if (parallel) {\n return Promise.all(matchingCalls.map(processOne));\n }\n\n const results: ToolCallResult<TName, TResult>[] = [];\n for (const toolCall of matchingCalls) {\n results.push(await processOne(toolCall));\n }\n return results;\n },\n\n filterByName<TName extends ToolNames<T>>(\n toolCalls: ParsedToolCallUnion<T>[],\n name: TName\n ): ParsedToolCall<TName, ToolArgs<T, TName>>[] {\n return toolCalls.filter(\n (tc): tc is ParsedToolCall<TName, ToolArgs<T, TName>> =>\n tc.name === name\n );\n },\n\n hasToolCall(\n toolCalls: ParsedToolCallUnion<T>[],\n name: ToolNames<T>\n ): boolean {\n return toolCalls.some((tc) => tc.name === name);\n },\n\n getResultsByName<TName extends ToolNames<T> & keyof TResults>(\n results: ToolCallResultUnion<TResults>[],\n name: TName\n ): ToolCallResult<TName, TResults[TName]>[] {\n return results.filter(\n (r): r is ToolCallResult<TName, TResults[TName]> => r.name === name\n );\n },\n };\n}\n\n/**\n * Utility to check if there were no tool calls besides a specific one\n */\nexport function hasNoOtherToolCalls<T extends ToolMap>(\n toolCalls: ParsedToolCallUnion<T>[],\n excludeName: ToolNames<T>\n): boolean {\n return toolCalls.filter((tc) => tc.name !== excludeName).length === 0;\n}\n","import z from \"zod\";\n\nexport const askUserQuestionTool = {\n name: \"AskUserQuestion\" as const,\n description: `Use this tool when you need to ask the user questions during execution. This allows you to:\n\n1. Gather user preferences or requirements\n2. Clarify ambiguous instructions\n3. Get decisions on implementation choices as you work\n4. Offer choices to the user about what direction to take.\n\nUsage notes:\n\n* Users will always be able to select \"Other\" to provide custom text input\n* Use multiSelect: true to allow multiple answers to be selected for a question\n* If you recommend a specific option, make that the first option in the list and add \"(Recommended)\" at the end of the label\n`,\n schema: z.object({\n questions: z.array(\n z.object({\n question: z.string().describe(\"The full question text to display\"),\n header: z\n .string()\n .describe(\"Short label for the question (max 12 characters)\"),\n options: z\n .array(\n z.object({\n label: z.string(),\n description: z.string(),\n })\n )\n .min(0)\n .max(4)\n .describe(\"Array of 0-4 choices, each with label and description\"),\n multiSelect: z\n .boolean()\n .describe(\"If true, users can select multiple options\"),\n })\n ),\n }),\n strict: true,\n};\n\nexport type AskUserQuestionToolSchemaType = z.infer<\n typeof askUserQuestionTool.schema\n>;\n","import { z } from \"zod\";\n\nexport const globTool = {\n name: \"Glob\" as const,\n description: `Search for files matching a glob pattern within the available file system.\n\nUsage:\n- Use glob patterns like \"**/*.ts\" to find all TypeScript files\n- Use \"docs/**\" to find all files in the docs directory\n- Patterns are matched against virtual paths in the file system\n\nExamples:\n- \"*.md\" - Find all markdown files in the root\n- \"**/*.test.ts\" - Find all test files recursively\n- \"src/**/*.ts\" - Find all TypeScript files in src directory\n`,\n schema: z.object({\n pattern: z.string().describe(\"Glob pattern to match files against\"),\n root: z\n .string()\n .optional()\n .describe(\"Optional root directory to search from\"),\n }),\n strict: true,\n};\n\nexport type GlobToolSchemaType = z.infer<typeof globTool.schema>;\n","import { z } from \"zod\";\n\nexport const grepTool = {\n name: \"Grep\" as const,\n description: `Search file contents for a pattern within the available file system.\n\nUsage:\n- Searches for a regex pattern across file contents\n- Returns matching lines with file paths and line numbers\n- Can filter by file patterns and limit results\n\nExamples:\n- Search for \"TODO\" in all files\n- Search for function definitions with \"function.*handleClick\"\n- Search case-insensitively with ignoreCase: true\n`,\n schema: z.object({\n pattern: z\n .string()\n .describe(\"Regex pattern to search for in file contents\"),\n ignoreCase: z\n .boolean()\n .optional()\n .describe(\"Case-insensitive search (default: false)\"),\n maxMatches: z\n .number()\n .optional()\n .describe(\"Maximum number of matches to return (default: 50)\"),\n includePatterns: z\n .array(z.string())\n .optional()\n .describe(\"Glob patterns to include (e.g., ['*.ts', '*.js'])\"),\n excludePatterns: z\n .array(z.string())\n .optional()\n .describe(\"Glob patterns to exclude (e.g., ['*.test.ts'])\"),\n contextLines: z\n .number()\n .optional()\n .describe(\"Number of context lines to show around matches\"),\n }),\n strict: true,\n};\n\nexport type GrepToolSchemaType = z.infer<typeof grepTool.schema>;\n","import { z } from \"zod\";\n\nexport const readTool = {\n name: \"FileRead\" as const,\n description: `Read file contents with optional pagination.\n\nUsage:\n- Provide the virtual path to the file you want to read\n- Supports text files, images, and PDFs\n- For large files, use offset and limit to read specific portions\n\nThe tool returns the file content in an appropriate format:\n- Text files: Plain text content\n- Images: Base64-encoded image data\n- PDFs: Extracted text content\n`,\n schema: z.object({\n path: z.string().describe(\"Virtual path to the file to read\"),\n offset: z\n .number()\n .optional()\n .describe(\n \"Line number to start reading from (1-indexed, for text files)\"\n ),\n limit: z\n .number()\n .optional()\n .describe(\"Maximum number of lines to read (for text files)\"),\n }),\n strict: true,\n};\n\nexport type ReadToolSchemaType = z.infer<typeof readTool.schema>;\n","import { z } from \"zod\";\n\nexport const writeTool = {\n name: \"FileWrite\" as const,\n description: `Create or overwrite a file with new content.\n\nUsage:\n- Provide the absolute virtual path to the file\n- The file will be created if it doesn't exist\n- If the file exists, it will be completely overwritten\n\nIMPORTANT:\n- You must read the file first (in this session) before writing to it\n- This is an atomic write operation - the entire file is replaced\n- Path must be absolute (e.g., \"/docs/readme.md\", not \"docs/readme.md\")\n`,\n schema: z.object({\n file_path: z\n .string()\n .describe(\"The absolute virtual path to the file to write\"),\n content: z.string().describe(\"The content to write to the file\"),\n }),\n strict: true,\n};\n\nexport type WriteToolSchemaType = z.infer<typeof writeTool.schema>;\n","import { z } from \"zod\";\n\nexport const editTool = {\n name: \"FileEdit\" as const,\n description: `Edit specific sections of a file by replacing text.\n\nUsage:\n- Provide the exact text to find and replace\n- The old_string must match exactly (whitespace-sensitive)\n- By default, only replaces the first occurrence\n- Use replace_all: true to replace all occurrences\n\nIMPORTANT:\n- You must read the file first (in this session) before editing it\n- old_string must be unique in the file (unless using replace_all)\n- The operation fails if old_string is not found\n- old_string and new_string must be different\n`,\n schema: z.object({\n file_path: z\n .string()\n .describe(\"The absolute virtual path to the file to modify\"),\n old_string: z.string().describe(\"The exact text to replace\"),\n new_string: z\n .string()\n .describe(\n \"The text to replace it with (must be different from old_string)\"\n ),\n replace_all: z\n .boolean()\n .optional()\n .describe(\n \"If true, replace all occurrences of old_string (default: false)\"\n ),\n }),\n strict: true,\n};\n\nexport type EditToolSchemaType = z.infer<typeof editTool.schema>;\n","import type { ContentBlock } from \"@langchain/core/messages\";\n\n/**\n * File node in the tree structure provided to the agent.\n * Represents both files and directories in a virtual file system.\n */\nexport interface FileNode {\n /** Virtual path (e.g., \"docs/readme.md\") */\n path: string;\n /** Whether this is a file or directory */\n type: \"file\" | \"directory\";\n /** Optional description shown in the prompt */\n description?: string;\n /** MIME type for multimodal content (e.g., \"image/png\", \"application/pdf\") */\n mimeType?: string;\n /** Provider-specific metadata (S3 key, database ID, etc.) */\n metadata?: Record<string, unknown>;\n /** Child nodes for directories */\n children?: FileNode[];\n}\n\n/**\n * Options for rendering the file tree in the prompt\n */\nexport interface FileTreeRenderOptions {\n /** Maximum depth to render (default: unlimited) */\n maxDepth?: number;\n /** Include file descriptions (default: true) */\n showDescriptions?: boolean;\n /** Show MIME types next to files (default: false) */\n showMimeTypes?: boolean;\n /** Glob patterns to exclude from display */\n excludePatterns?: string[];\n /** Custom header text (default: \"Available files and directories:\") */\n headerText?: string;\n /** Custom description text (default: \"You have access to the following files. Use the Read, Glob, and Grep tools to explore them.\") */\n descriptionText?: string;\n}\n\n/**\n * Text file content\n */\nexport interface TextFileContent {\n type: \"text\";\n content: string;\n}\n\n/**\n * Image file content (base64 encoded)\n */\nexport interface ImageFileContent {\n type: \"image\";\n mimeType: string;\n /** Base64-encoded image data */\n data: string;\n}\n\n/**\n * PDF file content (extracted text)\n */\nexport interface PdfFileContent {\n type: \"pdf\";\n /** Extracted text content */\n content: string;\n}\n\n/**\n * Union type for all file content types\n */\nexport type FileContent = TextFileContent | ImageFileContent | PdfFileContent;\n\n/**\n * Options for grep operations\n */\nexport interface GrepOptions {\n /** Case-insensitive search */\n ignoreCase?: boolean;\n /** Maximum number of matches to return */\n maxMatches?: number;\n /** File patterns to include (glob) */\n includePatterns?: string[];\n /** File patterns to exclude (glob) */\n excludePatterns?: string[];\n /** Include N lines of context around matches */\n contextLines?: number;\n}\n\n/**\n * A single grep match result\n */\nexport interface GrepMatch {\n /** Path to the file containing the match */\n path: string;\n /** Line number (1-indexed) */\n lineNumber: number;\n /** The matching line content */\n line: string;\n /** Context lines before the match */\n contextBefore?: string[];\n /** Context lines after the match */\n contextAfter?: string[];\n}\n\n/**\n * Provider interface for file system operations.\n * Implement this interface to support different backends (local FS, S3, Redis, etc.)\n */\nexport interface FileSystemProvider {\n /**\n * Find files matching a glob pattern\n * @param pattern Glob pattern to match\n * @param root Optional root path to search from\n * @returns Array of matching file nodes\n */\n glob(pattern: string, root?: string): Promise<FileNode[]>;\n\n /**\n * Search file contents for a pattern\n * @param pattern Regex pattern to search for\n * @param options Search options\n * @returns Array of matches\n */\n grep(pattern: string, options?: GrepOptions): Promise<GrepMatch[]>;\n\n /**\n * Read file content\n * @param path Virtual path to the file\n * @returns File content in appropriate format\n */\n read(path: string): Promise<FileContent>;\n\n /**\n * Write content to a file\n * @param path Virtual path to the file\n * @param content Text content to write\n * @returns void\n * @optional - Providers may not support write operations\n */\n write?(path: string, content: string): Promise<void>;\n\n /**\n * Check if a file or directory exists\n * @param path Virtual path to check\n */\n exists(path: string): Promise<boolean>;\n}\n\n/**\n * Configuration for creating file system tools\n */\nexport interface FileSystemToolsConfig {\n /** The file system provider implementation */\n provider: FileSystemProvider;\n /** The scoped file nodes the agent can access */\n scopedNodes: FileNode[];\n}\n\n/**\n * Convert FileContent to LangChain MessageContent format\n */\nexport function fileContentToMessageContent(\n content: FileContent\n): ContentBlock[] {\n switch (content.type) {\n case \"text\":\n return [{ type: \"text\", text: content.content }];\n case \"image\":\n return [\n {\n type: \"image_url\",\n image_url: {\n url: `data:${content.mimeType};base64,${content.data}`,\n },\n },\n ];\n case \"pdf\":\n return [{ type: \"text\", text: content.content }];\n }\n}\n","import type { FileNode, FileTreeRenderOptions } from \"./types\";\nimport { minimatch } from \"minimatch\";\n\nconst DEFAULT_HEADER = \"Available files and directories:\";\nconst DEFAULT_DESCRIPTION =\n \"You have access to the following files. Use the Read, Glob, and Grep tools to explore them.\";\n\n/**\n * Check if a path matches any of the exclude patterns\n */\nfunction isExcluded(path: string, excludePatterns?: string[]): boolean {\n if (!excludePatterns || excludePatterns.length === 0) {\n return false;\n }\n return excludePatterns.some((pattern) => minimatch(path, pattern));\n}\n\n/**\n * Render a single node with proper indentation\n */\nfunction renderNode(\n node: FileNode,\n options: FileTreeRenderOptions,\n depth: number,\n indent: string\n): string[] {\n const lines: string[] = [];\n\n // Check depth limit\n if (options.maxDepth !== undefined && depth > options.maxDepth) {\n return lines;\n }\n\n // Check exclusion patterns\n if (isExcluded(node.path, options.excludePatterns)) {\n return lines;\n }\n\n // Get the filename from the path\n const parts = node.path.split(\"/\");\n const name = parts[parts.length - 1] || node.path;\n\n // Build the line\n let line = indent;\n\n if (node.type === \"directory\") {\n line += `${name}/`;\n } else {\n line += name;\n }\n\n // Add MIME type if requested\n if (options.showMimeTypes && node.mimeType) {\n line += ` [${node.mimeType}]`;\n }\n\n // Add description if present and enabled\n if (options.showDescriptions !== false && node.description) {\n line += ` - ${node.description}`;\n }\n\n lines.push(line);\n\n // Render children for directories\n if (node.type === \"directory\" && node.children) {\n const childIndent = indent + \" \";\n for (const child of node.children) {\n lines.push(...renderNode(child, options, depth + 1, childIndent));\n }\n }\n\n return lines;\n}\n\n/**\n * Build a text representation of the file tree for injection into the agent's prompt.\n *\n * @param nodes Array of root-level file nodes\n * @param options Rendering options\n * @returns Formatted file tree string wrapped in <file_system> tags\n *\n * @example\n * ```typescript\n * const tree = buildFileTreePrompt([\n * {\n * path: \"docs\",\n * type: \"directory\",\n * children: [\n * { path: \"docs/readme.md\", type: \"file\", description: \"Project docs\" }\n * ]\n * },\n * { path: \"src/index.ts\", type: \"file\", description: \"Entry point\" }\n * ], { maxDepth: 2 });\n *\n * // Output:\n * // <file_system>\n * // Available files and directories:\n * //\n * // docs/\n * // readme.md - Project docs\n * // src/index.ts - Entry point\n * // </file_system>\n * ```\n */\nexport function buildFileTreePrompt(\n nodes: FileNode[],\n options: FileTreeRenderOptions = {}\n): string {\n const header = options.headerText ?? DEFAULT_HEADER;\n const description = options.descriptionText ?? DEFAULT_DESCRIPTION;\n const lines: string[] = [];\n\n for (const node of nodes) {\n lines.push(...renderNode(node, options, 0, \"\"));\n }\n\n if (lines.length === 0) {\n return `<file_system>\\n${header}\\n\\n${description}\\n\\n(no files available)\\n</file_system>`;\n }\n\n return `<file_system>\\n${header}\\n\\n${lines.join(\"\\n\")}\\n</file_system>`;\n}\n\n/**\n * Flatten a file tree into a list of all file paths.\n * Useful for scope validation.\n *\n * @param nodes Array of file nodes\n * @returns Array of all file paths (files only, not directories)\n */\nexport function flattenFileTree(nodes: FileNode[]): string[] {\n const paths: string[] = [];\n\n function traverse(node: FileNode): void {\n if (node.type === \"file\") {\n paths.push(node.path);\n }\n if (node.children) {\n for (const child of node.children) {\n traverse(child);\n }\n }\n }\n\n for (const node of nodes) {\n traverse(node);\n }\n\n return paths;\n}\n\n/**\n * Check if a path is within the scoped file tree.\n *\n * @param path Path to check\n * @param scopedNodes The file nodes that define the allowed scope\n * @returns true if the path is within scope\n */\nexport function isPathInScope(path: string, scopedNodes: FileNode[]): boolean {\n const allowedPaths = flattenFileTree(scopedNodes);\n return allowedPaths.includes(path);\n}\n\n/**\n * Find a node by path in the file tree.\n *\n * @param path Path to find\n * @param nodes Array of file nodes to search\n * @returns The matching node or undefined\n */\nexport function findNodeByPath(\n path: string,\n nodes: FileNode[]\n): FileNode | undefined {\n for (const node of nodes) {\n if (node.path === path) {\n return node;\n }\n if (node.children) {\n const found = findNodeByPath(path, node.children);\n if (found) {\n return found;\n }\n }\n }\n return undefined;\n}\n","import { minimatch } from \"minimatch\";\nimport type {\n FileSystemProvider,\n FileNode,\n FileContent,\n GrepOptions,\n GrepMatch,\n} from \"../types\";\nimport { flattenFileTree } from \"../tree-builder\";\n\n/**\n * Abstract base class for filesystem providers.\n * Implements scope validation and common utilities.\n * Subclasses only need to implement the actual I/O operations.\n */\nexport abstract class BaseFileSystemProvider implements FileSystemProvider {\n protected scopedNodes: FileNode[];\n protected allowedPaths: Set<string>;\n\n constructor(scopedNodes: FileNode[]) {\n this.scopedNodes = scopedNodes;\n this.allowedPaths = new Set(flattenFileTree(scopedNodes));\n }\n\n /**\n * Validate that a path is within the allowed scope.\n * Throws an error if the path is not allowed.\n */\n protected validatePath(path: string): void {\n if (!this.allowedPaths.has(path)) {\n throw new Error(`Path \"${path}\" is not within the allowed scope`);\n }\n }\n\n /**\n * Filter paths by glob pattern.\n */\n protected filterByPattern(\n paths: string[],\n pattern: string,\n root?: string\n ): string[] {\n // Prepend root if provided\n const effectivePattern = root ? `${root}/${pattern}` : pattern;\n\n return paths.filter((path) => {\n // Also match if root is provided and path starts with root\n if (root && !path.startsWith(root)) {\n return false;\n }\n return minimatch(path, effectivePattern, { matchBase: true });\n });\n }\n\n /**\n * Get all file paths in scope\n */\n protected getAllPaths(): string[] {\n return Array.from(this.allowedPaths);\n }\n\n /**\n * Find FileNode by path\n */\n protected findNode(path: string): FileNode | undefined {\n const findInNodes = (nodes: FileNode[]): FileNode | undefined => {\n for (const node of nodes) {\n if (node.path === path) {\n return node;\n }\n if (node.children) {\n const found = findInNodes(node.children);\n if (found) return found;\n }\n }\n return undefined;\n };\n return findInNodes(this.scopedNodes);\n }\n\n // ============================================================================\n // Abstract methods - must be implemented by subclasses\n // ============================================================================\n\n /**\n * Read raw file content from the backend.\n * This is called after scope validation.\n */\n protected abstract readFile(node: FileNode): Promise<FileContent>;\n\n /**\n * Read file as text for grep operations.\n * Default implementation uses readFile, but can be overridden for efficiency.\n */\n protected async readFileAsText(node: FileNode): Promise<string | null> {\n try {\n const content = await this.readFile(node);\n if (content.type === \"text\") {\n return content.content;\n }\n if (content.type === \"pdf\") {\n return content.content;\n }\n // Binary files can't be grepped\n return null;\n } catch {\n return null;\n }\n }\n\n // ============================================================================\n // FileSystemProvider implementation\n // ============================================================================\n\n async glob(pattern: string, root?: string): Promise<FileNode[]> {\n const allPaths = this.getAllPaths();\n const matchingPaths = this.filterByPattern(allPaths, pattern, root);\n\n return matchingPaths\n .map((path) => this.findNode(path))\n .filter((node): node is FileNode => node !== undefined);\n }\n\n async grep(pattern: string, options?: GrepOptions): Promise<GrepMatch[]> {\n const matches: GrepMatch[] = [];\n const maxMatches = options?.maxMatches ?? 50;\n\n // Build regex\n const flags = options?.ignoreCase ? \"gi\" : \"g\";\n let regex: RegExp;\n try {\n regex = new RegExp(pattern, flags);\n } catch {\n throw new Error(`Invalid regex pattern: ${pattern}`);\n }\n\n // Get files to search\n let paths = this.getAllPaths();\n\n // Apply include patterns\n if (options?.includePatterns?.length) {\n const includePatterns = options.includePatterns;\n paths = paths.filter((path) =>\n includePatterns.some((p) => minimatch(path, p, { matchBase: true }))\n );\n }\n\n // Apply exclude patterns\n if (options?.excludePatterns?.length) {\n const excludePatterns = options.excludePatterns;\n paths = paths.filter(\n (path) =>\n !excludePatterns.some((p) => minimatch(path, p, { matchBase: true }))\n );\n }\n\n // Search each file\n for (const path of paths) {\n if (matches.length >= maxMatches) break;\n\n const node = this.findNode(path);\n if (!node || node.type !== \"file\") continue;\n\n const text = await this.readFileAsText(node);\n if (!text) continue;\n\n const lines = text.split(\"\\n\");\n\n for (let i = 0; i < lines.length; i++) {\n if (matches.length >= maxMatches) break;\n\n const line = lines[i];\n if (line === undefined) continue;\n\n if (regex.test(line)) {\n // Reset regex lastIndex for global flag\n regex.lastIndex = 0;\n\n const match: GrepMatch = {\n path,\n lineNumber: i + 1,\n line: line.trim(),\n };\n\n // Add context lines if requested\n if (options?.contextLines && options.contextLines > 0) {\n const contextBefore: string[] = [];\n const contextAfter: string[] = [];\n\n for (let j = Math.max(0, i - options.contextLines); j < i; j++) {\n const contextLine = lines[j];\n if (contextLine !== undefined) {\n contextBefore.push(contextLine.trim());\n }\n }\n\n for (\n let j = i + 1;\n j <= Math.min(lines.length - 1, i + options.contextLines);\n j++\n ) {\n const contextLine = lines[j];\n if (contextLine !== undefined) {\n contextAfter.push(contextLine.trim());\n }\n }\n\n match.contextBefore = contextBefore;\n match.contextAfter = contextAfter;\n }\n\n matches.push(match);\n }\n }\n }\n\n return matches;\n }\n\n async read(path: string): Promise<FileContent> {\n this.validatePath(path);\n\n const node = this.findNode(path);\n if (!node) {\n throw new Error(`File not found: ${path}`);\n }\n\n if (node.type !== \"file\") {\n throw new Error(`Path is a directory, not a file: ${path}`);\n }\n\n return this.readFile(node);\n }\n\n async exists(path: string): Promise<boolean> {\n return this.allowedPaths.has(path);\n }\n}\n\n/**\n * A simple in-memory filesystem provider for testing.\n * Files are stored as a map of path -> content.\n */\nexport class InMemoryFileSystemProvider extends BaseFileSystemProvider {\n private files: Map<string, FileContent>;\n\n constructor(scopedNodes: FileNode[], files: Map<string, FileContent>) {\n super(scopedNodes);\n this.files = files;\n }\n\n protected async readFile(node: FileNode): Promise<FileContent> {\n const content = this.files.get(node.path);\n if (!content) {\n throw new Error(`File not found in storage: ${node.path}`);\n }\n return content;\n }\n\n /**\n * Add or update a file in the in-memory storage\n */\n setFile(path: string, content: FileContent): void {\n this.files.set(path, content);\n }\n\n /**\n * Write text content to a file\n */\n async write(path: string, content: string): Promise<void> {\n this.validatePath(path);\n this.files.set(path, { type: \"text\", content });\n }\n\n /**\n * Create an InMemoryFileSystemProvider from a simple object map\n */\n static fromTextFiles(\n scopedNodes: FileNode[],\n files: Record<string, string>\n ): InMemoryFileSystemProvider {\n const fileMap = new Map<string, FileContent>();\n for (const [path, content] of Object.entries(files)) {\n fileMap.set(path, { type: \"text\", content });\n }\n return new InMemoryFileSystemProvider(scopedNodes, fileMap);\n }\n}\n\n/**\n * A resolver function that reads file content given a FileNode.\n * Use this for simple cases where you just need to provide a read function.\n */\nexport type FileResolver = (node: FileNode) => Promise<FileContent>;\n\n/**\n * Configuration for a backend in the CompositeFileSystemProvider\n */\nexport interface BackendConfig {\n /** The resolver function or provider for this backend */\n resolver: FileResolver | FileSystemProvider;\n}\n\n/**\n * A composite filesystem provider that routes to different backends based on file metadata.\n *\n * Files are routed based on `node.metadata.backend` field. If no backend is specified,\n * the default backend is used.\n *\n * @example\n * ```typescript\n * const files: FileNode[] = [\n * { path: \"invoices/2024.pdf\", type: \"file\", metadata: { backend: \"s3\", s3Key: \"...\" } },\n * { path: \"cache/summary.txt\", type: \"file\", metadata: { backend: \"redis\" } },\n * { path: \"local/config.json\", type: \"file\" }, // uses default backend\n * ];\n *\n * const provider = new CompositeFileSystemProvider(files, {\n * backends: {\n * s3: { resolver: async (node) => s3Client.getObject(node.metadata.s3Key) },\n * redis: { resolver: async (node) => redis.get(node.path) },\n * },\n * defaultBackend: \"local\",\n * defaultResolver: async (node) => fs.readFile(node.path),\n * });\n * ```\n */\nexport class CompositeFileSystemProvider extends BaseFileSystemProvider {\n private backends: Map<string, BackendConfig>;\n private defaultBackend?: string;\n private defaultResolver?: FileResolver;\n\n constructor(\n scopedNodes: FileNode[],\n config: {\n /** Map of backend name to configuration */\n backends: Record<string, BackendConfig>;\n /** Default backend name for files without metadata.backend */\n defaultBackend?: string;\n /** Fallback resolver if no backend matches (alternative to defaultBackend) */\n defaultResolver?: FileResolver;\n }\n ) {\n super(scopedNodes);\n this.backends = new Map(Object.entries(config.backends));\n this.defaultBackend = config.defaultBackend;\n this.defaultResolver = config.defaultResolver;\n }\n\n /**\n * Get the backend name for a file node\n */\n private getBackendName(node: FileNode): string | undefined {\n const backend = node.metadata?.backend;\n if (typeof backend === \"string\") {\n return backend;\n }\n return this.defaultBackend;\n }\n\n /**\n * Resolve content using a resolver (function or provider)\n */\n private async resolveContent(\n resolver: FileResolver | FileSystemProvider,\n node: FileNode\n ): Promise<FileContent> {\n if (typeof resolver === \"function\") {\n return resolver(node);\n }\n // It's a FileSystemProvider\n return resolver.read(node.path);\n }\n\n protected async readFile(node: FileNode): Promise<FileContent> {\n const backendName = this.getBackendName(node);\n\n // Try named backend\n if (backendName) {\n const config = this.backends.get(backendName);\n if (config) {\n return this.resolveContent(config.resolver, node);\n }\n }\n\n // Try default resolver\n if (this.defaultResolver) {\n return this.defaultResolver(node);\n }\n\n // No resolver found\n const availableBackends = Array.from(this.backends.keys()).join(\", \");\n throw new Error(\n `No resolver for file \"${node.path}\". ` +\n `Backend: ${backendName ?? \"(none)\"}. ` +\n `Available backends: ${availableBackends || \"(none)\"}`\n );\n }\n\n /**\n * Add or update a backend configuration\n */\n setBackend(name: string, config: BackendConfig): void {\n this.backends.set(name, config);\n }\n\n /**\n * Remove a backend\n */\n removeBackend(name: string): boolean {\n return this.backends.delete(name);\n }\n\n /**\n * Check if a backend exists\n */\n hasBackend(name: string): boolean {\n return this.backends.has(name);\n }\n}\n","import validate from './validate.js';\n\n/**\n * Convert array of 16 byte values to UUID string format of the form:\n * XXXXXXXX-XXXX-XXXX-XXXX-XXXXXXXXXXXX\n */\nconst byteToHex = [];\nfor (let i = 0; i < 256; ++i) {\n byteToHex.push((i + 0x100).toString(16).slice(1));\n}\nexport function unsafeStringify(arr, offset = 0) {\n // Note: Be careful editing this code! It's been tuned for performance\n // and works in ways you may not expect. See https://github.com/uuidjs/uuid/pull/434\n //\n // Note to future-self: No, you can't remove the `toLowerCase()` call.\n // REF: https://github.com/uuidjs/uuid/pull/677#issuecomment-1757351351\n return (byteToHex[arr[offset + 0]] + byteToHex[arr[offset + 1]] + byteToHex[arr[offset + 2]] + byteToHex[arr[offset + 3]] + '-' + byteToHex[arr[offset + 4]] + byteToHex[arr[offset + 5]] + '-' + byteToHex[arr[offset + 6]] + byteToHex[arr[offset + 7]] + '-' + byteToHex[arr[offset + 8]] + byteToHex[arr[offset + 9]] + '-' + byteToHex[arr[offset + 10]] + byteToHex[arr[offset + 11]] + byteToHex[arr[offset + 12]] + byteToHex[arr[offset + 13]] + byteToHex[arr[offset + 14]] + byteToHex[arr[offset + 15]]).toLowerCase();\n}\nfunction stringify(arr, offset = 0) {\n const uuid = unsafeStringify(arr, offset);\n // Consistency check for valid UUID. If this throws, it's likely due to one\n // of the following:\n // - One or more input array values don't map to a hex octet (leading to\n // \"undefined\" in the uuid)\n // - Invalid input values for the RFC `version` or `variant` fields\n if (!validate(uuid)) {\n throw TypeError('Stringified UUID is invalid');\n }\n return uuid;\n}\nexport default stringify;","import crypto from 'node:crypto';\nconst rnds8Pool = new Uint8Array(256); // # of random values to pre-allocate\nlet poolPtr = rnds8Pool.length;\nexport default function rng() {\n if (poolPtr > rnds8Pool.length - 16) {\n crypto.randomFillSync(rnds8Pool);\n poolPtr = 0;\n }\n return rnds8Pool.slice(poolPtr, poolPtr += 16);\n}","import crypto from 'node:crypto';\nexport default {\n randomUUID: crypto.randomUUID\n};","import native from './native.js';\nimport rng from './rng.js';\nimport { unsafeStringify } from './stringify.js';\nfunction v4(options, buf, offset) {\n if (native.randomUUID && !buf && !options) {\n return native.randomUUID();\n }\n options = options || {};\n const rnds = options.random || (options.rng || rng)();\n\n // Per 4.4, set bits for version and `clock_seq_hi_and_reserved`\n rnds[6] = rnds[6] & 0x0f | 0x40;\n rnds[8] = rnds[8] & 0x3f | 0x80;\n\n // Copy bytes to buffer, if provided\n if (buf) {\n offset = offset || 0;\n for (let i = 0; i < 16; ++i) {\n buf[offset + i] = rnds[i];\n }\n return buf;\n }\n return unsafeStringify(rnds);\n}\nexport default v4;","import type Redis from \"ioredis\";\n\nimport {\n type $InferMessageContent,\n AIMessage,\n HumanMessage,\n type MessageContent,\n type MessageStructure,\n type StoredMessage,\n ToolMessage,\n} from \"@langchain/core/messages\";\nimport { v4 as uuidv4 } from \"uuid\";\n\nconst THREAD_TTL_SECONDS = 60 * 60 * 24 * 90; // 90 days\n\nfunction getThreadKey(threadId: string, key: string): string {\n return `thread:${threadId}:${key}`;\n}\n\n/**\n * Content for a tool message response.\n * Can be a simple string or complex content parts (text, images, cache points, etc.)\n */\nexport type ToolMessageContent = $InferMessageContent<MessageStructure, \"tool\">;\n\nexport interface ThreadManagerConfig {\n redis: Redis;\n threadId: string;\n /** Thread key, defaults to 'messages' */\n key?: string;\n}\n\nexport interface ThreadManager {\n /** Initialize an empty thread */\n initialize(): Promise<void>;\n /** Load all messages from the thread */\n load(): Promise<StoredMessage[]>;\n /** Append messages to the thread */\n append(messages: StoredMessage[]): Promise<void>;\n /** Delete the thread */\n delete(): Promise<void>;\n\n /** Create a HumanMessage (returns StoredMessage for storage) */\n createHumanMessage(content: string | MessageContent): StoredMessage;\n\n /** Create an AIMessage with optional additional kwargs */\n createAIMessage(\n content: string | MessageContent,\n kwargs?: { header?: string; options?: string[]; multiSelect?: boolean }\n ): StoredMessage;\n\n /** Create a ToolMessage */\n createToolMessage(\n content: ToolMessageContent,\n toolCallId: string\n ): StoredMessage;\n\n /** Create and append a HumanMessage */\n appendHumanMessage(content: string | MessageContent): Promise<void>;\n /** Create and append a ToolMessage */\n appendToolMessage(\n content: ToolMessageContent,\n toolCallId: string\n ): Promise<void>;\n /** Create and append an AIMessage */\n appendAIMessage(content: string | MessageContent): Promise<void>;\n}\n\n/**\n * Creates a thread manager for handling conversation state in Redis.\n */\nexport function createThreadManager(\n config: ThreadManagerConfig\n): ThreadManager {\n const { redis, threadId, key = \"messages\" } = config;\n const redisKey = getThreadKey(threadId, key);\n\n return {\n async initialize(): Promise<void> {\n await redis.del(redisKey);\n },\n\n async load(): Promise<StoredMessage[]> {\n const data = await redis.lrange(redisKey, 0, -1);\n return data.map((item) => JSON.parse(item) as StoredMessage);\n },\n\n async append(messages: StoredMessage[]): Promise<void> {\n if (messages.length > 0) {\n await redis.rpush(redisKey, ...messages.map((m) => JSON.stringify(m)));\n await redis.expire(redisKey, THREAD_TTL_SECONDS);\n }\n },\n\n async delete(): Promise<void> {\n await redis.del(redisKey);\n },\n\n createHumanMessage(content: string | MessageContent): StoredMessage {\n return new HumanMessage({\n id: uuidv4(),\n content: content as string,\n }).toDict();\n },\n\n createAIMessage(\n content: string,\n kwargs?: { header?: string; options?: string[]; multiSelect?: boolean }\n ): StoredMessage {\n return new AIMessage({\n id: uuidv4(),\n content,\n additional_kwargs: kwargs\n ? {\n header: kwargs.header,\n options: kwargs.options,\n multiSelect: kwargs.multiSelect,\n }\n : undefined,\n }).toDict();\n },\n\n createToolMessage(\n content: ToolMessageContent,\n toolCallId: string\n ): StoredMessage {\n return new ToolMessage({\n // Cast needed due to langchain type compatibility\n content: content as MessageContent,\n tool_call_id: toolCallId,\n }).toDict();\n },\n\n async appendHumanMessage(content: string | MessageContent): Promise<void> {\n const message = this.createHumanMessage(content);\n await this.append([message]);\n },\n\n async appendToolMessage(\n content: ToolMessageContent,\n toolCallId: string\n ): Promise<void> {\n const message = this.createToolMessage(content, toolCallId);\n await this.append([message]);\n },\n\n async appendAIMessage(content: string | MessageContent): Promise<void> {\n const message = this.createAIMessage(content);\n await this.append([message]);\n },\n };\n}\n","import type Redis from \"ioredis\";\nimport { createThreadManager } from \"./lib/thread-manager\";\nimport type { ToolResultConfig } from \"./lib/types\";\nimport {\n type AIMessage,\n mapStoredMessageToChatMessage,\n type MessageContent,\n type StoredMessage,\n} from \"@langchain/core/messages\";\nimport type { RawToolCall } from \"./lib/tool-registry\";\n\n/**\n * Shared Zeitlich activities - thread management and message handling\n * Note: runAgent is workflow-specific and should be created per-workflow\n */\nexport interface ZeitlichSharedActivities {\n /**\n * Append a tool result to the thread.\n * Handles JSON serialization and optional cache points.\n */\n appendToolResult(config: ToolResultConfig): Promise<void>;\n\n /**\n * Initialize an empty thread.\n */\n initializeThread(threadId: string): Promise<void>;\n\n /**\n * Append messages to a thread.\n */\n appendThreadMessages(\n threadId: string,\n messages: StoredMessage[]\n ): Promise<void>;\n\n /**\n * Append a human message to a thread.\n */\n appendHumanMessage(\n threadId: string,\n content: string | MessageContent\n ): Promise<void>;\n\n /**\n * Extract raw tool calls from a stored message.\n * Returns unvalidated tool calls - use toolRegistry.parseToolCall() to validate.\n */\n parseToolCalls(storedMessage: StoredMessage): Promise<RawToolCall[]>;\n}\n\n/**\n * Creates shared Temporal activities for thread management\n *\n * @returns An object containing the shared activity functions\n *\n * @experimental The Zeitlich integration is an experimental feature; APIs may change without notice.\n */\nexport function createSharedActivities(redis: Redis): ZeitlichSharedActivities {\n return {\n async appendToolResult(config: ToolResultConfig): Promise<void> {\n const { threadId, toolCallId, content } = config;\n const thread = createThreadManager({ redis, threadId });\n\n await thread.appendToolMessage(content, toolCallId);\n },\n\n async initializeThread(threadId: string): Promise<void> {\n const thread = createThreadManager({ redis, threadId });\n await thread.initialize();\n },\n\n async appendThreadMessages(\n threadId: string,\n messages: StoredMessage[]\n ): Promise<void> {\n const thread = createThreadManager({ redis, threadId });\n await thread.append(messages);\n },\n\n async appendHumanMessage(\n threadId: string,\n content: string | MessageContent\n ): Promise<void> {\n const thread = createThreadManager({ redis, threadId });\n await thread.appendHumanMessage(content);\n },\n\n async parseToolCalls(storedMessage: StoredMessage): Promise<RawToolCall[]> {\n const message = mapStoredMessageToChatMessage(storedMessage) as AIMessage;\n const toolCalls = message.tool_calls ?? [];\n\n return toolCalls.map((toolCall) => ({\n id: toolCall.id,\n name: toolCall.name,\n args: toolCall.args,\n }));\n },\n };\n}\n","import { SimplePlugin } from \"@temporalio/plugin\";\nimport { createSharedActivities } from \"./activities\";\nimport type Redis from \"ioredis\";\n\n/**\n * Options for the Zeitlich plugin\n *\n * @experimental The Zeitlich plugin is an experimental feature; APIs may change without notice.\n */\nexport interface ZeitlichPluginOptions {\n redis: Redis;\n}\n\n/**\n * A Temporal plugin that integrates Zeitlich for use in workflows.\n * This plugin creates shared activities for thread management.\n * Workflow-specific activities (like runAgent) should be created separately.\n *\n * @experimental The Zeitlich plugin is an experimental feature; APIs may change without notice.\n */\nexport class ZeitlichPlugin extends SimplePlugin {\n constructor(options: ZeitlichPluginOptions) {\n super({\n name: \"ZeitlichPlugin\",\n activities: createSharedActivities(options.redis),\n });\n }\n}\n","import type Redis from \"ioredis\";\nimport { createThreadManager } from \"./thread-manager\";\nimport type { AgentResponse, InvocationConfig } from \"./types\";\nimport type { ToolDefinition } from \"./tool-registry\";\nimport {\n mapStoredMessagesToChatMessages,\n SystemMessage,\n} from \"@langchain/core/messages\";\nimport { v4 as uuidv4 } from \"uuid\";\nimport type {\n BaseChatModel,\n BaseChatModelCallOptions,\n BindToolsInput,\n} from \"@langchain/core/language_models/chat_models\";\n\n/**\n * Configuration for invoking the model\n */\nexport interface InvokeModelConfig {\n threadId: string;\n agentName: string;\n tools: ToolDefinition[];\n}\n\n/**\n * Core model invocation logic - shared utility for workflow-specific activities\n *\n * @param redis - Redis client for thread management\n * @param config - Model invocation configuration\n * @param model - Pre-instantiated LangChain chat model\n * @param invocationConfig - Per-invocation configuration (system prompt, etc.)\n * @returns Agent response with message and metadata\n */\nexport async function invokeModel(\n redis: Redis,\n { threadId, agentName, tools }: InvokeModelConfig,\n model: BaseChatModel<BaseChatModelCallOptions & { tools?: BindToolsInput }>,\n { systemPrompt }: InvocationConfig\n): Promise<AgentResponse> {\n const thread = createThreadManager({ redis, threadId });\n const runId = uuidv4();\n\n const messages = await thread.load();\n const response = await model.invoke(\n [\n new SystemMessage(systemPrompt),\n ...mapStoredMessagesToChatMessages(messages),\n ],\n {\n runName: agentName,\n runId,\n metadata: { thread_id: threadId },\n tools,\n }\n );\n\n await thread.append([response.toDict()]);\n\n return {\n message: response.toDict(),\n stopReason: (response.response_metadata?.stop_reason as string) ?? null,\n usage: {\n input_tokens: response.usage_metadata?.input_tokens,\n output_tokens: response.usage_metadata?.output_tokens,\n total_tokens: response.usage_metadata?.total_tokens,\n },\n };\n}\n","import { AIMessage, type StoredMessage } from \"@langchain/core/messages\";\nimport type { ActivityToolHandler } from \"../../lib/tool-router\";\nimport type { AskUserQuestionToolSchemaType } from \"./tool\";\n\n/**\n * Handle user interaction tool result - creates AI messages for display.\n */\nexport const handleAskUserQuestionToolResult: ActivityToolHandler<\n AskUserQuestionToolSchemaType,\n { chatMessages: StoredMessage[] }\n> = async (args) => {\n const messages = args.questions.map(\n ({ question, header, options, multiSelect }) =>\n new AIMessage({\n content: question,\n additional_kwargs: {\n header,\n options,\n multiSelect,\n },\n }).toDict()\n );\n\n return { content: \"Question submitted\", result: { chatMessages: messages } };\n};\n","import type { FileSystemProvider, FileNode } from \"../../lib/filesystem/types\";\nimport type { GlobToolSchemaType } from \"./tool\";\n\nexport interface GlobHandlerConfig {\n provider: FileSystemProvider;\n scopedNodes: FileNode[];\n}\n\n/**\n * Create a glob handler that searches within the scoped file tree.\n */\nexport function createGlobHandler(config: GlobHandlerConfig) {\n return async (\n args: GlobToolSchemaType\n ): Promise<{ content: string; result: { files: FileNode[] } }> => {\n const { pattern, root } = args;\n\n try {\n const matches = await config.provider.glob(pattern, root);\n\n if (matches.length === 0) {\n return {\n content: `No files found matching pattern: ${pattern}`,\n result: { files: [] },\n };\n }\n\n const paths = matches.map((node) => node.path);\n const fileList = paths.map((p) => ` ${p}`).join(\"\\n\");\n\n return {\n content: `Found ${matches.length} file(s) matching \"${pattern}\":\\n${fileList}`,\n result: { files: matches },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return {\n content: `Error searching for files: ${message}`,\n result: { files: [] },\n };\n }\n };\n}\n","import type {\n FileSystemProvider,\n FileNode,\n GrepMatch,\n} from \"../../lib/filesystem/types\";\nimport type { GrepToolSchemaType } from \"./tool\";\n\nexport interface GrepHandlerConfig {\n provider: FileSystemProvider;\n scopedNodes: FileNode[];\n}\n\n/**\n * Format a single grep match for display\n */\nfunction formatMatch(match: GrepMatch, showContext: boolean): string {\n const lines: string[] = [];\n\n if (showContext && match.contextBefore?.length) {\n for (let i = 0; i < match.contextBefore.length; i++) {\n const lineNum = match.lineNumber - match.contextBefore.length + i;\n lines.push(`${match.path}:${lineNum}-${match.contextBefore[i]}`);\n }\n }\n\n lines.push(`${match.path}:${match.lineNumber}:${match.line}`);\n\n if (showContext && match.contextAfter?.length) {\n for (let i = 0; i < match.contextAfter.length; i++) {\n const lineNum = match.lineNumber + 1 + i;\n lines.push(`${match.path}:${lineNum}-${match.contextAfter[i]}`);\n }\n }\n\n return lines.join(\"\\n\");\n}\n\n/**\n * Create a grep handler that searches within the scoped file tree.\n */\nexport function createGrepHandler(config: GrepHandlerConfig) {\n return async (\n args: GrepToolSchemaType\n ): Promise<{ content: string; result: { matches: GrepMatch[] } }> => {\n const {\n pattern,\n ignoreCase,\n maxMatches,\n includePatterns,\n excludePatterns,\n contextLines,\n } = args;\n\n try {\n const matches = await config.provider.grep(pattern, {\n ignoreCase,\n maxMatches: maxMatches ?? 50,\n includePatterns,\n excludePatterns,\n contextLines,\n });\n\n if (matches.length === 0) {\n return {\n content: `No matches found for pattern: ${pattern}`,\n result: { matches: [] },\n };\n }\n\n const showContext = contextLines !== undefined && contextLines > 0;\n const formattedMatches = matches\n .map((m) => formatMatch(m, showContext))\n .join(\"\\n\");\n\n return {\n content: `Found ${matches.length} match(es) for \"${pattern}\":\\n\\n${formattedMatches}`,\n result: { matches },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return {\n content: `Error searching file contents: ${message}`,\n result: { matches: [] },\n };\n }\n };\n}\n","import type { ContentBlock } from \"@langchain/core/messages\";\nimport type {\n FileSystemProvider,\n FileNode,\n FileContent,\n} from \"../../lib/filesystem/types\";\nimport { fileContentToMessageContent } from \"../../lib/filesystem/types\";\nimport { isPathInScope } from \"../../lib/filesystem/tree-builder\";\nimport type { ReadToolSchemaType } from \"./tool\";\n\nexport interface ReadHandlerConfig {\n provider: FileSystemProvider;\n scopedNodes: FileNode[];\n}\n\n/**\n * Apply offset and limit to text content\n */\nfunction applyTextRange(\n content: string,\n offset?: number,\n limit?: number\n): string {\n if (offset === undefined && limit === undefined) {\n return content;\n }\n\n const lines = content.split(\"\\n\");\n const startLine = offset !== undefined ? Math.max(0, offset - 1) : 0;\n const endLine = limit !== undefined ? startLine + limit : lines.length;\n\n const selectedLines = lines.slice(startLine, endLine);\n\n // Format with line numbers\n return selectedLines\n .map((line, i) => {\n const lineNum = (startLine + i + 1).toString().padStart(6, \" \");\n return `${lineNum}|${line}`;\n })\n .join(\"\\n\");\n}\n\n/**\n * Create a read handler that reads files within the scoped file tree.\n */\nexport function createReadHandler(config: ReadHandlerConfig) {\n return async (\n args: ReadToolSchemaType\n ): Promise<{\n content: ContentBlock[];\n result: { path: string; content: FileContent };\n }> => {\n const { path, offset, limit } = args;\n\n // Validate path is in scope\n if (!isPathInScope(path, config.scopedNodes)) {\n return {\n content: [\n {\n type: \"text\",\n text: `Error: Path \"${path}\" is not within the available file system scope.`,\n },\n ],\n result: {\n path,\n content: {\n type: \"text\",\n content:\n \"Error: Path is not within the available file system scope.\",\n },\n },\n };\n }\n\n try {\n // Check if file exists\n const exists = await config.provider.exists(path);\n if (!exists) {\n return {\n content: [\n {\n type: \"text\",\n text: `Error: File \"${path}\" does not exist.`,\n },\n ],\n result: {\n path,\n content: { type: \"text\", content: \"Error: File does not exist.\" },\n },\n };\n }\n\n const fileContent: FileContent = await config.provider.read(path);\n\n // Handle text content with offset/limit\n if (fileContent.type === \"text\") {\n const processedContent = applyTextRange(\n fileContent.content,\n offset,\n limit\n );\n\n let header = `File: ${path}`;\n if (offset !== undefined || limit !== undefined) {\n const startLine = offset ?? 1;\n const endInfo = limit ? `, showing ${limit} lines` : \"\";\n header += ` (from line ${startLine}${endInfo})`;\n }\n\n return {\n content: [\n {\n type: \"text\",\n text: `${header}\\n\\n${processedContent}`,\n },\n ],\n result: {\n path,\n content: {\n type: \"text\",\n content: `${header}\\n\\n${processedContent}`,\n },\n },\n };\n }\n\n // For non-text content, return as multimodal\n const messageContent = fileContentToMessageContent(fileContent);\n\n return {\n content: [\n {\n type: \"text\",\n text: `File: ${path} (${fileContent.type})`,\n },\n ...messageContent,\n ],\n result: { path, content: fileContent },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return {\n content: [\n {\n type: \"text\",\n text: `Error reading file \"${path}\": ${message}`,\n },\n ],\n result: {\n path,\n content: {\n type: \"text\",\n content: `Error reading file \"${path}\": ${message}`,\n },\n },\n };\n }\n };\n}\n","import type { FileSystemProvider, FileNode } from \"../../lib/filesystem/types\";\nimport { isPathInScope } from \"../../lib/filesystem/tree-builder\";\nimport type { WriteToolSchemaType } from \"./tool\";\n\nexport interface WriteHandlerConfig {\n provider: FileSystemProvider;\n scopedNodes: FileNode[];\n /**\n * Set of file paths that have been read in this session.\n * Required for enforcing read-before-write policy.\n */\n readFiles: Set<string>;\n /**\n * If true, skip the read-before-write check (not recommended)\n */\n skipReadCheck?: boolean;\n}\n\nexport interface WriteResult {\n path: string;\n success: boolean;\n created: boolean;\n bytesWritten: number;\n}\n\n/**\n * Create a write handler that writes files within the scoped file tree.\n */\nexport function createWriteHandler(config: WriteHandlerConfig) {\n return async (\n args: WriteToolSchemaType\n ): Promise<{ content: string; result: WriteResult }> => {\n const { file_path, content } = args;\n\n // Validate path is in scope\n if (!isPathInScope(file_path, config.scopedNodes)) {\n return {\n content: `Error: Path \"${file_path}\" is not within the available file system scope.`,\n result: {\n path: file_path,\n success: false,\n created: false,\n bytesWritten: 0,\n },\n };\n }\n\n // Check read-before-write requirement\n if (!config.skipReadCheck && !config.readFiles.has(file_path)) {\n // Check if file exists - new files don't need to be read first\n const exists = await config.provider.exists(file_path);\n if (exists) {\n return {\n content: `Error: You must read \"${file_path}\" before writing to it. Use FileRead first.`,\n result: {\n path: file_path,\n success: false,\n created: false,\n bytesWritten: 0,\n },\n };\n }\n }\n\n try {\n const exists = await config.provider.exists(file_path);\n\n // Check if provider supports write\n if (!config.provider.write) {\n return {\n content: `Error: The file system provider does not support write operations.`,\n result: {\n path: file_path,\n success: false,\n created: false,\n bytesWritten: 0,\n },\n };\n }\n\n await config.provider.write(file_path, content);\n\n const bytesWritten = Buffer.byteLength(content, \"utf-8\");\n const action = exists ? \"Updated\" : \"Created\";\n\n return {\n content: `${action} file: ${file_path} (${bytesWritten} bytes)`,\n result: {\n path: file_path,\n success: true,\n created: !exists,\n bytesWritten,\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return {\n content: `Error writing file \"${file_path}\": ${message}`,\n result: {\n path: file_path,\n success: false,\n created: false,\n bytesWritten: 0,\n },\n };\n }\n };\n}\n","import type { FileSystemProvider, FileNode } from \"../../lib/filesystem/types\";\nimport { isPathInScope } from \"../../lib/filesystem/tree-builder\";\nimport type { EditToolSchemaType } from \"./tool\";\n\nexport interface EditHandlerConfig {\n provider: FileSystemProvider;\n scopedNodes: FileNode[];\n /**\n * Set of file paths that have been read in this session.\n * Required for enforcing read-before-write policy.\n */\n readFiles: Set<string>;\n /**\n * If true, skip the read-before-write check (not recommended)\n */\n skipReadCheck?: boolean;\n}\n\nexport interface EditResult {\n path: string;\n success: boolean;\n replacements: number;\n}\n\n/**\n * Escape special regex characters in a string\n */\nfunction escapeRegExp(str: string): string {\n return str.replace(/[.*+?^${}()|[\\]\\\\]/g, \"\\\\$&\");\n}\n\n/**\n * Create an edit handler that edits files within the scoped file tree.\n */\nexport function createEditHandler(config: EditHandlerConfig) {\n return async (\n args: EditToolSchemaType\n ): Promise<{ content: string; result: EditResult }> => {\n const { file_path, old_string, new_string, replace_all = false } = args;\n\n // Validate old_string !== new_string\n if (old_string === new_string) {\n return {\n content: `Error: old_string and new_string must be different.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Validate path is in scope\n if (!isPathInScope(file_path, config.scopedNodes)) {\n return {\n content: `Error: Path \"${file_path}\" is not within the available file system scope.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Check read-before-write requirement\n if (!config.skipReadCheck && !config.readFiles.has(file_path)) {\n return {\n content: `Error: You must read \"${file_path}\" before editing it. Use FileRead first.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n try {\n // Check if file exists\n const exists = await config.provider.exists(file_path);\n if (!exists) {\n return {\n content: `Error: File \"${file_path}\" does not exist.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Check if provider supports write\n if (!config.provider.write) {\n return {\n content: `Error: The file system provider does not support write operations.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Read current content\n const fileContent = await config.provider.read(file_path);\n if (fileContent.type !== \"text\") {\n return {\n content: `Error: FileEdit only works with text files. \"${file_path}\" is ${fileContent.type}.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n const content = fileContent.content;\n\n // Check if old_string exists in the file\n if (!content.includes(old_string)) {\n return {\n content: `Error: Could not find the specified text in \"${file_path}\". Make sure old_string matches exactly (whitespace-sensitive).`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Count occurrences\n const escapedOldString = escapeRegExp(old_string);\n const globalRegex = new RegExp(escapedOldString, \"g\");\n const occurrences = (content.match(globalRegex) || []).length;\n\n // Check uniqueness if not replace_all\n if (!replace_all && occurrences > 1) {\n return {\n content: `Error: old_string appears ${occurrences} times in \"${file_path}\". Either provide more context to make it unique, or use replace_all: true.`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n\n // Perform replacement\n let newContent: string;\n let replacements: number;\n\n if (replace_all) {\n newContent = content.split(old_string).join(new_string);\n replacements = occurrences;\n } else {\n // Replace only the first occurrence\n const index = content.indexOf(old_string);\n newContent =\n content.slice(0, index) +\n new_string +\n content.slice(index + old_string.length);\n replacements = 1;\n }\n\n // Write the modified content\n await config.provider.write(file_path, newContent);\n\n const summary = replace_all\n ? `Replaced ${replacements} occurrence(s)`\n : `Replaced 1 occurrence`;\n\n return {\n content: `${summary} in ${file_path}`,\n result: {\n path: file_path,\n success: true,\n replacements,\n },\n };\n } catch (error) {\n const message = error instanceof Error ? error.message : \"Unknown error\";\n return {\n content: `Error editing file \"${file_path}\": ${message}`,\n result: {\n path: file_path,\n success: false,\n replacements: 0,\n },\n };\n }\n };\n}\n"]}
|