@threaded/ai 1.0.1 → 1.0.3

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.
@@ -1 +1 @@
1
- {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/mcp.ts","../src/types.ts","../src/utils.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts"],"sourcesContent":["export * from \"./mcp\";\nexport * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./thread\";\nexport * from \"./schema\";\nexport * from \"./helpers\";\nexport * from \"./approval\";\nexport * from \"./composition/tap\";\nexport * from \"./composition/when\";\nexport * from \"./composition/model\";\nexport * from \"./composition/retry\";\nexport * from \"./composition/scope\";\nexport * from \"./composition/compose\";\n","import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n // check if zod is available and has toJSONSchema method\n try {\n const zodModule = require(\"zod\");\n if (zodModule && typeof zodModule.toJSONSchema === \"function\") {\n const jsonSchema = zodModule.toJSONSchema(standardSchema);\n return {\n name,\n schema: jsonSchema,\n };\n }\n } catch (error) {\n // zod not available or doesn't have toJSONSchema\n }\n\n throw new Error(\n \"Standard Schema conversion requires zod v4+ with toJSONSchema support. \" +\n \"Please install zod@^4.0.0 or provide a JsonSchema object instead.\",\n );\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty>;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n requireApproval?: boolean;\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n parallel?: boolean;\n retryCount?: number;\n approvalId?: string;\n}\n\nexport type StreamEvent = \n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage?: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n additionalProperties?: boolean;\n };\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(tool.schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n const toolCallsBuffer: Record<string, any> = {};\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = decoder.decode(value);\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6);\n if (data === \"[DONE]\") continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n for (const toolCall of delta.tool_calls) {\n const { index } = toolCall;\n if (!toolCallsBuffer[index]) {\n toolCallsBuffer[index] = {\n id: toolCall.id || \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n };\n }\n\n if (toolCall.id) {\n toolCallsBuffer[index].id = toolCall.id;\n }\n if (toolCall.function?.name) {\n toolCallsBuffer[index].function.name +=\n toolCall.function.name;\n }\n if (toolCall.function?.arguments) {\n toolCallsBuffer[index].function.arguments +=\n toolCall.function.arguments;\n }\n }\n }\n } catch (e) {\n // Skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n // Convert tool calls buffer to array\n toolCalls = Object.values(toolCallsBuffer);\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n const messages = [...ctx.history];\n let system = instructions;\n\n // Extract system message if it exists\n if (messages[0]?.role === \"system\") {\n system = messages[0].content;\n messages.shift();\n }\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = decoder.decode(value);\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: JSON.stringify(toolUse.input),\n },\n });\n }\n } catch (e) {\n // Skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n const chunk = decoder.decode(value);\n const lines = chunk.split(\"\\n\");\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6);\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // Skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport { ConversationContext, StepFunction, ToolCall } from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: { model?: string; schema?: any } = {}): StepFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : ctxOrMessage;\n\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n\n let currentCtx = ctx;\n\n do {\n currentCtx = await callProvider(\n { model, instructions, schema: normalizedSchema },\n currentCtx,\n );\n\n if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {\n currentCtx = await executeTools(currentCtx);\n }\n } while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n // notify UI of pending tool calls\n if (ctx.stream) {\n ctx.stream({ type: 'tool_calls_ready', calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n } = toolConfig;\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n\n if (!approval?.approved) {\n if (ctx.stream) {\n ctx.stream({ type: 'tool_error', call, error: 'Tool execution denied by user' });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: 'tool_error', call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: 'tool_executing', call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: 'tool_complete', call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n \n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: 'tool_error', call, error });\n }\n return { call, result: { error } };\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCall))\n : await runCallsSequentially(calls, runCall);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst defaultStore = createMemoryStore();\nconst threads = new Map<string, Thread>();\n\nexport const getOrCreateThread = (\n id: string,\n store: ThreadStore = defaultStore,\n): Thread => {\n if (threads.has(id)) {\n return threads.get(id)!;\n }\n\n const thread = createThread(id, store);\n threads.set(id, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage?: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n \n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || { \n history: [], \n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AA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,IAAI,KAAK;AAAA,QACxB;AAEA,eAAO;AAAA,MACT;AAAA,MACA,CAAC;AAAA,IACH;AAEA,cAAU,QAAQ;AAClB,cAAU,gBAAgB;AAC1B,cAAU,aAAa;AAAA,EACzB;AAEA,MAAI,OAAO,YAAY;AACrB,cAAU,aAAa,EAAE,GAAG,OAAO,WAAW;AAAA,EAChD;AAEA,MAAI,OAAO,QAAQ;AACjB,UAAM,CAAC,OAAO,GAAG,IAAI,IAAI,UAAU;AACnC,QAAI,OAAO,SAAS,UAAU;AAC5B,gBAAU,UAAU,CAAC,EAAE,MAAM,UAAU,SAAS,OAAO,OAAO,GAAG,GAAG,IAAI;AAAA,IAC1E,OAAO;AACL,gBAAU,UAAU,CAAC,EAAE,MAAM,UAAU,SAAS,OAAO,OAAO,GAAG,GAAG,UAAU,OAAO;AAAA,IACvF;AAAA,EACF;AAEA,SAAO;AACT;AAEO,IAAM,QAAQ,CACnB,WACG,UACc;AACjB,SAAO,OAAO,QAA2D;AACvE,QAAI,YAAY,aAAa,QAAQ,GAAG;AAExC,QAAI,OAAO,OAAO;AAChB,SAAG;AACD,oBAAY,MAAM,QAAQ,GAAG,KAAK,EAAE,SAAS;AAAA,MAC/C,SAAS,CAAC,OAAO,MAAM,SAAS;AAAA,IAClC,OAAO;AACL,kBAAY,MAAM,QAAQ,GAAG,KAAK,EAAE,SAAS;AAAA,IAC/C;AAEA,WAAO;AAAA,MACL,GAAG;AAAA,MACH,SAAS,OAAO,SAAS,IAAI,UAAU,UAAU;AAAA,MACjD,cAAc,OAAO,SAAS,IAAI,eAAe,UAAU;AAAA,MAC3D,aAAa,OAAO,SAAS,IAAI,cAAc,UAAU;AAAA,MACzD,YAAY,OAAO,SAAS,IAAI,aAAa,UAAU;AAAA,IACzD;AAAA,EACF;AACF;","names":["Inherit","model","maxCalls","model","model","model","msg","model","model","maxCalls","error"]}
1
+ {"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/mcp.ts","../src/types.ts","../src/utils.ts","../src/embed.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts","../src/utils/rateLimited.ts"],"sourcesContent":["export * from \"./mcp\";\nexport * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./embed\";\nexport * from \"./thread\";\nexport * from \"./schema\";\nexport * from \"./helpers\";\nexport * from \"./approval\";\nexport * from \"./composition/tap\";\nexport * from \"./composition/when\";\nexport * from \"./composition/model\";\nexport * from \"./composition/retry\";\nexport * from \"./composition/scope\";\nexport * from \"./utils/rateLimited\";\nexport * from \"./composition/compose\";\n","import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\nimport { z, type ZodType } from \"zod\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return {\n name,\n schema: jsonSchema,\n };\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n\nexport const convertStandardSchemaToSchemaProperties = (\n standardSchema: StandardSchema,\n): Record<string, SchemaProperty> => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return convertMCPSchemaToToolSchema(jsonSchema);\n};\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty> | StandardSchema;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n /** require user approval before executing tools */\n requireApproval?: boolean;\n /**\n * custom callback to handle tool approval, return true to approve\n * \n * @example\n * // simple callback\n * approvalCallback: (call) => call.function.name !== 'dangerousTool'\n * \n * @example\n * // event-driven (SSE): server sends approval request, waits for client POST\n * approvalCallback: (call) => new Promise((resolve) => {\n * pendingApprovals.set(call.id, resolve);\n * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\\n\\n`);\n * })\n * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))\n */\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n /** execute tools in parallel instead of sequentially */\n parallel?: boolean;\n /** number of times to retry failed tool executions */\n retryCount?: number;\n /** identifier for approval requests, useful for managing multiple approval flows */\n approvalId?: string;\n /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */\n executeOnApproval?: boolean;\n}\n\nexport type StreamEvent =\n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n stream?: (event: StreamEvent) => void;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: Record<string, any>;\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n [key: string]: any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\nimport { isStandardSchema, convertStandardSchemaToSchemaProperties } from \"./schema\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const schema = isStandardSchema(tool.schema)\n ? convertStandardSchemaToSchemaProperties(tool.schema)\n : tool.schema;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { pipeline } from \"@huggingface/transformers\";\nimport { getKey } from \"./utils\";\n\nconst modelCache = new Map<string, any>();\n\n/**\n * generates embeddings for text using openai or huggingface models\n *\n * openai models use the prefix \"openai/\" (e.g., \"openai/text-embedding-3-small\")\n * all other models use huggingface transformers\n *\n * @example\n * const vector = await embed(\"openai/text-embedding-3-small\", \"hello world\");\n * const vector2 = await embed(\"Xenova/all-MiniLM-L6-v2\", \"hello world\");\n */\nexport const embed = async (\n model: string,\n text: string,\n config?: { dimensions?: number },\n): Promise<number[]> => {\n if (model.startsWith(\"openai/\")) {\n const modelName = model.replace(\"openai/\", \"\");\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const body: any = {\n model: modelName,\n input: text,\n };\n\n if (config?.dimensions) {\n body.dimensions = config.dimensions;\n }\n\n const response = await fetch(\"https://api.openai.com/v1/embeddings\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n const data = (await response.json()) as any;\n return data.data[0].embedding;\n }\n\n if (!modelCache.has(model)) {\n const extractor = await pipeline(\"feature-extraction\", model, {\n dtype: \"fp32\",\n });\n modelCache.set(model, extractor);\n }\n\n const extractor = modelCache.get(model);\n const result = await extractor(text, { pooling: \"mean\", normalize: true });\n return Array.from(result.data);\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\n// openai streams tool calls as incremental chunks with index properties that need assembly\n// example: {\"index\": 0, \"function\": {\"name\": \"get_wea\"}} then {\"index\": 0, \"function\": {\"arguments\": \"ther\"}}\n// google/anthropic send complete tool calls in single chunks, so they don't need this logic\nconst appendToolCalls = (toolCalls: any[], tcchunklist: any[]): any[] => {\n for (const tcchunk of tcchunklist) {\n while (toolCalls.length <= tcchunk.index) {\n toolCalls.push({\n id: \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n }\n const tc = toolCalls[tcchunk.index];\n tc.id += tcchunk.id || \"\";\n tc.function.name += tcchunk.function?.name || \"\";\n tc.function.arguments += tcchunk.function?.arguments || \"\";\n }\n return toolCalls;\n};\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") continue;\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: \"content\", content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n toolCalls = appendToolCalls(toolCalls, delta.tool_calls);\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nconst convertToAnthropicFormat = (messages: any[]): any[] => {\n const result: any[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n\n if (msg.role === \"system\") {\n i++;\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (msg.tool_calls) {\n result.push({\n role: \"assistant\",\n content: msg.tool_calls.map((tc: any) => ({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments),\n })),\n });\n } else {\n result.push({\n role: \"assistant\",\n content: msg.content,\n });\n }\n i++;\n } else if (msg.role === \"tool\") {\n const toolResults: any[] = [];\n while (i < messages.length && messages[i].role === \"tool\") {\n const toolMsg = messages[i];\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolMsg.tool_call_id,\n content: toolMsg.content,\n });\n i++;\n }\n result.push({\n role: \"user\",\n content: toolResults,\n });\n } else {\n result.push(msg);\n i++;\n }\n }\n\n return result;\n};\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n let system = instructions;\n\n if (ctx.history[0]?.role === \"system\") {\n system = ctx.history[0].content;\n }\n\n const messages = convertToAnthropicFormat(ctx.history);\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: \"\",\n },\n index: parsed.index,\n });\n }\n\n if (\n parsed.type === \"content_block_delta\" &&\n parsed.delta?.type === \"input_json_delta\"\n ) {\n const toolCall = toolCalls.find((tc) => tc.index === parsed.index);\n if (toolCall) {\n toolCall.function.arguments += parsed.delta.partial_json;\n }\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls.map(({ index, ...tc }) => tc);\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n \n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport {\n ConversationContext,\n StepFunction,\n ToolCall,\n JsonSchema,\n StandardSchema,\n ComposedFunction,\n} from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: {\n model?: string;\n schema?: JsonSchema | StandardSchema;\n} = {}): ComposedFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? // model()(\"hello!\");\n {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : // model()(/* few shot or history */);\n ctxOrMessage;\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n let currentCtx = ctx;\n\n do {\n currentCtx = await callProvider(\n { model, instructions, schema: normalizedSchema },\n currentCtx,\n );\n\n if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {\n currentCtx = await executeTools(currentCtx);\n }\n } while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_calls_ready\", calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n executeOnApproval = false,\n } = toolConfig;\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall, approved: boolean) => {\n if (!approved) {\n if (ctx.stream) {\n ctx.stream({\n type: \"tool_error\",\n call,\n error: \"Tool execution denied by user\",\n });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_executing\", call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: \"tool_complete\", call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n\n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return { call, result: { error } };\n };\n\n if (executeOnApproval && requireApproval) {\n const resultPromises = calls.map(async (call) => {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return runCall(call, approved);\n });\n\n const results = await Promise.all(resultPromises);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n }\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const runCallWithApproval = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n return runCall(call, approval?.approved ?? true);\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCallWithApproval))\n : await runCallsSequentially(calls, runCallWithApproval);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst threads = new Map<string, Thread>();\n\n/**\n * @example\n * // in-memory (default)\n * const thread = getOrCreateThread('user-123');\n *\n * @example\n * // sqlite\n * const thread = getOrCreateThread('user-123', {\n * async get(id) {\n * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);\n * return row ? JSON.parse(row.messages) : [];\n * },\n * async set(id, messages) {\n * await db.run(\n * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',\n * id,\n * JSON.stringify(messages),\n * Date.now()\n * );\n * }\n * });\n */\nexport const getOrCreateThread = (id: string, store?: ThreadStore): Thread => {\n const cacheKey = store ? `${id}-${store}` : id;\n\n if (threads.has(cacheKey)) {\n return threads.get(cacheKey)!;\n }\n\n const threadStore = store || createMemoryStore();\n const thread = createThread(id, threadStore);\n threads.set(cacheKey, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n\n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n if (config.stream) {\n scopedCtx.stream = config.stream;\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n","type RateLimitConfig = {\n rps: number;\n burst: number;\n concurrency: number;\n};\n\ntype QueueItem = {\n fn: () => Promise<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n};\n\n/**\n * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls\n * \n * @param config - rate limit configuration\n * @param config.rps - maximum requests per second\n * @param config.burst - maximum burst size (initial token bucket capacity)\n * @param config.concurrency - maximum concurrent in-flight requests\n * \n * @example\n * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });\n * \n * const workflow = limiter(\n * compose(\n * scope({ tools: [searchTool] }, model())\n * )\n * );\n * \n * await workflow(\"hello\");\n */\nexport const rateLimited =\n (config: RateLimitConfig) =>\n <T extends (...args: any[]) => Promise<any>>(fn: T): T => {\n const { rps, burst, concurrency } = config;\n\n let tokens = burst;\n let inFlight = 0;\n const queue: QueueItem[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n\n const refillTokens = () => {\n tokens = Math.min(tokens + 1, burst);\n processQueue();\n };\n\n const startInterval = () => {\n if (!intervalId) {\n intervalId = setInterval(refillTokens, 1000 / rps);\n }\n };\n\n const stopInterval = () => {\n if (intervalId && queue.length === 0 && inFlight === 0) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n const processQueue = () => {\n while (queue.length > 0 && tokens > 0 && inFlight < concurrency) {\n tokens--;\n inFlight++;\n\n const item = queue.shift()!;\n\n item\n .fn()\n .then((result) => {\n inFlight--;\n item.resolve(result);\n processQueue();\n stopInterval();\n })\n .catch((error) => {\n inFlight--;\n item.reject(error);\n processQueue();\n stopInterval();\n });\n }\n };\n\n return (async (...args: any[]) => {\n return new Promise((resolve, reject) => {\n queue.push({\n fn: () => fn(...args),\n resolve,\n reject,\n });\n startInterval();\n processQueue();\n });\n }) as T;\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iBAAgC;AAEzB,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AACf,QAAM,aAAa,aAAE,aAAa,cAAyB;AAC3D,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,EACV;AACF;AAEO,IAAM,+BAA+B,CAC1C,cACmC;AACnC,MAAI,CAAC,WAAW,WAAY,QAAO,CAAC;AAEpC,QAAM,SAAyC,CAAC;AAChD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,UAAU,GAAG;AAC/D,UAAM,OAAO;AACb,WAAO,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SAAgB;AAChC,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK;AAAA,QACT,IAAI,MAAM,GAAG,GAAG,IAAI;AAAA,QACpB;AAAA,QACA;AAAA,MACF,CAAC;AACD,oBAAc;AACd,mBAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;","names":["Inherit","model","maxCalls","model","extractor","model","model","model","msg","model","model","maxCalls","error","results"]}
package/dist/index.d.cts CHANGED
@@ -32,7 +32,7 @@ interface ToolDefinition {
32
32
  interface ToolConfig {
33
33
  name: string;
34
34
  description: string;
35
- schema: Record<string, SchemaProperty>;
35
+ schema: Record<string, SchemaProperty> | StandardSchema;
36
36
  execute: (args: any) => Promise<any> | any;
37
37
  _maxCalls?: number;
38
38
  }
@@ -45,11 +45,32 @@ interface SchemaProperty {
45
45
  properties?: Record<string, SchemaProperty>;
46
46
  }
47
47
  interface ToolExecutionConfig {
48
+ /** require user approval before executing tools */
48
49
  requireApproval?: boolean;
50
+ /**
51
+ * custom callback to handle tool approval, return true to approve
52
+ *
53
+ * @example
54
+ * // simple callback
55
+ * approvalCallback: (call) => call.function.name !== 'dangerousTool'
56
+ *
57
+ * @example
58
+ * // event-driven (SSE): server sends approval request, waits for client POST
59
+ * approvalCallback: (call) => new Promise((resolve) => {
60
+ * pendingApprovals.set(call.id, resolve);
61
+ * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\n\n`);
62
+ * })
63
+ * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))
64
+ */
49
65
  approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;
66
+ /** execute tools in parallel instead of sequentially */
50
67
  parallel?: boolean;
68
+ /** number of times to retry failed tool executions */
51
69
  retryCount?: number;
70
+ /** identifier for approval requests, useful for managing multiple approval flows */
52
71
  approvalId?: string;
72
+ /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */
73
+ executeOnApproval?: boolean;
53
74
  }
54
75
  type StreamEvent = {
55
76
  type: 'content';
@@ -100,20 +121,17 @@ interface ScopeConfig {
100
121
  system?: string;
101
122
  silent?: boolean;
102
123
  until?: (ctx: ConversationContext) => boolean;
124
+ stream?: (event: StreamEvent) => void;
103
125
  }
104
126
  type StepFunction = (ctx: ConversationContext) => Promise<ConversationContext>;
105
- type ComposedFunction = (ctxOrMessage?: ConversationContext | string) => Promise<ConversationContext>;
127
+ type ComposedFunction = (ctxOrMessage: ConversationContext | string) => Promise<ConversationContext>;
106
128
  interface JsonSchema {
107
129
  name: string;
108
- schema: {
109
- type: string;
110
- properties: Record<string, any>;
111
- required?: string[];
112
- additionalProperties?: boolean;
113
- };
130
+ schema: Record<string, any>;
114
131
  }
115
132
  interface StandardSchema {
116
133
  "~standard": any;
134
+ [key: string]: any;
117
135
  }
118
136
  interface ProviderConfig {
119
137
  model: string;
@@ -152,12 +170,49 @@ declare const setKeys: (keys: ApiKeys) => void;
152
170
  declare const getKey: (provider: string) => string;
153
171
  declare const maxCalls: (toolConfig: ToolConfig, maxCalls: number) => ToolConfig;
154
172
 
173
+ /**
174
+ * generates embeddings for text using openai or huggingface models
175
+ *
176
+ * openai models use the prefix "openai/" (e.g., "openai/text-embedding-3-small")
177
+ * all other models use huggingface transformers
178
+ *
179
+ * @example
180
+ * const vector = await embed("openai/text-embedding-3-small", "hello world");
181
+ * const vector2 = await embed("Xenova/all-MiniLM-L6-v2", "hello world");
182
+ */
183
+ declare const embed: (model: string, text: string, config?: {
184
+ dimensions?: number;
185
+ }) => Promise<number[]>;
186
+
187
+ /**
188
+ * @example
189
+ * // in-memory (default)
190
+ * const thread = getOrCreateThread('user-123');
191
+ *
192
+ * @example
193
+ * // sqlite
194
+ * const thread = getOrCreateThread('user-123', {
195
+ * async get(id) {
196
+ * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);
197
+ * return row ? JSON.parse(row.messages) : [];
198
+ * },
199
+ * async set(id, messages) {
200
+ * await db.run(
201
+ * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',
202
+ * id,
203
+ * JSON.stringify(messages),
204
+ * Date.now()
205
+ * );
206
+ * }
207
+ * });
208
+ */
155
209
  declare const getOrCreateThread: (id: string, store?: ThreadStore) => Thread;
156
210
 
157
211
  declare const isStandardSchema: (schema: any) => schema is StandardSchema;
158
212
  declare const convertStandardSchemaToJsonSchema: (standardSchema: StandardSchema, name?: string) => JsonSchema;
159
213
  declare const convertMCPSchemaToToolSchema: (mcpSchema: any) => Record<string, SchemaProperty>;
160
214
  declare function normalizeSchema(schema: JsonSchema | StandardSchema, name?: string): JsonSchema;
215
+ declare const convertStandardSchemaToSchemaProperties: (standardSchema: StandardSchema) => Record<string, SchemaProperty>;
161
216
 
162
217
  /**
163
218
  * scope({ until: noToolsCalled() })
@@ -198,8 +253,8 @@ declare const when: (condition: (ctx: ConversationContext) => boolean, action: S
198
253
 
199
254
  declare const model: ({ model, schema, }?: {
200
255
  model?: string;
201
- schema?: any;
202
- }) => StepFunction;
256
+ schema?: JsonSchema | StandardSchema;
257
+ }) => ComposedFunction;
203
258
 
204
259
  /**
205
260
  * scope({}, retry({ times: 2 }, model(...)))
@@ -208,6 +263,32 @@ declare const retry: ({ times }: RetryOptions | undefined, step: StepFunction) =
208
263
 
209
264
  declare const scope: (config: ScopeConfig, ...steps: StepFunction[]) => StepFunction;
210
265
 
266
+ type RateLimitConfig = {
267
+ rps: number;
268
+ burst: number;
269
+ concurrency: number;
270
+ };
271
+ /**
272
+ * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls
273
+ *
274
+ * @param config - rate limit configuration
275
+ * @param config.rps - maximum requests per second
276
+ * @param config.burst - maximum burst size (initial token bucket capacity)
277
+ * @param config.concurrency - maximum concurrent in-flight requests
278
+ *
279
+ * @example
280
+ * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });
281
+ *
282
+ * const workflow = limiter(
283
+ * compose(
284
+ * scope({ tools: [searchTool] }, model())
285
+ * )
286
+ * );
287
+ *
288
+ * await workflow("hello");
289
+ */
290
+ declare const rateLimited: (config: RateLimitConfig) => <T extends (...args: any[]) => Promise<any>>(fn: T) => T;
291
+
211
292
  declare const compose: (...steps: StepFunction[]) => ComposedFunction;
212
293
 
213
- export { type ApiKeys, type ApprovalRequest, type ApprovalResponse, type ComposedFunction, type ConversationContext, Inherit, type JsonSchema, type Message, type ParsedModel, type ProviderConfig, type RetryOptions, type SchemaProperty, type ScopeConfig, type StandardSchema, type StepFunction, type StreamEvent, type Thread, type ThreadStore, type ToolCall, type ToolCallResult, type ToolConfig, type ToolDefinition, type ToolExecutionConfig, appendToLastRequest, compose, convertMCPSchemaToToolSchema, convertStandardSchemaToJsonSchema, createMCPTools, everyNMessages, everyNTokens, generateApprovalToken, getKey, getOrCreateThread, isStandardSchema, maxCalls, model, noToolsCalled, normalizeSchema, onApprovalRequested, onApprovalResolved, parseModelName, removeApprovalListener, requestApproval, resolveApproval, retry, scope, setKeys, tap, toolConfigToToolDefinition, toolNotUsedInNTurns, toolWasCalled, when };
294
+ export { type ApiKeys, type ApprovalRequest, type ApprovalResponse, type ComposedFunction, type ConversationContext, Inherit, type JsonSchema, type Message, type ParsedModel, type ProviderConfig, type RetryOptions, type SchemaProperty, type ScopeConfig, type StandardSchema, type StepFunction, type StreamEvent, type Thread, type ThreadStore, type ToolCall, type ToolCallResult, type ToolConfig, type ToolDefinition, type ToolExecutionConfig, appendToLastRequest, compose, convertMCPSchemaToToolSchema, convertStandardSchemaToJsonSchema, convertStandardSchemaToSchemaProperties, createMCPTools, embed, everyNMessages, everyNTokens, generateApprovalToken, getKey, getOrCreateThread, isStandardSchema, maxCalls, model, noToolsCalled, normalizeSchema, onApprovalRequested, onApprovalResolved, parseModelName, rateLimited, removeApprovalListener, requestApproval, resolveApproval, retry, scope, setKeys, tap, toolConfigToToolDefinition, toolNotUsedInNTurns, toolWasCalled, when };