@threaded/ai 1.0.0 → 1.0.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/index.cjs CHANGED
@@ -29,19 +29,24 @@ __export(index_exports, {
29
29
  everyNMessages: () => everyNMessages,
30
30
  everyNTokens: () => everyNTokens,
31
31
  generateApprovalToken: () => generateApprovalToken,
32
+ getKey: () => getKey,
32
33
  getOrCreateThread: () => getOrCreateThread,
33
34
  isStandardSchema: () => isStandardSchema,
35
+ maxCalls: () => maxCalls,
34
36
  model: () => model,
35
37
  noToolsCalled: () => noToolsCalled,
36
38
  normalizeSchema: () => normalizeSchema,
37
39
  onApprovalRequested: () => onApprovalRequested,
38
40
  onApprovalResolved: () => onApprovalResolved,
41
+ parseModelName: () => parseModelName,
39
42
  removeApprovalListener: () => removeApprovalListener,
40
43
  requestApproval: () => requestApproval,
41
44
  resolveApproval: () => resolveApproval,
42
45
  retry: () => retry,
43
46
  scope: () => scope,
47
+ setKeys: () => setKeys,
44
48
  tap: () => tap,
49
+ toolConfigToToolDefinition: () => toolConfigToToolDefinition,
45
50
  toolNotUsedInNTurns: () => toolNotUsedInNTurns,
46
51
  toolWasCalled: () => toolWasCalled,
47
52
  when: () => when
@@ -178,6 +183,9 @@ var parseModelName = (model2) => {
178
183
  };
179
184
  };
180
185
  var globalKeys = {};
186
+ var setKeys = (keys) => {
187
+ globalKeys = { ...globalKeys, ...keys };
188
+ };
181
189
  var getKey = (provider) => {
182
190
  const key = globalKeys[provider.toLowerCase()];
183
191
  if (!key) {
@@ -185,6 +193,10 @@ var getKey = (provider) => {
185
193
  }
186
194
  return key;
187
195
  };
196
+ var maxCalls = (toolConfig, maxCalls2) => ({
197
+ ...toolConfig,
198
+ _maxCalls: maxCalls2
199
+ });
188
200
 
189
201
  // src/providers/openai.ts
190
202
  var callOpenAI = async (config, ctx) => {
@@ -720,10 +732,10 @@ var executeTools = async (ctx) => {
720
732
  }
721
733
  const toolName = call.function.name;
722
734
  const limits = ctx.toolLimits || {};
723
- const maxCalls = limits[toolName];
735
+ const maxCalls2 = limits[toolName];
724
736
  const currentCount = updatedCounts[toolName] || 0;
725
- if (maxCalls && currentCount >= maxCalls) {
726
- const error2 = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;
737
+ if (maxCalls2 && currentCount >= maxCalls2) {
738
+ const error2 = `Tool ${toolName} has reached its limit of ${maxCalls2} calls`;
727
739
  if (ctx.stream) {
728
740
  ctx.stream({ type: "tool_error", call, error: error2 });
729
741
  }
@@ -1102,19 +1114,24 @@ var scope = (config, ...steps) => {
1102
1114
  everyNMessages,
1103
1115
  everyNTokens,
1104
1116
  generateApprovalToken,
1117
+ getKey,
1105
1118
  getOrCreateThread,
1106
1119
  isStandardSchema,
1120
+ maxCalls,
1107
1121
  model,
1108
1122
  noToolsCalled,
1109
1123
  normalizeSchema,
1110
1124
  onApprovalRequested,
1111
1125
  onApprovalResolved,
1126
+ parseModelName,
1112
1127
  removeApprovalListener,
1113
1128
  requestApproval,
1114
1129
  resolveApproval,
1115
1130
  retry,
1116
1131
  scope,
1132
+ setKeys,
1117
1133
  tap,
1134
+ toolConfigToToolDefinition,
1118
1135
  toolNotUsedInNTurns,
1119
1136
  toolWasCalled,
1120
1137
  when
@@ -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 \"./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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AAEf,MAAI;AACF,UAAM,YAAY,QAAQ,KAAK;AAC/B,QAAI,aAAa,OAAO,UAAU,iBAAiB,YAAY;AAC7D,YAAM,aAAa,UAAU,aAAa,cAAc;AACxD,aAAO;AAAA,QACL;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAEhB;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;AACF;AAEO,IAAM,+BAA+B,CAC1C,cACmC;AACnC,MAAI,CAAC,WAAW,WAAY,QAAO,CAAC;AAEpC,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,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","model","model","model","msg","model","model","error"]}
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;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACEO,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AAEf,MAAI;AACF,UAAM,YAAY,QAAQ,KAAK;AAC/B,QAAI,aAAa,OAAO,UAAU,iBAAiB,YAAY;AAC7D,YAAM,aAAa,UAAU,aAAa,cAAc;AACxD,aAAO;AAAA,QACL;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAEhB;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;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,GAAG,IAAI;AAAA,MACZ,MAAM,KAAK,QAAQ;AAAA,MACnB,aAAa,KAAK,eAAe;AAAA,MACjC,UAAU,CAAC,UAAU,UAAU,SAAS,GAAG;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,gBACd,QACA,MACY;AACZ,MAAI,iBAAiB,MAAM,GAAG;AAC5B,WAAO,kCAAkC,QAAQ,IAAI;AAAA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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"]}
package/dist/index.d.cts CHANGED
@@ -146,6 +146,12 @@ interface RetryOptions {
146
146
 
147
147
  declare const createMCPTools: (client: Client) => Promise<ToolConfig[]>;
148
148
 
149
+ declare const toolConfigToToolDefinition: (tool: ToolConfig) => ToolDefinition;
150
+ declare const parseModelName: (model: string) => ParsedModel;
151
+ declare const setKeys: (keys: ApiKeys) => void;
152
+ declare const getKey: (provider: string) => string;
153
+ declare const maxCalls: (toolConfig: ToolConfig, maxCalls: number) => ToolConfig;
154
+
149
155
  declare const getOrCreateThread: (id: string, store?: ThreadStore) => Thread;
150
156
 
151
157
  declare const isStandardSchema: (schema: any) => schema is StandardSchema;
@@ -204,4 +210,4 @@ declare const scope: (config: ScopeConfig, ...steps: StepFunction[]) => StepFunc
204
210
 
205
211
  declare const compose: (...steps: StepFunction[]) => ComposedFunction;
206
212
 
207
- 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, getOrCreateThread, isStandardSchema, model, noToolsCalled, normalizeSchema, onApprovalRequested, onApprovalResolved, removeApprovalListener, requestApproval, resolveApproval, retry, scope, tap, toolNotUsedInNTurns, toolWasCalled, when };
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 };
package/dist/index.d.ts CHANGED
@@ -146,6 +146,12 @@ interface RetryOptions {
146
146
 
147
147
  declare const createMCPTools: (client: Client) => Promise<ToolConfig[]>;
148
148
 
149
+ declare const toolConfigToToolDefinition: (tool: ToolConfig) => ToolDefinition;
150
+ declare const parseModelName: (model: string) => ParsedModel;
151
+ declare const setKeys: (keys: ApiKeys) => void;
152
+ declare const getKey: (provider: string) => string;
153
+ declare const maxCalls: (toolConfig: ToolConfig, maxCalls: number) => ToolConfig;
154
+
149
155
  declare const getOrCreateThread: (id: string, store?: ThreadStore) => Thread;
150
156
 
151
157
  declare const isStandardSchema: (schema: any) => schema is StandardSchema;
@@ -204,4 +210,4 @@ declare const scope: (config: ScopeConfig, ...steps: StepFunction[]) => StepFunc
204
210
 
205
211
  declare const compose: (...steps: StepFunction[]) => ComposedFunction;
206
212
 
207
- 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, getOrCreateThread, isStandardSchema, model, noToolsCalled, normalizeSchema, onApprovalRequested, onApprovalResolved, removeApprovalListener, requestApproval, resolveApproval, retry, scope, tap, toolNotUsedInNTurns, toolWasCalled, when };
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 };
package/dist/index.js CHANGED
@@ -135,6 +135,9 @@ var parseModelName = (model2) => {
135
135
  };
136
136
  };
137
137
  var globalKeys = {};
138
+ var setKeys = (keys) => {
139
+ globalKeys = { ...globalKeys, ...keys };
140
+ };
138
141
  var getKey = (provider) => {
139
142
  const key = globalKeys[provider.toLowerCase()];
140
143
  if (!key) {
@@ -142,6 +145,10 @@ var getKey = (provider) => {
142
145
  }
143
146
  return key;
144
147
  };
148
+ var maxCalls = (toolConfig, maxCalls2) => ({
149
+ ...toolConfig,
150
+ _maxCalls: maxCalls2
151
+ });
145
152
 
146
153
  // src/providers/openai.ts
147
154
  var callOpenAI = async (config, ctx) => {
@@ -677,10 +684,10 @@ var executeTools = async (ctx) => {
677
684
  }
678
685
  const toolName = call.function.name;
679
686
  const limits = ctx.toolLimits || {};
680
- const maxCalls = limits[toolName];
687
+ const maxCalls2 = limits[toolName];
681
688
  const currentCount = updatedCounts[toolName] || 0;
682
- if (maxCalls && currentCount >= maxCalls) {
683
- const error2 = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;
689
+ if (maxCalls2 && currentCount >= maxCalls2) {
690
+ const error2 = `Tool ${toolName} has reached its limit of ${maxCalls2} calls`;
684
691
  if (ctx.stream) {
685
692
  ctx.stream({ type: "tool_error", call, error: error2 });
686
693
  }
@@ -1058,19 +1065,24 @@ export {
1058
1065
  everyNMessages,
1059
1066
  everyNTokens,
1060
1067
  generateApprovalToken,
1068
+ getKey,
1061
1069
  getOrCreateThread,
1062
1070
  isStandardSchema,
1071
+ maxCalls,
1063
1072
  model,
1064
1073
  noToolsCalled,
1065
1074
  normalizeSchema,
1066
1075
  onApprovalRequested,
1067
1076
  onApprovalResolved,
1077
+ parseModelName,
1068
1078
  removeApprovalListener,
1069
1079
  requestApproval,
1070
1080
  resolveApproval,
1071
1081
  retry,
1072
1082
  scope,
1083
+ setKeys,
1073
1084
  tap,
1085
+ toolConfigToToolDefinition,
1074
1086
  toolNotUsedInNTurns,
1075
1087
  toolWasCalled,
1076
1088
  when
package/dist/index.js.map CHANGED
@@ -1 +1 @@
1
- {"version":3,"sources":["../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":["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":";;;;;;;;AAEO,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AAEf,MAAI;AACF,UAAM,YAAY,UAAQ,KAAK;AAC/B,QAAI,aAAa,OAAO,UAAU,iBAAiB,YAAY;AAC7D,YAAM,aAAa,UAAU,aAAa,cAAc;AACxD,aAAO;AAAA,QACL;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAEhB;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;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,GAAG,IAAI;AAAA,MACZ,MAAM,KAAK,QAAQ;AAAA,MACnB,aAAa,KAAK,eAAe;AAAA,MACjC,UAAU,CAAC,UAAU,UAAU,SAAS,GAAG;AAAA,IAC7C;AAAA,EACF;AACA,SAAO;AACT;AAEO,SAAS,gBACd,QACA,MACY;AACZ,MAAI,iBAAiB,MAAM,GAAG;AAC5B,WAAO,kCAAkC,QAAQ,IAAI;AAAA,EACvD;AACA,SAAO;AACT;;;ACnDO,IAAM,iBAAiB,OAAO,WAA0C;AAC7E,QAAM,aAAa,OAAO,iBAAiB;AAC3C,QAAM,aAAa,YAAY;AAE/B,MAAI,CAAC,YAAY;A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A,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","model","model","model","msg","model","model","error"]}
1
+ {"version":3,"sources":["../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":["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":";;;;;;;;AAEO,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AAEf,MAAI;AACF,UAAM,YAAY,UAAQ,KAAK;AAC/B,QAAI,aAAa,OAAO,UAAU,iBAAiB,YAAY;AAC7D,YAAM,aAAa,UAAU,aAAa,cAAc;AACxD,aAAO;AAAA,QACL;AAAA,QACA,QAAQ;AAAA,MACV;AAAA,IACF;AAAA,EACF,SAAS,OAAO;AAAA,EAEhB;AAEA,QAAM,IAAI;AAAA,IACR;AAAA,EAEF;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,GA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AG,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"]}
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@threaded/ai",
3
- "version": "1.0.0",
3
+ "version": "1.0.1",
4
4
  "main": "dist/index.js",
5
5
  "type": "module",
6
6
  "scripts": {