@threaded/ai 1.0.4 → 1.0.5
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/index.cjs +45 -13
- package/dist/index.cjs.map +1 -1
- package/dist/index.d.cts +1 -0
- package/dist/index.d.ts +1 -0
- package/dist/index.js +35 -13
- package/dist/index.js.map +1 -1
- package/package.json +1 -1
package/dist/index.cjs
CHANGED
|
@@ -1,7 +1,9 @@
|
|
|
1
1
|
"use strict";
|
|
2
|
+
var __create = Object.create;
|
|
2
3
|
var __defProp = Object.defineProperty;
|
|
3
4
|
var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
|
|
4
5
|
var __getOwnPropNames = Object.getOwnPropertyNames;
|
|
6
|
+
var __getProtoOf = Object.getPrototypeOf;
|
|
5
7
|
var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
6
8
|
var __export = (target, all) => {
|
|
7
9
|
for (var name in all)
|
|
@@ -15,6 +17,14 @@ var __copyProps = (to, from, except, desc) => {
|
|
|
15
17
|
}
|
|
16
18
|
return to;
|
|
17
19
|
};
|
|
20
|
+
var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
|
|
21
|
+
// If the importer is in node compatibility mode or this is not an ESM
|
|
22
|
+
// file that has been converted to a CommonJS file using a Babel-
|
|
23
|
+
// compatible transform (i.e. "__esModule" has not been set), then set
|
|
24
|
+
// "default" to the CommonJS "module.exports" for node compatibility.
|
|
25
|
+
isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
|
|
26
|
+
mod
|
|
27
|
+
));
|
|
18
28
|
var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
|
|
19
29
|
|
|
20
30
|
// src/index.ts
|
|
@@ -200,7 +210,6 @@ var maxCalls = (toolConfig, maxCalls2) => ({
|
|
|
200
210
|
});
|
|
201
211
|
|
|
202
212
|
// src/embed.ts
|
|
203
|
-
var import_transformers = require("@huggingface/transformers");
|
|
204
213
|
var modelCache = /* @__PURE__ */ new Map();
|
|
205
214
|
var embed = async (model2, text, config) => {
|
|
206
215
|
if (model2.startsWith("openai/")) {
|
|
@@ -231,15 +240,22 @@ var embed = async (model2, text, config) => {
|
|
|
231
240
|
const data = await response.json();
|
|
232
241
|
return data.data[0].embedding;
|
|
233
242
|
}
|
|
234
|
-
|
|
235
|
-
const
|
|
236
|
-
|
|
237
|
-
|
|
238
|
-
|
|
243
|
+
try {
|
|
244
|
+
const { pipeline } = await import("@huggingface/transformers");
|
|
245
|
+
if (!modelCache.has(model2)) {
|
|
246
|
+
const extractor2 = await pipeline("feature-extraction", model2, {
|
|
247
|
+
dtype: "fp32"
|
|
248
|
+
});
|
|
249
|
+
modelCache.set(model2, extractor2);
|
|
250
|
+
}
|
|
251
|
+
const extractor = modelCache.get(model2);
|
|
252
|
+
const result = await extractor(text, { pooling: "mean", normalize: true });
|
|
253
|
+
return Array.from(result.data);
|
|
254
|
+
} catch (error) {
|
|
255
|
+
throw new Error(
|
|
256
|
+
`huggingface transformers failed to load. install system dependencies or use openai models instead. original error: ${error.message}`
|
|
257
|
+
);
|
|
239
258
|
}
|
|
240
|
-
const extractor = modelCache.get(model2);
|
|
241
|
-
const result = await extractor(text, { pooling: "mean", normalize: true });
|
|
242
|
-
return Array.from(result.data);
|
|
243
259
|
};
|
|
244
260
|
|
|
245
261
|
// src/providers/openai.ts
|
|
@@ -295,7 +311,8 @@ var callOpenAI = async (config, ctx) => {
|
|
|
295
311
|
"Content-Type": "application/json",
|
|
296
312
|
Authorization: `Bearer ${apiKey}`
|
|
297
313
|
},
|
|
298
|
-
body: JSON.stringify(body)
|
|
314
|
+
body: JSON.stringify(body),
|
|
315
|
+
signal: ctx.abortSignal
|
|
299
316
|
});
|
|
300
317
|
if (!response.ok) {
|
|
301
318
|
const error = await response.text();
|
|
@@ -328,6 +345,9 @@ var handleOpenAIStream = async (response, ctx) => {
|
|
|
328
345
|
let buffer = "";
|
|
329
346
|
try {
|
|
330
347
|
while (true) {
|
|
348
|
+
if (ctx.abortSignal?.aborted) {
|
|
349
|
+
break;
|
|
350
|
+
}
|
|
331
351
|
const { done, value } = await reader.read();
|
|
332
352
|
if (done) break;
|
|
333
353
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -469,7 +489,8 @@ Return only the JSON object, no other text or formatting.`;
|
|
|
469
489
|
"x-api-key": apiKey,
|
|
470
490
|
"anthropic-version": "2023-06-01"
|
|
471
491
|
},
|
|
472
|
-
body: JSON.stringify(body)
|
|
492
|
+
body: JSON.stringify(body),
|
|
493
|
+
signal: ctx.abortSignal
|
|
473
494
|
});
|
|
474
495
|
if (!response.ok) {
|
|
475
496
|
const error = await response.text();
|
|
@@ -510,6 +531,9 @@ var handleAnthropicStream = async (response, ctx) => {
|
|
|
510
531
|
let buffer = "";
|
|
511
532
|
try {
|
|
512
533
|
while (true) {
|
|
534
|
+
if (ctx.abortSignal?.aborted) {
|
|
535
|
+
break;
|
|
536
|
+
}
|
|
513
537
|
const { done, value } = await reader.read();
|
|
514
538
|
if (done) break;
|
|
515
539
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -614,7 +638,8 @@ var callGoogle = async (config, ctx) => {
|
|
|
614
638
|
headers: {
|
|
615
639
|
"Content-Type": "application/json"
|
|
616
640
|
},
|
|
617
|
-
body: JSON.stringify(body)
|
|
641
|
+
body: JSON.stringify(body),
|
|
642
|
+
signal: ctx.abortSignal
|
|
618
643
|
}
|
|
619
644
|
);
|
|
620
645
|
if (!response.ok) {
|
|
@@ -657,6 +682,9 @@ var handleGoogleStream = async (response, ctx) => {
|
|
|
657
682
|
let buffer = "";
|
|
658
683
|
try {
|
|
659
684
|
while (true) {
|
|
685
|
+
if (ctx.abortSignal?.aborted) {
|
|
686
|
+
break;
|
|
687
|
+
}
|
|
660
688
|
const { done, value } = await reader.read();
|
|
661
689
|
if (done) break;
|
|
662
690
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -788,6 +816,9 @@ var model = ({
|
|
|
788
816
|
const instructions = systemMessage?.content;
|
|
789
817
|
let currentCtx = ctx;
|
|
790
818
|
do {
|
|
819
|
+
if (currentCtx.abortSignal?.aborted) {
|
|
820
|
+
break;
|
|
821
|
+
}
|
|
791
822
|
currentCtx = await callProvider(
|
|
792
823
|
{ model: model2, instructions, schema: normalizedSchema },
|
|
793
824
|
currentCtx
|
|
@@ -795,7 +826,7 @@ var model = ({
|
|
|
795
826
|
if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {
|
|
796
827
|
currentCtx = await executeTools(currentCtx);
|
|
797
828
|
}
|
|
798
|
-
} while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);
|
|
829
|
+
} while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length && !currentCtx.abortSignal?.aborted);
|
|
799
830
|
return currentCtx;
|
|
800
831
|
};
|
|
801
832
|
};
|
|
@@ -1193,6 +1224,7 @@ var scopeContext = (config, ctx) => {
|
|
|
1193
1224
|
scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : void 0;
|
|
1194
1225
|
}
|
|
1195
1226
|
scopedCtx.stream = ctx.stream;
|
|
1227
|
+
scopedCtx.abortSignal = ctx.abortSignal;
|
|
1196
1228
|
if (config.tools) {
|
|
1197
1229
|
const toolDefinitions = config.tools.map(toolConfigToToolDefinition);
|
|
1198
1230
|
const toolExecutors = config.tools.reduce(
|
package/dist/index.cjs.map
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/mcp.ts","../src/types.ts","../src/utils.ts","../src/embed.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts","../src/utils/rateLimited.ts"],"sourcesContent":["export * from \"./mcp\";\nexport * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./embed\";\nexport * from \"./thread\";\nexport * from \"./schema\";\nexport * from \"./helpers\";\nexport * from \"./approval\";\nexport * from \"./composition/tap\";\nexport * from \"./composition/when\";\nexport * from \"./composition/model\";\nexport * from \"./composition/retry\";\nexport * from \"./composition/scope\";\nexport * from \"./utils/rateLimited\";\nexport * from \"./composition/compose\";\n","import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\nimport { z, type ZodType } from \"zod\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return {\n name,\n schema: jsonSchema,\n };\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n ...(prop.enum && { enum: prop.enum }),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n\nexport const convertStandardSchemaToSchemaProperties = (\n standardSchema: StandardSchema,\n): Record<string, SchemaProperty> => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return convertMCPSchemaToToolSchema(jsonSchema);\n};\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty> | StandardSchema;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n /** require user approval before executing tools */\n requireApproval?: boolean;\n /**\n * custom callback to handle tool approval, return true to approve\n * \n * @example\n * // simple callback\n * approvalCallback: (call) => call.function.name !== 'dangerousTool'\n * \n * @example\n * // event-driven (SSE): server sends approval request, waits for client POST\n * approvalCallback: (call) => new Promise((resolve) => {\n * pendingApprovals.set(call.id, resolve);\n * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\\n\\n`);\n * })\n * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))\n */\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n /** execute tools in parallel instead of sequentially */\n parallel?: boolean;\n /** number of times to retry failed tool executions */\n retryCount?: number;\n /** identifier for approval requests, useful for managing multiple approval flows */\n approvalId?: string;\n /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */\n executeOnApproval?: boolean;\n}\n\nexport type StreamEvent =\n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n stream?: (event: StreamEvent) => void;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: Record<string, any>;\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n [key: string]: any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\nimport { isStandardSchema, convertStandardSchemaToSchemaProperties } from \"./schema\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const schema = isStandardSchema(tool.schema)\n ? convertStandardSchemaToSchemaProperties(tool.schema)\n : tool.schema;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { pipeline } from \"@huggingface/transformers\";\nimport { getKey } from \"./utils\";\n\nconst modelCache = new Map<string, any>();\n\n/**\n * generates embeddings for text using openai or huggingface models\n *\n * openai models use the prefix \"openai/\" (e.g., \"openai/text-embedding-3-small\")\n * all other models use huggingface transformers\n *\n * @example\n * const vector = await embed(\"openai/text-embedding-3-small\", \"hello world\");\n * const vector2 = await embed(\"Xenova/all-MiniLM-L6-v2\", \"hello world\");\n */\nexport const embed = async (\n model: string,\n text: string,\n config?: { dimensions?: number },\n): Promise<number[]> => {\n if (model.startsWith(\"openai/\")) {\n const modelName = model.replace(\"openai/\", \"\");\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const body: any = {\n model: modelName,\n input: text,\n };\n\n if (config?.dimensions) {\n body.dimensions = config.dimensions;\n }\n\n const response = await fetch(\"https://api.openai.com/v1/embeddings\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n const data = (await response.json()) as any;\n return data.data[0].embedding;\n }\n\n if (!modelCache.has(model)) {\n const extractor = await pipeline(\"feature-extraction\", model, {\n dtype: \"fp32\",\n });\n modelCache.set(model, extractor);\n }\n\n const extractor = modelCache.get(model);\n const result = await extractor(text, { pooling: \"mean\", normalize: true });\n return Array.from(result.data);\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\n// openai streams tool calls as incremental chunks with index properties that need assembly\n// example: {\"index\": 0, \"function\": {\"name\": \"get_wea\"}} then {\"index\": 0, \"function\": {\"arguments\": \"ther\"}}\n// google/anthropic send complete tool calls in single chunks, so they don't need this logic\nconst appendToolCalls = (toolCalls: any[], tcchunklist: any[]): any[] => {\n for (const tcchunk of tcchunklist) {\n while (toolCalls.length <= tcchunk.index) {\n toolCalls.push({\n id: \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n }\n const tc = toolCalls[tcchunk.index];\n tc.id += tcchunk.id || \"\";\n tc.function.name += tcchunk.function?.name || \"\";\n tc.function.arguments += tcchunk.function?.arguments || \"\";\n }\n return toolCalls;\n};\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") continue;\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: \"content\", content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n toolCalls = appendToolCalls(toolCalls, delta.tool_calls);\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nconst convertToAnthropicFormat = (messages: any[]): any[] => {\n const result: any[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n\n if (msg.role === \"system\") {\n i++;\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (msg.tool_calls) {\n result.push({\n role: \"assistant\",\n content: msg.tool_calls.map((tc: any) => ({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments),\n })),\n });\n } else {\n result.push({\n role: \"assistant\",\n content: msg.content,\n });\n }\n i++;\n } else if (msg.role === \"tool\") {\n const toolResults: any[] = [];\n while (i < messages.length && messages[i].role === \"tool\") {\n const toolMsg = messages[i];\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolMsg.tool_call_id,\n content: toolMsg.content,\n });\n i++;\n }\n result.push({\n role: \"user\",\n content: toolResults,\n });\n } else {\n result.push(msg);\n i++;\n }\n }\n\n return result;\n};\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n let system = instructions;\n\n if (ctx.history[0]?.role === \"system\") {\n system = ctx.history[0].content;\n }\n\n const messages = convertToAnthropicFormat(ctx.history);\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: \"\",\n },\n index: parsed.index,\n });\n }\n\n if (\n parsed.type === \"content_block_delta\" &&\n parsed.delta?.type === \"input_json_delta\"\n ) {\n const toolCall = toolCalls.find((tc) => tc.index === parsed.index);\n if (toolCall) {\n toolCall.function.arguments += parsed.delta.partial_json;\n }\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls.map(({ index, ...tc }) => tc);\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n \n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport {\n ConversationContext,\n StepFunction,\n ToolCall,\n JsonSchema,\n StandardSchema,\n ComposedFunction,\n} from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: {\n model?: string;\n schema?: JsonSchema | StandardSchema;\n} = {}): ComposedFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? // model()(\"hello!\");\n {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : // model()(/* few shot or history */);\n ctxOrMessage;\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n let currentCtx = ctx;\n\n do {\n currentCtx = await callProvider(\n { model, instructions, schema: normalizedSchema },\n currentCtx,\n );\n\n if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {\n currentCtx = await executeTools(currentCtx);\n }\n } while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_calls_ready\", calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n executeOnApproval = false,\n } = toolConfig;\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall, approved: boolean) => {\n if (!approved) {\n if (ctx.stream) {\n ctx.stream({\n type: \"tool_error\",\n call,\n error: \"Tool execution denied by user\",\n });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_executing\", call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: \"tool_complete\", call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n\n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return { call, result: { error } };\n };\n\n if (executeOnApproval && requireApproval) {\n const resultPromises = calls.map(async (call) => {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return runCall(call, approved);\n });\n\n const results = await Promise.all(resultPromises);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n }\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const runCallWithApproval = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n return runCall(call, approval?.approved ?? true);\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCallWithApproval))\n : await runCallsSequentially(calls, runCallWithApproval);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst threads = new Map<string, Thread>();\n\n/**\n * @example\n * // in-memory (default)\n * const thread = getOrCreateThread('user-123');\n *\n * @example\n * // sqlite\n * const thread = getOrCreateThread('user-123', {\n * async get(id) {\n * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);\n * return row ? JSON.parse(row.messages) : [];\n * },\n * async set(id, messages) {\n * await db.run(\n * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',\n * id,\n * JSON.stringify(messages),\n * Date.now()\n * );\n * }\n * });\n */\nexport const getOrCreateThread = (id: string, store?: ThreadStore): Thread => {\n const cacheKey = store ? `${id}-${store}` : id;\n\n if (threads.has(cacheKey)) {\n return threads.get(cacheKey)!;\n }\n\n const threadStore = store || createMemoryStore();\n const thread = createThread(id, threadStore);\n threads.set(cacheKey, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n\n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n if (config.stream) {\n scopedCtx.stream = config.stream;\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n","type RateLimitConfig = {\n rps: number;\n burst: number;\n concurrency: number;\n};\n\ntype QueueItem = {\n fn: () => Promise<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n};\n\n/**\n * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls\n * \n * @param config - rate limit configuration\n * @param config.rps - maximum requests per second\n * @param config.burst - maximum burst size (initial token bucket capacity)\n * @param config.concurrency - maximum concurrent in-flight requests\n * \n * @example\n * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });\n * \n * const workflow = limiter(\n * compose(\n * scope({ tools: [searchTool] }, model())\n * )\n * );\n * \n * await workflow(\"hello\");\n */\nexport const rateLimited =\n (config: RateLimitConfig) =>\n <T extends (...args: any[]) => Promise<any>>(fn: T): T => {\n const { rps, burst, concurrency } = config;\n\n let tokens = burst;\n let inFlight = 0;\n const queue: QueueItem[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n\n const refillTokens = () => {\n tokens = Math.min(tokens + 1, burst);\n processQueue();\n };\n\n const startInterval = () => {\n if (!intervalId) {\n intervalId = setInterval(refillTokens, 1000 / rps);\n }\n };\n\n const stopInterval = () => {\n if (intervalId && queue.length === 0 && inFlight === 0) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n const processQueue = () => {\n while (queue.length > 0 && tokens > 0 && inFlight < concurrency) {\n tokens--;\n inFlight++;\n\n const item = queue.shift()!;\n\n item\n .fn()\n .then((result) => {\n inFlight--;\n item.resolve(result);\n processQueue();\n stopInterval();\n })\n .catch((error) => {\n inFlight--;\n item.reject(error);\n processQueue();\n stopInterval();\n });\n }\n };\n\n return (async (...args: any[]) => {\n return new Promise((resolve, reject) => {\n queue.push({\n fn: () => fn(...args),\n resolve,\n reject,\n });\n startInterval();\n processQueue();\n });\n }) as T;\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;;;ACCA,iBAAgC;AAEzB,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AACf,QAAM,aAAa,aAAE,aAAa,cAAyB;AAC3D,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,EACV;AACF;AAEO,IAAM,+BAA+B,CAC1C,cACmC;AACnC,MAAI,CAAC,WAAW,WAAY,QAAO,CAAC;AAEpC,QAAM,SAAyC,CAAC;AAChD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,UAAU,GAAG;AAC/D,UAAM,OAAO;AACb,WAAO,GAAG,IAAI;AAAA,MACZ,MAAM,KAAK,QAAQ;AAAA,MACnB,aAAa,KAAK,eAAe;AAAA,MACjC,UAAU,CAAC,UAAU,UAAU,SAAS,GAAG;AAAA,MAC3C,GAAI,KAAK,QAAQ,EAAE,MAAM,KAAK,KAAK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AAAA,QACA;AAAA,MACF,CAAC;AACD,oBAAc;AACd,mBAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;","names":["Inherit","model","maxCalls","model","extractor","model","model","model","msg","model","model","maxCalls","error","results"]}
|
|
1
|
+
{"version":3,"sources":["../src/index.ts","../src/schema.ts","../src/mcp.ts","../src/types.ts","../src/utils.ts","../src/embed.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts","../src/utils/rateLimited.ts"],"sourcesContent":["export * from \"./mcp\";\nexport * from \"./types\";\nexport * from \"./utils\";\nexport * from \"./embed\";\nexport * from \"./thread\";\nexport * from \"./schema\";\nexport * from \"./helpers\";\nexport * from \"./approval\";\nexport * from \"./composition/tap\";\nexport * from \"./composition/when\";\nexport * from \"./composition/model\";\nexport * from \"./composition/retry\";\nexport * from \"./composition/scope\";\nexport * from \"./utils/rateLimited\";\nexport * from \"./composition/compose\";\n","import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\nimport { z, type ZodType } from \"zod\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return {\n name,\n schema: jsonSchema,\n };\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n ...(prop.enum && { enum: prop.enum }),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n\nexport const convertStandardSchemaToSchemaProperties = (\n standardSchema: StandardSchema,\n): Record<string, SchemaProperty> => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return convertMCPSchemaToToolSchema(jsonSchema);\n};\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty> | StandardSchema;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n /** require user approval before executing tools */\n requireApproval?: boolean;\n /**\n * custom callback to handle tool approval, return true to approve\n * \n * @example\n * // simple callback\n * approvalCallback: (call) => call.function.name !== 'dangerousTool'\n * \n * @example\n * // event-driven (SSE): server sends approval request, waits for client POST\n * approvalCallback: (call) => new Promise((resolve) => {\n * pendingApprovals.set(call.id, resolve);\n * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\\n\\n`);\n * })\n * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))\n */\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n /** execute tools in parallel instead of sequentially */\n parallel?: boolean;\n /** number of times to retry failed tool executions */\n retryCount?: number;\n /** identifier for approval requests, useful for managing multiple approval flows */\n approvalId?: string;\n /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */\n executeOnApproval?: boolean;\n}\n\nexport type StreamEvent =\n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n abortSignal?: AbortSignal;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n stream?: (event: StreamEvent) => void;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: Record<string, any>;\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n [key: string]: any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\nimport { isStandardSchema, convertStandardSchemaToSchemaProperties } from \"./schema\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const schema = isStandardSchema(tool.schema)\n ? convertStandardSchemaToSchemaProperties(tool.schema)\n : tool.schema;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { getKey } from \"./utils\";\n\nconst modelCache = new Map<string, any>();\n\n/**\n * generates embeddings for text using openai or huggingface models\n *\n * openai models use the prefix \"openai/\" (e.g., \"openai/text-embedding-3-small\")\n * all other models use huggingface transformers\n *\n * @example\n * const vector = await embed(\"openai/text-embedding-3-small\", \"hello world\");\n * const vector2 = await embed(\"Xenova/all-MiniLM-L6-v2\", \"hello world\");\n */\nexport const embed = async (\n model: string,\n text: string,\n config?: { dimensions?: number },\n): Promise<number[]> => {\n if (model.startsWith(\"openai/\")) {\n const modelName = model.replace(\"openai/\", \"\");\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const body: any = {\n model: modelName,\n input: text,\n };\n\n if (config?.dimensions) {\n body.dimensions = config.dimensions;\n }\n\n const response = await fetch(\"https://api.openai.com/v1/embeddings\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n const data = (await response.json()) as any;\n return data.data[0].embedding;\n }\n\n try {\n const { pipeline } = await import(\"@huggingface/transformers\");\n\n if (!modelCache.has(model)) {\n const extractor = await pipeline(\"feature-extraction\", model, {\n dtype: \"fp32\",\n });\n modelCache.set(model, extractor);\n }\n\n const extractor = modelCache.get(model);\n const result = await extractor(text, { pooling: \"mean\", normalize: true });\n return Array.from(result.data);\n } catch (error: any) {\n throw new Error(\n `huggingface transformers failed to load. install system dependencies or use openai models instead. original error: ${error.message}`,\n );\n }\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\n// openai streams tool calls as incremental chunks with index properties that need assembly\n// example: {\"index\": 0, \"function\": {\"name\": \"get_wea\"}} then {\"index\": 0, \"function\": {\"arguments\": \"ther\"}}\n// google/anthropic send complete tool calls in single chunks, so they don't need this logic\nconst appendToolCalls = (toolCalls: any[], tcchunklist: any[]): any[] => {\n for (const tcchunk of tcchunklist) {\n while (toolCalls.length <= tcchunk.index) {\n toolCalls.push({\n id: \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n }\n const tc = toolCalls[tcchunk.index];\n tc.id += tcchunk.id || \"\";\n tc.function.name += tcchunk.function?.name || \"\";\n tc.function.arguments += tcchunk.function?.arguments || \"\";\n }\n return toolCalls;\n};\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") continue;\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: \"content\", content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n toolCalls = appendToolCalls(toolCalls, delta.tool_calls);\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nconst convertToAnthropicFormat = (messages: any[]): any[] => {\n const result: any[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n\n if (msg.role === \"system\") {\n i++;\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (msg.tool_calls) {\n result.push({\n role: \"assistant\",\n content: msg.tool_calls.map((tc: any) => ({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments),\n })),\n });\n } else {\n result.push({\n role: \"assistant\",\n content: msg.content,\n });\n }\n i++;\n } else if (msg.role === \"tool\") {\n const toolResults: any[] = [];\n while (i < messages.length && messages[i].role === \"tool\") {\n const toolMsg = messages[i];\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolMsg.tool_call_id,\n content: toolMsg.content,\n });\n i++;\n }\n result.push({\n role: \"user\",\n content: toolResults,\n });\n } else {\n result.push(msg);\n i++;\n }\n }\n\n return result;\n};\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n let system = instructions;\n\n if (ctx.history[0]?.role === \"system\") {\n system = ctx.history[0].content;\n }\n\n const messages = convertToAnthropicFormat(ctx.history);\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: \"\",\n },\n index: parsed.index,\n });\n }\n\n if (\n parsed.type === \"content_block_delta\" &&\n parsed.delta?.type === \"input_json_delta\"\n ) {\n const toolCall = toolCalls.find((tc) => tc.index === parsed.index);\n if (toolCall) {\n toolCall.function.arguments += parsed.delta.partial_json;\n }\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls.map(({ index, ...tc }) => tc);\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n \n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport {\n ConversationContext,\n ToolCall,\n JsonSchema,\n StandardSchema,\n ComposedFunction,\n} from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: {\n model?: string;\n schema?: JsonSchema | StandardSchema;\n} = {}): ComposedFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? // model()(\"hello!\");\n {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : // model()(/* few shot or history */);\n ctxOrMessage;\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n let currentCtx = ctx;\n\n do {\n if (currentCtx.abortSignal?.aborted) {\n break;\n }\n\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 (\n currentCtx.lastResponse?.tool_calls &&\n currentCtx.tools?.length &&\n !currentCtx.abortSignal?.aborted\n );\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_calls_ready\", calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n executeOnApproval = false,\n } = toolConfig;\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall, approved: boolean) => {\n if (!approved) {\n if (ctx.stream) {\n ctx.stream({\n type: \"tool_error\",\n call,\n error: \"Tool execution denied by user\",\n });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_executing\", call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: \"tool_complete\", call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n\n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return { call, result: { error } };\n };\n\n if (executeOnApproval && requireApproval) {\n const resultPromises = calls.map(async (call) => {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return runCall(call, approved);\n });\n\n const results = await Promise.all(resultPromises);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n }\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const runCallWithApproval = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n return runCall(call, approval?.approved ?? true);\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCallWithApproval))\n : await runCallsSequentially(calls, runCallWithApproval);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst threads = new Map<string, Thread>();\n\n/**\n * @example\n * // in-memory (default)\n * const thread = getOrCreateThread('user-123');\n *\n * @example\n * // sqlite\n * const thread = getOrCreateThread('user-123', {\n * async get(id) {\n * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);\n * return row ? JSON.parse(row.messages) : [];\n * },\n * async set(id, messages) {\n * await db.run(\n * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',\n * id,\n * JSON.stringify(messages),\n * Date.now()\n * );\n * }\n * });\n */\nexport const getOrCreateThread = (id: string, store?: ThreadStore): Thread => {\n const cacheKey = store ? `${id}-${store}` : id;\n\n if (threads.has(cacheKey)) {\n return threads.get(cacheKey)!;\n }\n\n const threadStore = store || createMemoryStore();\n const thread = createThread(id, threadStore);\n threads.set(cacheKey, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n\n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n scopedCtx.abortSignal = ctx.abortSignal;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n if (config.stream) {\n scopedCtx.stream = config.stream;\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n","type RateLimitConfig = {\n rps: number;\n burst: number;\n concurrency: number;\n};\n\ntype QueueItem = {\n fn: () => Promise<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n};\n\n/**\n * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls\n *\n * @param config - rate limit configuration\n * @param config.rps - maximum requests per second\n * @param config.burst - maximum burst size (initial token bucket capacity)\n * @param config.concurrency - maximum concurrent in-flight requests\n *\n * @example\n * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });\n *\n * const workflow = limiter(\n * compose(\n * scope({ tools: [searchTool] }, model())\n * )\n * );\n *\n * await workflow(\"hello\");\n */\nexport const rateLimited =\n (config: RateLimitConfig) =>\n <T extends (...args: any[]) => Promise<any>>(fn: T): T => {\n const { rps, burst, concurrency } = config;\n\n let tokens = burst;\n let inFlight = 0;\n const queue: QueueItem[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n\n const refillTokens = () => {\n tokens = Math.min(tokens + 1, burst);\n processQueue();\n };\n\n const startInterval = () => {\n if (!intervalId) {\n intervalId = setInterval(refillTokens, 1000 / rps);\n }\n };\n\n const stopInterval = () => {\n if (intervalId && queue.length === 0 && inFlight === 0) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n const processQueue = () => {\n while (queue.length > 0 && tokens > 0 && inFlight < concurrency) {\n tokens--;\n inFlight++;\n\n const item = queue.shift()!;\n\n item\n .fn()\n .then((result) => {\n inFlight--;\n item.resolve(result);\n processQueue();\n stopInterval();\n })\n .catch((error) => {\n inFlight--;\n item.reject(error);\n processQueue();\n stopInterval();\n });\n }\n };\n\n return (async (...args: any[]) => {\n return new Promise((resolve, reject) => {\n queue.push({\n fn: () => fn(...args),\n resolve,\n reject,\n });\n startInterval();\n processQueue();\n });\n }) as T;\n };\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;;;AAAA;AAAA;AAAA;AAAA;AAAA;AAAA;AAA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AI;AAAA,QACpB;AAAA,QACA;AAAA,MACF,CAAC;AACD,oBAAc;AACd,mBAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;","names":["Inherit","model","maxCalls","model","extractor","model","model","model","msg","model","model","maxCalls","error","results"]}
|
package/dist/index.d.cts
CHANGED
package/dist/index.d.ts
CHANGED
package/dist/index.js
CHANGED
|
@@ -142,7 +142,6 @@ var maxCalls = (toolConfig, maxCalls2) => ({
|
|
|
142
142
|
});
|
|
143
143
|
|
|
144
144
|
// src/embed.ts
|
|
145
|
-
import { pipeline } from "@huggingface/transformers";
|
|
146
145
|
var modelCache = /* @__PURE__ */ new Map();
|
|
147
146
|
var embed = async (model2, text, config) => {
|
|
148
147
|
if (model2.startsWith("openai/")) {
|
|
@@ -173,15 +172,22 @@ var embed = async (model2, text, config) => {
|
|
|
173
172
|
const data = await response.json();
|
|
174
173
|
return data.data[0].embedding;
|
|
175
174
|
}
|
|
176
|
-
|
|
177
|
-
const
|
|
178
|
-
|
|
179
|
-
|
|
180
|
-
|
|
175
|
+
try {
|
|
176
|
+
const { pipeline } = await import("@huggingface/transformers");
|
|
177
|
+
if (!modelCache.has(model2)) {
|
|
178
|
+
const extractor2 = await pipeline("feature-extraction", model2, {
|
|
179
|
+
dtype: "fp32"
|
|
180
|
+
});
|
|
181
|
+
modelCache.set(model2, extractor2);
|
|
182
|
+
}
|
|
183
|
+
const extractor = modelCache.get(model2);
|
|
184
|
+
const result = await extractor(text, { pooling: "mean", normalize: true });
|
|
185
|
+
return Array.from(result.data);
|
|
186
|
+
} catch (error) {
|
|
187
|
+
throw new Error(
|
|
188
|
+
`huggingface transformers failed to load. install system dependencies or use openai models instead. original error: ${error.message}`
|
|
189
|
+
);
|
|
181
190
|
}
|
|
182
|
-
const extractor = modelCache.get(model2);
|
|
183
|
-
const result = await extractor(text, { pooling: "mean", normalize: true });
|
|
184
|
-
return Array.from(result.data);
|
|
185
191
|
};
|
|
186
192
|
|
|
187
193
|
// src/providers/openai.ts
|
|
@@ -237,7 +243,8 @@ var callOpenAI = async (config, ctx) => {
|
|
|
237
243
|
"Content-Type": "application/json",
|
|
238
244
|
Authorization: `Bearer ${apiKey}`
|
|
239
245
|
},
|
|
240
|
-
body: JSON.stringify(body)
|
|
246
|
+
body: JSON.stringify(body),
|
|
247
|
+
signal: ctx.abortSignal
|
|
241
248
|
});
|
|
242
249
|
if (!response.ok) {
|
|
243
250
|
const error = await response.text();
|
|
@@ -270,6 +277,9 @@ var handleOpenAIStream = async (response, ctx) => {
|
|
|
270
277
|
let buffer = "";
|
|
271
278
|
try {
|
|
272
279
|
while (true) {
|
|
280
|
+
if (ctx.abortSignal?.aborted) {
|
|
281
|
+
break;
|
|
282
|
+
}
|
|
273
283
|
const { done, value } = await reader.read();
|
|
274
284
|
if (done) break;
|
|
275
285
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -411,7 +421,8 @@ Return only the JSON object, no other text or formatting.`;
|
|
|
411
421
|
"x-api-key": apiKey,
|
|
412
422
|
"anthropic-version": "2023-06-01"
|
|
413
423
|
},
|
|
414
|
-
body: JSON.stringify(body)
|
|
424
|
+
body: JSON.stringify(body),
|
|
425
|
+
signal: ctx.abortSignal
|
|
415
426
|
});
|
|
416
427
|
if (!response.ok) {
|
|
417
428
|
const error = await response.text();
|
|
@@ -452,6 +463,9 @@ var handleAnthropicStream = async (response, ctx) => {
|
|
|
452
463
|
let buffer = "";
|
|
453
464
|
try {
|
|
454
465
|
while (true) {
|
|
466
|
+
if (ctx.abortSignal?.aborted) {
|
|
467
|
+
break;
|
|
468
|
+
}
|
|
455
469
|
const { done, value } = await reader.read();
|
|
456
470
|
if (done) break;
|
|
457
471
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -556,7 +570,8 @@ var callGoogle = async (config, ctx) => {
|
|
|
556
570
|
headers: {
|
|
557
571
|
"Content-Type": "application/json"
|
|
558
572
|
},
|
|
559
|
-
body: JSON.stringify(body)
|
|
573
|
+
body: JSON.stringify(body),
|
|
574
|
+
signal: ctx.abortSignal
|
|
560
575
|
}
|
|
561
576
|
);
|
|
562
577
|
if (!response.ok) {
|
|
@@ -599,6 +614,9 @@ var handleGoogleStream = async (response, ctx) => {
|
|
|
599
614
|
let buffer = "";
|
|
600
615
|
try {
|
|
601
616
|
while (true) {
|
|
617
|
+
if (ctx.abortSignal?.aborted) {
|
|
618
|
+
break;
|
|
619
|
+
}
|
|
602
620
|
const { done, value } = await reader.read();
|
|
603
621
|
if (done) break;
|
|
604
622
|
buffer += decoder.decode(value, { stream: true });
|
|
@@ -730,6 +748,9 @@ var model = ({
|
|
|
730
748
|
const instructions = systemMessage?.content;
|
|
731
749
|
let currentCtx = ctx;
|
|
732
750
|
do {
|
|
751
|
+
if (currentCtx.abortSignal?.aborted) {
|
|
752
|
+
break;
|
|
753
|
+
}
|
|
733
754
|
currentCtx = await callProvider(
|
|
734
755
|
{ model: model2, instructions, schema: normalizedSchema },
|
|
735
756
|
currentCtx
|
|
@@ -737,7 +758,7 @@ var model = ({
|
|
|
737
758
|
if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {
|
|
738
759
|
currentCtx = await executeTools(currentCtx);
|
|
739
760
|
}
|
|
740
|
-
} while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);
|
|
761
|
+
} while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length && !currentCtx.abortSignal?.aborted);
|
|
741
762
|
return currentCtx;
|
|
742
763
|
};
|
|
743
764
|
};
|
|
@@ -1135,6 +1156,7 @@ var scopeContext = (config, ctx) => {
|
|
|
1135
1156
|
scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : void 0;
|
|
1136
1157
|
}
|
|
1137
1158
|
scopedCtx.stream = ctx.stream;
|
|
1159
|
+
scopedCtx.abortSignal = ctx.abortSignal;
|
|
1138
1160
|
if (config.tools) {
|
|
1139
1161
|
const toolDefinitions = config.tools.map(toolConfigToToolDefinition);
|
|
1140
1162
|
const toolExecutors = config.tools.reduce(
|
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/embed.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts","../src/utils/rateLimited.ts"],"sourcesContent":["import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\nimport { z, type ZodType } from \"zod\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return {\n name,\n schema: jsonSchema,\n };\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n ...(prop.enum && { enum: prop.enum }),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n\nexport const convertStandardSchemaToSchemaProperties = (\n standardSchema: StandardSchema,\n): Record<string, SchemaProperty> => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return convertMCPSchemaToToolSchema(jsonSchema);\n};\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty> | StandardSchema;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n /** require user approval before executing tools */\n requireApproval?: boolean;\n /**\n * custom callback to handle tool approval, return true to approve\n * \n * @example\n * // simple callback\n * approvalCallback: (call) => call.function.name !== 'dangerousTool'\n * \n * @example\n * // event-driven (SSE): server sends approval request, waits for client POST\n * approvalCallback: (call) => new Promise((resolve) => {\n * pendingApprovals.set(call.id, resolve);\n * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\\n\\n`);\n * })\n * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))\n */\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n /** execute tools in parallel instead of sequentially */\n parallel?: boolean;\n /** number of times to retry failed tool executions */\n retryCount?: number;\n /** identifier for approval requests, useful for managing multiple approval flows */\n approvalId?: string;\n /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */\n executeOnApproval?: boolean;\n}\n\nexport type StreamEvent =\n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n stream?: (event: StreamEvent) => void;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: Record<string, any>;\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n [key: string]: any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\nimport { isStandardSchema, convertStandardSchemaToSchemaProperties } from \"./schema\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const schema = isStandardSchema(tool.schema)\n ? convertStandardSchemaToSchemaProperties(tool.schema)\n : tool.schema;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { pipeline } from \"@huggingface/transformers\";\nimport { getKey } from \"./utils\";\n\nconst modelCache = new Map<string, any>();\n\n/**\n * generates embeddings for text using openai or huggingface models\n *\n * openai models use the prefix \"openai/\" (e.g., \"openai/text-embedding-3-small\")\n * all other models use huggingface transformers\n *\n * @example\n * const vector = await embed(\"openai/text-embedding-3-small\", \"hello world\");\n * const vector2 = await embed(\"Xenova/all-MiniLM-L6-v2\", \"hello world\");\n */\nexport const embed = async (\n model: string,\n text: string,\n config?: { dimensions?: number },\n): Promise<number[]> => {\n if (model.startsWith(\"openai/\")) {\n const modelName = model.replace(\"openai/\", \"\");\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const body: any = {\n model: modelName,\n input: text,\n };\n\n if (config?.dimensions) {\n body.dimensions = config.dimensions;\n }\n\n const response = await fetch(\"https://api.openai.com/v1/embeddings\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n const data = (await response.json()) as any;\n return data.data[0].embedding;\n }\n\n if (!modelCache.has(model)) {\n const extractor = await pipeline(\"feature-extraction\", model, {\n dtype: \"fp32\",\n });\n modelCache.set(model, extractor);\n }\n\n const extractor = modelCache.get(model);\n const result = await extractor(text, { pooling: \"mean\", normalize: true });\n return Array.from(result.data);\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\n// openai streams tool calls as incremental chunks with index properties that need assembly\n// example: {\"index\": 0, \"function\": {\"name\": \"get_wea\"}} then {\"index\": 0, \"function\": {\"arguments\": \"ther\"}}\n// google/anthropic send complete tool calls in single chunks, so they don't need this logic\nconst appendToolCalls = (toolCalls: any[], tcchunklist: any[]): any[] => {\n for (const tcchunk of tcchunklist) {\n while (toolCalls.length <= tcchunk.index) {\n toolCalls.push({\n id: \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n }\n const tc = toolCalls[tcchunk.index];\n tc.id += tcchunk.id || \"\";\n tc.function.name += tcchunk.function?.name || \"\";\n tc.function.arguments += tcchunk.function?.arguments || \"\";\n }\n return toolCalls;\n};\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") continue;\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: \"content\", content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n toolCalls = appendToolCalls(toolCalls, delta.tool_calls);\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nconst convertToAnthropicFormat = (messages: any[]): any[] => {\n const result: any[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n\n if (msg.role === \"system\") {\n i++;\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (msg.tool_calls) {\n result.push({\n role: \"assistant\",\n content: msg.tool_calls.map((tc: any) => ({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments),\n })),\n });\n } else {\n result.push({\n role: \"assistant\",\n content: msg.content,\n });\n }\n i++;\n } else if (msg.role === \"tool\") {\n const toolResults: any[] = [];\n while (i < messages.length && messages[i].role === \"tool\") {\n const toolMsg = messages[i];\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolMsg.tool_call_id,\n content: toolMsg.content,\n });\n i++;\n }\n result.push({\n role: \"user\",\n content: toolResults,\n });\n } else {\n result.push(msg);\n i++;\n }\n }\n\n return result;\n};\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n let system = instructions;\n\n if (ctx.history[0]?.role === \"system\") {\n system = ctx.history[0].content;\n }\n\n const messages = convertToAnthropicFormat(ctx.history);\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: \"\",\n },\n index: parsed.index,\n });\n }\n\n if (\n parsed.type === \"content_block_delta\" &&\n parsed.delta?.type === \"input_json_delta\"\n ) {\n const toolCall = toolCalls.find((tc) => tc.index === parsed.index);\n if (toolCall) {\n toolCall.function.arguments += parsed.delta.partial_json;\n }\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls.map(({ index, ...tc }) => tc);\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n \n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport {\n ConversationContext,\n StepFunction,\n ToolCall,\n JsonSchema,\n StandardSchema,\n ComposedFunction,\n} from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: {\n model?: string;\n schema?: JsonSchema | StandardSchema;\n} = {}): ComposedFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? // model()(\"hello!\");\n {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : // model()(/* few shot or history */);\n ctxOrMessage;\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n let currentCtx = ctx;\n\n do {\n currentCtx = await callProvider(\n { model, instructions, schema: normalizedSchema },\n currentCtx,\n );\n\n if (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length) {\n currentCtx = await executeTools(currentCtx);\n }\n } while (currentCtx.lastResponse?.tool_calls && currentCtx.tools?.length);\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_calls_ready\", calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n executeOnApproval = false,\n } = toolConfig;\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall, approved: boolean) => {\n if (!approved) {\n if (ctx.stream) {\n ctx.stream({\n type: \"tool_error\",\n call,\n error: \"Tool execution denied by user\",\n });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_executing\", call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: \"tool_complete\", call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n\n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return { call, result: { error } };\n };\n\n if (executeOnApproval && requireApproval) {\n const resultPromises = calls.map(async (call) => {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return runCall(call, approved);\n });\n\n const results = await Promise.all(resultPromises);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n }\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const runCallWithApproval = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n return runCall(call, approval?.approved ?? true);\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCallWithApproval))\n : await runCallsSequentially(calls, runCallWithApproval);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst threads = new Map<string, Thread>();\n\n/**\n * @example\n * // in-memory (default)\n * const thread = getOrCreateThread('user-123');\n *\n * @example\n * // sqlite\n * const thread = getOrCreateThread('user-123', {\n * async get(id) {\n * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);\n * return row ? JSON.parse(row.messages) : [];\n * },\n * async set(id, messages) {\n * await db.run(\n * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',\n * id,\n * JSON.stringify(messages),\n * Date.now()\n * );\n * }\n * });\n */\nexport const getOrCreateThread = (id: string, store?: ThreadStore): Thread => {\n const cacheKey = store ? `${id}-${store}` : id;\n\n if (threads.has(cacheKey)) {\n return threads.get(cacheKey)!;\n }\n\n const threadStore = store || createMemoryStore();\n const thread = createThread(id, threadStore);\n threads.set(cacheKey, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n\n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n if (config.stream) {\n scopedCtx.stream = config.stream;\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n","type RateLimitConfig = {\n rps: number;\n burst: number;\n concurrency: number;\n};\n\ntype QueueItem = {\n fn: () => Promise<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n};\n\n/**\n * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls\n * \n * @param config - rate limit configuration\n * @param config.rps - maximum requests per second\n * @param config.burst - maximum burst size (initial token bucket capacity)\n * @param config.concurrency - maximum concurrent in-flight requests\n * \n * @example\n * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });\n * \n * const workflow = limiter(\n * compose(\n * scope({ tools: [searchTool] }, model())\n * )\n * );\n * \n * await workflow(\"hello\");\n */\nexport const rateLimited =\n (config: RateLimitConfig) =>\n <T extends (...args: any[]) => Promise<any>>(fn: T): T => {\n const { rps, burst, concurrency } = config;\n\n let tokens = burst;\n let inFlight = 0;\n const queue: QueueItem[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n\n const refillTokens = () => {\n tokens = Math.min(tokens + 1, burst);\n processQueue();\n };\n\n const startInterval = () => {\n if (!intervalId) {\n intervalId = setInterval(refillTokens, 1000 / rps);\n }\n };\n\n const stopInterval = () => {\n if (intervalId && queue.length === 0 && inFlight === 0) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n const processQueue = () => {\n while (queue.length > 0 && tokens > 0 && inFlight < concurrency) {\n tokens--;\n inFlight++;\n\n const item = queue.shift()!;\n\n item\n .fn()\n .then((result) => {\n inFlight--;\n item.resolve(result);\n processQueue();\n stopInterval();\n })\n .catch((error) => {\n inFlight--;\n item.reject(error);\n processQueue();\n stopInterval();\n });\n }\n };\n\n return (async (...args: any[]) => {\n return new Promise((resolve, reject) => {\n queue.push({\n fn: () => fn(...args),\n resolve,\n reject,\n });\n startInterval();\n processQueue();\n });\n }) as T;\n };\n"],"mappings":";AACA,SAAS,SAAuB;AAEzB,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AACf,QAAM,aAAa,EAAE,aAAa,cAAyB;AAC3D,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,EACV;AACF;AAEO,IAAM,+BAA+B,CAC1C,cACmC;AACnC,MAAI,CAAC,WAAW,WAAY,QAAO,CAAC;AAEpC,QAAM,SAAyC,CAAC;AAChD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,UAAU,GAAG;AAC/D,UAAM,OAAO;AACb,WAAO,GAAG,IAAI;AAAA,MACZ,MAAM,KAAK,QAAQ;AAAA,MACnB,aAAa,KAAK,eAAe;AAAA,MACjC,UAAU,CAAC,UAAU,UAAU,SAAS,GAAG;AAAA,MAC3C,GAAI,KAAK,QAAQ,EAAE,MAAM,KAAK,KAAK;AAAA,IACrC;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;AAEO,IAAM,0CAA0C,CACrD,mBAC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D,YAAY,OAAO,SAAS,IAAI,aAAa,UAAU;AAAA,IACzD;AAAA,EACF;AACF;;;AChFO,IAAM,cACX,CAAC,WACD,CAA6C,OAAa;AACxD,QAAM,EAAE,KAAK,OAAO,YAAY,IAAI;AAEpC,MAAI,SAAS;AACb,MAAI,WAAW;AACf,QAAM,QAAqB,CAAC;AAC5B,MAAI,aAAoC;AAExC,QAAM,eAAe,MAAM;AACzB,aAAS,KAAK,IAAI,SAAS,GAAG,KAAK;AACnC,iBAAa;AAAA,EACf;AAEA,QAAM,gBAAgB,MAAM;AAC1B,QAAI,CAAC,YAAY;AACf,mBAAa,YAAY,cAAc,MAAO,GAAG;AAAA,IACnD;AAAA,EACF;AAEA,QAAM,eAAe,MAAM;AACzB,QAAI,cAAc,MAAM,WAAW,KAAK,aAAa,GAAG;AACtD,oBAAc,UAAU;AACxB,mBAAa;AAAA,IACf;AAAA,EACF;AAEA,QAAM,eAAe,MAAM;AACzB,WAAO,MAAM,SAAS,KAAK,SAAS,KAAK,WAAW,aAAa;AAC/D;AACA;AAEA,YAAM,OAAO,MAAM,MAAM;AAEzB,WACG,GAAG,EACH,KAAK,CAAC,WAAW;AAChB;AACA,aAAK,QAAQ,MAAM;AACnB,qBAAa;AACb,qBAAa;AAAA,MACf,CAAC,EACA,MAAM,CAAC,UAAU;AAChB;AACA,aAAK,OAAO,KAAK;AACjB,qBAAa;AACb,qBAAa;AAAA,MACf,CAAC;AAAA,IACL;AAAA,EACF;AAEA,UAAQ,UAAU,SAAgB;AAChC,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK;AAAA,QACT,IAAI,MAAM,GAAG,GAAG,IAAI;AAAA,QACpB;AAAA,QACA;AAAA,MACF,CAAC;AACD,oBAAc;AACd,mBAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;","names":["Inherit","model","maxCalls","model","extractor","model","model","model","msg","model","model","maxCalls","error","results"]}
|
|
1
|
+
{"version":3,"sources":["../src/schema.ts","../src/mcp.ts","../src/types.ts","../src/utils.ts","../src/embed.ts","../src/providers/openai.ts","../src/providers/anthropic.ts","../src/providers/google.ts","../src/providers/huggingface.ts","../src/providers/index.ts","../src/approval.ts","../src/composition/model.ts","../src/thread.ts","../src/composition/when.ts","../src/helpers.ts","../src/composition/tap.ts","../src/composition/retry.ts","../src/composition/compose.ts","../src/composition/scope.ts","../src/utils/rateLimited.ts"],"sourcesContent":["import { JsonSchema, SchemaProperty, StandardSchema } from \"./types\";\nimport { z, type ZodType } from \"zod\";\n\nexport const isStandardSchema = (schema: any): schema is StandardSchema => {\n return schema && typeof schema === \"object\" && \"~standard\" in schema;\n};\n\nexport const convertStandardSchemaToJsonSchema = (\n standardSchema: StandardSchema,\n name: string = \"Schema\",\n): JsonSchema => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return {\n name,\n schema: jsonSchema,\n };\n};\n\nexport const convertMCPSchemaToToolSchema = (\n mcpSchema: any,\n): Record<string, SchemaProperty> => {\n if (!mcpSchema?.properties) return {};\n\n const result: Record<string, SchemaProperty> = {};\n for (const [key, value] of Object.entries(mcpSchema.properties)) {\n const prop = value as any;\n result[key] = {\n type: prop.type || \"string\",\n description: prop.description || \"\",\n optional: !mcpSchema.required?.includes(key),\n ...(prop.enum && { enum: prop.enum }),\n };\n }\n return result;\n};\n\nexport function normalizeSchema(\n schema: JsonSchema | StandardSchema,\n name?: string,\n): JsonSchema {\n if (isStandardSchema(schema)) {\n return convertStandardSchemaToJsonSchema(schema, name);\n }\n return schema as JsonSchema;\n}\n\nexport const convertStandardSchemaToSchemaProperties = (\n standardSchema: StandardSchema,\n): Record<string, SchemaProperty> => {\n const jsonSchema = z.toJSONSchema(standardSchema as ZodType);\n return convertMCPSchemaToToolSchema(jsonSchema);\n};\n","import { Client } from \"@modelcontextprotocol/sdk/client/index\";\nimport { ToolConfig } from \"./types\";\nimport { convertMCPSchemaToToolSchema } from \"./schema\";\n\nexport const createMCPTools = async (client: Client): Promise<ToolConfig[]> => {\n const serverInfo = client.getServerVersion();\n const serverName = serverInfo?.name;\n\n if (!serverName) {\n console.error(\"MCP server has no name? Skipping tool creation.\");\n return [];\n }\n\n const toolsResponse = await client.listTools();\n\n return toolsResponse.tools.map((mcpTool) => {\n const prefixedName = `${serverName}_${mcpTool.name}`;\n\n return {\n name: prefixedName,\n description: `[${serverName}] ${mcpTool.description || \"\"}`,\n schema: convertMCPSchemaToToolSchema(mcpTool.inputSchema),\n execute: async (args: any) => {\n const result = await client.callTool({\n name: mcpTool.name,\n arguments: args,\n });\n return (\n (result.content &&\n Array.isArray(result.content) &&\n result.content[0]?.text) ||\n JSON.stringify(result)\n );\n },\n };\n });\n};\n","export interface Message {\n role: \"system\" | \"user\" | \"assistant\" | \"tool\";\n content: string;\n tool_call_id?: string;\n}\n\nexport interface ToolCall {\n id: string;\n function: {\n name: string;\n arguments: string;\n };\n}\n\nexport interface ToolCallResult {\n name: string;\n inputs: any;\n results: any;\n}\n\nexport interface ToolDefinition {\n type: \"function\";\n function: {\n name: string;\n description: string;\n parameters: {\n type: string;\n properties: Record<string, any>;\n required?: string[];\n };\n };\n}\n\nexport interface ToolConfig {\n name: string;\n description: string;\n schema: Record<string, SchemaProperty> | StandardSchema;\n execute: (args: any) => Promise<any> | any;\n _maxCalls?: number;\n}\n\nexport interface SchemaProperty {\n type: \"string\" | \"number\" | \"boolean\" | \"array\" | \"object\";\n description?: string;\n enum?: string[];\n optional?: boolean;\n items?: SchemaProperty;\n properties?: Record<string, SchemaProperty>;\n}\n\nexport interface ToolExecutionConfig {\n /** require user approval before executing tools */\n requireApproval?: boolean;\n /**\n * custom callback to handle tool approval, return true to approve\n * \n * @example\n * // simple callback\n * approvalCallback: (call) => call.function.name !== 'dangerousTool'\n * \n * @example\n * // event-driven (SSE): server sends approval request, waits for client POST\n * approvalCallback: (call) => new Promise((resolve) => {\n * pendingApprovals.set(call.id, resolve);\n * res.write(`data: ${JSON.stringify({ type: 'approval_needed', call })}\\n\\n`);\n * })\n * // then: app.post('/approve/:id', (req) => pendingApprovals.get(id)(req.body.approved))\n */\n approvalCallback?: (call: ToolCall) => boolean | Promise<boolean>;\n /** execute tools in parallel instead of sequentially */\n parallel?: boolean;\n /** number of times to retry failed tool executions */\n retryCount?: number;\n /** identifier for approval requests, useful for managing multiple approval flows */\n approvalId?: string;\n /** execute tools immediately upon approval instead of waiting for all approvals (default: false, only applies when requireApproval is true) */\n executeOnApproval?: boolean;\n}\n\nexport type StreamEvent =\n | { type: 'content'; content: string }\n | { type: 'tool_calls_ready'; calls: ToolCall[] }\n | { type: 'tool_executing'; call: ToolCall }\n | { type: 'tool_complete'; call: ToolCall; result: any }\n | { type: 'tool_error'; call: ToolCall; error: string }\n | { type: 'approval_requested'; call: ToolCall; requestId: string };\n\nexport interface ConversationContext {\n history: Message[];\n lastRequest?: Message;\n lastResponse?: Message & { tool_calls?: ToolCall[] };\n tools?: ToolDefinition[];\n toolExecutors?: Record<string, Function>;\n stream?: (event: StreamEvent) => void;\n stopReason?: string;\n\n toolCallCounts?: Record<string, number>;\n toolLimits?: Record<string, number>;\n toolConfig?: ToolExecutionConfig;\n abortSignal?: AbortSignal;\n}\n\nexport enum Inherit {\n Nothing = 0,\n Conversation = 1 << 0,\n Tools = 1 << 1,\n All = Conversation | Tools,\n}\n\nexport interface ScopeConfig {\n inherit?: number;\n tools?: ToolConfig[];\n toolConfig?: ToolExecutionConfig;\n system?: string;\n silent?: boolean;\n until?: (ctx: ConversationContext) => boolean;\n stream?: (event: StreamEvent) => void;\n}\n\nexport type StepFunction = (\n ctx: ConversationContext,\n) => Promise<ConversationContext>;\nexport type ComposedFunction = (\n ctxOrMessage: ConversationContext | string,\n) => Promise<ConversationContext>;\n\nexport interface JsonSchema {\n name: string;\n schema: Record<string, any>;\n}\n\nexport interface StandardSchema {\n \"~standard\": any;\n [key: string]: any;\n}\n\nexport interface ProviderConfig {\n model: string;\n instructions?: string;\n schema?: JsonSchema;\n}\n\nexport interface ParsedModel {\n provider: string;\n model: string;\n}\n\nexport interface ApiKeys {\n openai?: string;\n anthropic?: string;\n google?: string;\n [provider: string]: string | undefined;\n}\n\nexport interface ThreadStore {\n get(threadId: string): Promise<Message[]>;\n set(threadId: string, messages: Message[]): Promise<void>;\n}\n\nexport interface Thread {\n id: string;\n store: ThreadStore;\n generate(step: StepFunction): Promise<ConversationContext>;\n message(content: string, workflow?: StepFunction): Promise<ConversationContext>;\n}\n\nexport interface RetryOptions {\n times?: number;\n}\n","import {\n ApiKeys,\n ParsedModel,\n SchemaProperty,\n ToolConfig,\n ToolDefinition,\n} from \"./types\";\nimport { isStandardSchema, convertStandardSchemaToSchemaProperties } from \"./schema\";\n\nexport const toolConfigToToolDefinition = (\n tool: ToolConfig,\n): ToolDefinition => {\n const schema = isStandardSchema(tool.schema)\n ? convertStandardSchemaToSchemaProperties(tool.schema)\n : tool.schema;\n\n const properties: Record<string, any> = {};\n const required: string[] = [];\n\n for (const [key, prop] of Object.entries(schema)) {\n properties[key] = convertSchemaProperty(prop);\n if (!prop.optional) {\n required.push(key);\n }\n }\n\n return {\n type: \"function\",\n function: {\n name: tool.name,\n description: tool.description,\n parameters: {\n type: \"object\",\n properties,\n ...(required.length > 0 && { required }),\n },\n },\n };\n};\n\nconst convertSchemaProperty = (prop: SchemaProperty): any => {\n const result: any = {\n type: prop.type,\n };\n\n if (prop.description) {\n result.description = prop.description;\n }\n\n if (prop.enum) {\n result.enum = prop.enum;\n }\n\n if (prop.items) {\n result.items = convertSchemaProperty(prop.items);\n }\n\n if (prop.properties) {\n result.properties = {};\n for (const [key, childProp] of Object.entries(prop.properties)) {\n result.properties[key] = convertSchemaProperty(childProp);\n }\n }\n\n return result;\n};\n\nexport const parseModelName = (model: string): ParsedModel => {\n const parts = model.split(\"/\");\n\n if (parts.length === 1) {\n return { provider: \"huggingface\", model: parts[0] };\n }\n\n return {\n provider: parts[0],\n model: parts.slice(1).join(\"/\"),\n };\n};\n\nlet globalKeys: ApiKeys = {};\n\nexport const setKeys = (keys: ApiKeys): void => {\n globalKeys = { ...globalKeys, ...keys };\n};\n\nexport const getKey = (provider: string): string => {\n const key = globalKeys[provider.toLowerCase()];\n if (!key) {\n throw new Error(`No API key configured for provider: ${provider}`);\n }\n return key;\n};\n\nexport const maxCalls = (toolConfig: ToolConfig, maxCalls: number): ToolConfig => ({\n ...toolConfig,\n _maxCalls: maxCalls,\n});\n","import { getKey } from \"./utils\";\n\nconst modelCache = new Map<string, any>();\n\n/**\n * generates embeddings for text using openai or huggingface models\n *\n * openai models use the prefix \"openai/\" (e.g., \"openai/text-embedding-3-small\")\n * all other models use huggingface transformers\n *\n * @example\n * const vector = await embed(\"openai/text-embedding-3-small\", \"hello world\");\n * const vector2 = await embed(\"Xenova/all-MiniLM-L6-v2\", \"hello world\");\n */\nexport const embed = async (\n model: string,\n text: string,\n config?: { dimensions?: number },\n): Promise<number[]> => {\n if (model.startsWith(\"openai/\")) {\n const modelName = model.replace(\"openai/\", \"\");\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const body: any = {\n model: modelName,\n input: text,\n };\n\n if (config?.dimensions) {\n body.dimensions = config.dimensions;\n }\n\n const response = await fetch(\"https://api.openai.com/v1/embeddings\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n const data = (await response.json()) as any;\n return data.data[0].embedding;\n }\n\n try {\n const { pipeline } = await import(\"@huggingface/transformers\");\n\n if (!modelCache.has(model)) {\n const extractor = await pipeline(\"feature-extraction\", model, {\n dtype: \"fp32\",\n });\n modelCache.set(model, extractor);\n }\n\n const extractor = modelCache.get(model);\n const result = await extractor(text, { pooling: \"mean\", normalize: true });\n return Array.from(result.data);\n } catch (error: any) {\n throw new Error(\n `huggingface transformers failed to load. install system dependencies or use openai models instead. original error: ${error.message}`,\n );\n }\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\n// openai streams tool calls as incremental chunks with index properties that need assembly\n// example: {\"index\": 0, \"function\": {\"name\": \"get_wea\"}} then {\"index\": 0, \"function\": {\"arguments\": \"ther\"}}\n// google/anthropic send complete tool calls in single chunks, so they don't need this logic\nconst appendToolCalls = (toolCalls: any[], tcchunklist: any[]): any[] => {\n for (const tcchunk of tcchunklist) {\n while (toolCalls.length <= tcchunk.index) {\n toolCalls.push({\n id: \"\",\n type: \"function\",\n function: { name: \"\", arguments: \"\" },\n });\n }\n const tc = toolCalls[tcchunk.index];\n tc.id += tcchunk.id || \"\";\n tc.function.name += tcchunk.function?.name || \"\";\n tc.function.arguments += tcchunk.function?.arguments || \"\";\n }\n return toolCalls;\n};\n\nexport const callOpenAI = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"openai\") || process.env.OPENAI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"OpenAI API key not found\");\n }\n\n const messages = [];\n if (instructions) {\n messages.push({ role: \"system\", content: instructions });\n }\n messages.push(...ctx.history);\n\n const body: any = {\n model,\n messages,\n stream: !!ctx.stream,\n };\n\n if (schema) {\n body.response_format = {\n type: \"json_schema\",\n json_schema: {\n name: schema.name,\n schema: { ...schema.schema, additionalProperties: false },\n strict: true,\n },\n };\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools;\n body.tool_choice = \"auto\";\n }\n\n const response = await fetch(\"https://api.openai.com/v1/chat/completions\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n Authorization: `Bearer ${apiKey}`,\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`OpenAI API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleOpenAIStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const choice = data.choices[0];\n const { message } = choice;\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: message.content || \"\",\n };\n\n if (message.tool_calls) {\n msg.tool_calls = message.tool_calls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleOpenAIStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n let toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (data === \"[DONE]\") continue;\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const delta = parsed.choices?.[0]?.delta;\n\n if (delta?.content) {\n fullContent += delta.content;\n if (ctx.stream) {\n ctx.stream({ type: \"content\", content: delta.content });\n }\n }\n\n if (delta?.tool_calls) {\n toolCalls = appendToolCalls(toolCalls, delta.tool_calls);\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ProviderConfig, Message, ConversationContext } from \"../types\";\nimport { getKey } from \"../utils\";\n\nconst convertToAnthropicFormat = (messages: any[]): any[] => {\n const result: any[] = [];\n let i = 0;\n\n while (i < messages.length) {\n const msg = messages[i];\n\n if (msg.role === \"system\") {\n i++;\n continue;\n }\n\n if (msg.role === \"assistant\") {\n if (msg.tool_calls) {\n result.push({\n role: \"assistant\",\n content: msg.tool_calls.map((tc: any) => ({\n type: \"tool_use\",\n id: tc.id,\n name: tc.function.name,\n input: JSON.parse(tc.function.arguments),\n })),\n });\n } else {\n result.push({\n role: \"assistant\",\n content: msg.content,\n });\n }\n i++;\n } else if (msg.role === \"tool\") {\n const toolResults: any[] = [];\n while (i < messages.length && messages[i].role === \"tool\") {\n const toolMsg = messages[i];\n toolResults.push({\n type: \"tool_result\",\n tool_use_id: toolMsg.tool_call_id,\n content: toolMsg.content,\n });\n i++;\n }\n result.push({\n role: \"user\",\n content: toolResults,\n });\n } else {\n result.push(msg);\n i++;\n }\n }\n\n return result;\n};\n\nexport const callAnthropic = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions, schema } = config;\n const apiKey = getKey(\"anthropic\") || process.env.ANTHROPIC_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Anthropic API key not found\");\n }\n\n let system = instructions;\n\n if (ctx.history[0]?.role === \"system\") {\n system = ctx.history[0].content;\n }\n\n const messages = convertToAnthropicFormat(ctx.history);\n\n if (schema) {\n const schemaPrompt = `\\n\\nYou must respond with valid JSON that matches this schema:\\n${JSON.stringify(\n schema.schema,\n null,\n 2,\n )}\\n\\nReturn only the JSON object, no other text or formatting.`;\n system = system ? system + schemaPrompt : schemaPrompt.slice(2);\n }\n\n const body: any = {\n model,\n messages,\n max_tokens: 4096,\n stream: !!ctx.stream,\n };\n\n if (system) {\n body.system = system;\n }\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n input_schema: tool.function.parameters,\n }));\n }\n\n const response = await fetch(\"https://api.anthropic.com/v1/messages\", {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n \"x-api-key\": apiKey,\n \"anthropic-version\": \"2023-06-01\",\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n });\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Anthropic API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleAnthropicStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const content = data.content[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: content.type === \"text\" ? content.text : \"\",\n };\n\n if (content.type === \"tool_use\") {\n msg.tool_calls = [\n {\n id: content.id,\n type: \"function\",\n function: {\n name: content.name,\n arguments: JSON.stringify(content.input),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleAnthropicStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n\n if (parsed.type === \"content_block_delta\" && parsed.delta?.text) {\n fullContent += parsed.delta.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: parsed.delta.text });\n }\n }\n\n if (\n parsed.type === \"content_block_start\" &&\n parsed.content_block?.type === \"tool_use\"\n ) {\n const toolUse = parsed.content_block;\n toolCalls.push({\n id: toolUse.id,\n type: \"function\",\n function: {\n name: toolUse.name,\n arguments: \"\",\n },\n index: parsed.index,\n });\n }\n\n if (\n parsed.type === \"content_block_delta\" &&\n parsed.delta?.type === \"input_json_delta\"\n ) {\n const toolCall = toolCalls.find((tc) => tc.index === parsed.index);\n if (toolCall) {\n toolCall.function.arguments += parsed.delta.partial_json;\n }\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls.map(({ index, ...tc }) => tc);\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, Message, ProviderConfig } from \"../types\";\nimport { getKey } from \"../utils\";\n\nexport const callGoogle = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { model, instructions } = config;\n const apiKey = getKey(\"google\") || process.env.GOOGLE_AI_API_KEY;\n\n if (!apiKey) {\n throw new Error(\"Google API key not found\");\n }\n\n const contents = [];\n\n if (instructions) {\n contents.push({\n role: \"user\",\n parts: [{ text: instructions }],\n });\n contents.push({\n role: \"model\",\n parts: [{ text: \"I understand.\" }],\n });\n }\n\n for (const msg of ctx.history) {\n const role = msg.role === \"assistant\" ? \"model\" : \"user\";\n contents.push({\n role,\n parts: [{ text: msg.content }],\n });\n }\n\n const body: any = {\n contents,\n };\n\n if (ctx.tools && ctx.tools.length > 0) {\n body.tools = [\n {\n function_declarations: ctx.tools.map((tool) => ({\n name: tool.function.name,\n description: tool.function.description,\n parameters: tool.function.parameters,\n })),\n },\n ];\n }\n\n const endpoint = ctx.stream ? \"streamGenerateContent\" : \"generateContent\";\n const response = await fetch(\n `https://generativelanguage.googleapis.com/v1beta/models/${model}:${endpoint}?key=${apiKey}`,\n {\n method: \"POST\",\n headers: {\n \"Content-Type\": \"application/json\",\n },\n body: JSON.stringify(body),\n signal: ctx.abortSignal,\n },\n );\n\n if (!response.ok) {\n const error = await response.text();\n throw new Error(`Google API error: ${error}`);\n }\n\n if (ctx.stream) {\n return handleGoogleStream(response, ctx);\n }\n const data = (await response.json()) as any;\n const candidate = data.candidates[0];\n const part = candidate.content.parts[0];\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: part.text || \"\",\n };\n\n if (part.functionCall) {\n msg.tool_calls = [\n {\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n },\n ];\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n\nconst handleGoogleStream = async (\n response: Response,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const reader = response.body!.getReader();\n const decoder = new TextDecoder();\n\n let fullContent = \"\";\n const toolCalls: any[] = [];\n let buffer = \"\";\n\n try {\n while (true) {\n if (ctx.abortSignal?.aborted) {\n break;\n }\n\n const { done, value } = await reader.read();\n if (done) break;\n\n buffer += decoder.decode(value, { stream: true });\n const lines = buffer.split(\"\\n\");\n \n // keep the last incomplete line in the buffer\n buffer = lines.pop() || \"\";\n\n for (const line of lines) {\n if (line.startsWith(\"data: \")) {\n const data = line.slice(6).trim();\n if (!data) continue;\n\n try {\n const parsed = JSON.parse(data);\n const candidate = parsed.candidates?.[0];\n const part = candidate?.content?.parts?.[0];\n\n if (part?.text) {\n fullContent += part.text;\n if (ctx.stream) {\n ctx.stream({ type: 'content', content: part.text });\n }\n }\n\n if (part?.functionCall) {\n toolCalls.push({\n id: Math.random().toString(36).substring(2, 9),\n type: \"function\",\n function: {\n name: part.functionCall.name,\n arguments: JSON.stringify(part.functionCall.args),\n },\n });\n }\n } catch (e) {\n // skip invalid JSON lines\n }\n }\n }\n }\n } finally {\n reader.releaseLock();\n }\n\n const msg: Message & { tool_calls?: any[] } = {\n role: \"assistant\",\n content: fullContent,\n };\n\n if (toolCalls.length > 0) {\n msg.tool_calls = toolCalls;\n }\n\n return {\n ...ctx,\n lastResponse: msg,\n history: [...ctx.history, msg],\n };\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\n\nexport const callHuggingFace = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n throw new Error(\n \"Hugging Face provider not yet implemented. Use openai/, anthropic/, or google/ prefixes.\",\n );\n};\n","import { ConversationContext, ProviderConfig } from \"../types\";\nimport { parseModelName } from \"../utils\";\nimport { callOpenAI } from \"./openai\";\nimport { callAnthropic } from \"./anthropic\";\nimport { callGoogle } from \"./google\";\nimport { callHuggingFace } from \"./huggingface\";\n\nexport const callProvider = async (\n config: ProviderConfig,\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const { provider, model } = parseModelName(config.model);\n const providerConfig = { ...config, model };\n\n switch (provider.toLowerCase()) {\n case \"openai\":\n return callOpenAI(providerConfig, ctx);\n case \"anthropic\":\n return callAnthropic(providerConfig, ctx);\n case \"google\":\n return callGoogle(providerConfig, ctx);\n case \"huggingface\":\n default:\n return callHuggingFace(providerConfig, ctx);\n }\n};\n","import { EventEmitter } from \"events\";\nimport { ToolCall } from \"./types\";\n\nexport interface ApprovalRequest {\n id: string;\n toolCall: ToolCall;\n approvalId?: string;\n}\n\nexport interface ApprovalResponse {\n id: string;\n approved: boolean;\n reason?: string;\n}\n\ninterface ApprovalManagerState {\n resolvers: Map<string, (response: ApprovalResponse) => void>;\n emitter: EventEmitter;\n}\n\nconst state: ApprovalManagerState = {\n resolvers: new Map(),\n emitter: new EventEmitter(),\n};\n\nexport const generateApprovalToken = (): string => {\n return `approval_${Date.now()}_${Math.random().toString(36).substring(2, 9)}`;\n};\n\nexport const requestApproval = async (\n toolCall: ToolCall,\n approvalId?: string,\n): Promise<ApprovalResponse> => {\n const id = generateApprovalToken();\n const request: ApprovalRequest = { id, toolCall, approvalId };\n\n state.emitter.emit(\"approvalRequested\", request);\n\n return new Promise<ApprovalResponse>((resolve) => {\n state.resolvers.set(id, resolve);\n });\n};\n\nexport const resolveApproval = (response: ApprovalResponse): boolean => {\n const resolver = state.resolvers.get(response.id);\n if (!resolver) return false;\n\n state.resolvers.delete(response.id);\n resolver(response);\n state.emitter.emit(\"approvalResolved\", response);\n return true;\n};\n\nexport const onApprovalRequested = (\n listener: (request: ApprovalRequest) => void,\n) => {\n state.emitter.on(\"approvalRequested\", listener);\n};\n\nexport const onApprovalResolved = (\n listener: (response: ApprovalResponse) => void,\n) => {\n state.emitter.on(\"approvalResolved\", listener);\n};\n\nexport const removeApprovalListener = (\n event: \"approvalRequested\" | \"approvalResolved\",\n listener: (...args: any[]) => void,\n) => {\n state.emitter.removeListener(event, listener);\n};\n","import { callProvider } from \"../providers\";\nimport { normalizeSchema } from \"../schema\";\nimport {\n ConversationContext,\n ToolCall,\n JsonSchema,\n StandardSchema,\n ComposedFunction,\n} from \"../types\";\nimport { requestApproval } from \"../approval\";\n\nexport const model = ({\n model = \"openai/gpt-4o-mini\",\n schema,\n}: {\n model?: string;\n schema?: JsonSchema | StandardSchema;\n} = {}): ComposedFunction => {\n return async (\n ctxOrMessage: ConversationContext | string,\n ): Promise<ConversationContext> => {\n const ctx =\n typeof ctxOrMessage === \"string\"\n ? // model()(\"hello!\");\n {\n history: [{ role: \"user\" as const, content: ctxOrMessage }],\n tools: [],\n }\n : // model()(/* few shot or history */);\n ctxOrMessage;\n const normalizedSchema = schema ? normalizeSchema(schema) : undefined;\n const systemMessage = ctx.history.find((m) => m.role === \"system\");\n const instructions = systemMessage?.content;\n let currentCtx = ctx;\n\n do {\n if (currentCtx.abortSignal?.aborted) {\n break;\n }\n\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 (\n currentCtx.lastResponse?.tool_calls &&\n currentCtx.tools?.length &&\n !currentCtx.abortSignal?.aborted\n );\n\n return currentCtx;\n };\n};\n\nconst executeTools = async (\n ctx: ConversationContext,\n): Promise<ConversationContext> => {\n const calls = ctx.lastResponse?.tool_calls || [];\n if (!calls.length) return ctx;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_calls_ready\", calls });\n }\n\n const toolConfig = ctx.toolConfig || {};\n const {\n requireApproval = false,\n approvalCallback,\n parallel = false,\n retryCount = 0,\n approvalId,\n executeOnApproval = false,\n } = toolConfig;\n\n const updatedCounts = { ...(ctx.toolCallCounts || {}) };\n\n const runCall = async (call: ToolCall, approved: boolean) => {\n if (!approved) {\n if (ctx.stream) {\n ctx.stream({\n type: \"tool_error\",\n call,\n error: \"Tool execution denied by user\",\n });\n }\n return {\n call,\n result: { error: \"Tool execution denied by user\" },\n };\n }\n\n const toolName = call.function.name;\n const limits = ctx.toolLimits || {};\n const maxCalls = limits[toolName];\n const currentCount = updatedCounts[toolName] || 0;\n\n if (maxCalls && currentCount >= maxCalls) {\n const error = `Tool ${toolName} has reached its limit of ${maxCalls} calls`;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return {\n call,\n result: { error },\n };\n }\n\n updatedCounts[toolName] = currentCount + 1;\n\n if (ctx.stream) {\n ctx.stream({ type: \"tool_executing\", call });\n }\n\n let lastError: Error | undefined;\n for (let i = 0; i <= retryCount; i++) {\n try {\n const executor = ctx.toolExecutors?.[call.function.name];\n if (!executor) {\n throw new Error(`Tool executor not found: ${call.function.name}`);\n }\n let args = {};\n try {\n args = call.function.arguments\n ? JSON.parse(call.function.arguments)\n : {};\n } catch (e) {\n throw new Error(\n `Invalid JSON arguments for tool ${call.function.name}: ${call.function.arguments}`,\n );\n }\n const result = await executor(args);\n if (ctx.stream) {\n ctx.stream({ type: \"tool_complete\", call, result });\n }\n return { call, result };\n } catch (e) {\n lastError = e as Error;\n }\n }\n\n const error = lastError!.message;\n if (ctx.stream) {\n ctx.stream({ type: \"tool_error\", call, error });\n }\n return { call, result: { error } };\n };\n\n if (executeOnApproval && requireApproval) {\n const resultPromises = calls.map(async (call) => {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return runCall(call, approved);\n });\n\n const results = await Promise.all(resultPromises);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n }\n\n const approvalPromises = calls.map(async (call) => {\n if (requireApproval) {\n let approved: boolean;\n\n if (approvalCallback) {\n approved = await approvalCallback(call);\n } else {\n const response = await requestApproval(call, approvalId);\n approved = response.approved;\n }\n\n return { call, approved };\n } else {\n return { call, approved: true };\n }\n });\n\n const approvals = await Promise.all(approvalPromises);\n\n const runCallWithApproval = async (call: ToolCall) => {\n const approval = approvals.find((a) => a.call.id === call.id);\n return runCall(call, approval?.approved ?? true);\n };\n\n const results = parallel\n ? await Promise.all(calls.map(runCallWithApproval))\n : await runCallsSequentially(calls, runCallWithApproval);\n\n return {\n ...ctx,\n history: [\n ...ctx.history,\n ...results.map(({ call, result }) => ({\n role: \"tool\" as const,\n tool_call_id: call.id,\n content: JSON.stringify(result),\n })),\n ],\n toolCallCounts: updatedCounts,\n };\n};\n\nconst runCallsSequentially = async (\n calls: ToolCall[],\n runCall: (call: ToolCall) => Promise<{ call: ToolCall; result: any }>,\n) => {\n const results: { call: ToolCall; result: any }[] = [];\n for (const call of calls) {\n results.push(await runCall(call));\n }\n return results;\n};\n","import {\n Message,\n ConversationContext,\n StepFunction,\n ThreadStore,\n Thread,\n} from \"./types\";\nimport { model } from \"./composition/model\";\n\nconst createMemoryStore = (): ThreadStore => {\n const store = new Map<string, Message[]>();\n\n return {\n async get(threadId: string): Promise<Message[]> {\n return store.get(threadId) || [];\n },\n\n async set(threadId: string, messages: Message[]): Promise<void> {\n store.set(threadId, messages);\n },\n };\n};\n\nconst createThread = (id: string, store: ThreadStore): Thread => {\n return {\n id,\n store,\n async generate(workflow: StepFunction): Promise<ConversationContext> {\n const history = await store.get(id);\n\n const initialContext: ConversationContext = {\n history,\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await workflow(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n async message(\n content: string,\n workflow?: StepFunction,\n ): Promise<ConversationContext> {\n const history = await store.get(id);\n const initialContext: ConversationContext = {\n history: [...history, { role: \"user\", content }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n const finalContext = await (workflow || model())(initialContext);\n await store.set(id, finalContext.history);\n\n return finalContext;\n },\n };\n};\n\nconst threads = new Map<string, Thread>();\n\n/**\n * @example\n * // in-memory (default)\n * const thread = getOrCreateThread('user-123');\n *\n * @example\n * // sqlite\n * const thread = getOrCreateThread('user-123', {\n * async get(id) {\n * const row = await db.get('SELECT messages FROM threads WHERE id = ?', id);\n * return row ? JSON.parse(row.messages) : [];\n * },\n * async set(id, messages) {\n * await db.run(\n * 'INSERT OR REPLACE INTO threads (id, messages, updated_at) VALUES (?, ?, ?)',\n * id,\n * JSON.stringify(messages),\n * Date.now()\n * );\n * }\n * });\n */\nexport const getOrCreateThread = (id: string, store?: ThreadStore): Thread => {\n const cacheKey = store ? `${id}-${store}` : id;\n\n if (threads.has(cacheKey)) {\n return threads.get(cacheKey)!;\n }\n\n const threadStore = store || createMemoryStore();\n const thread = createThread(id, threadStore);\n threads.set(cacheKey, thread);\n return thread;\n};\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const when = (\n condition: (ctx: ConversationContext) => boolean,\n action: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n if (condition(ctx)) {\n return await action(ctx);\n }\n return ctx;\n };\n};\n","import { ConversationContext, StepFunction } from \"./types\";\nimport { when } from \"./composition/when\";\n\n/**\n * scope({ until: noToolsCalled() })\n */\nexport const noToolsCalled =\n () =>\n (ctx: ConversationContext): boolean => {\n return (\n !ctx.lastResponse?.tool_calls || ctx.lastResponse.tool_calls.length === 0\n );\n };\n\nexport const everyNMessages = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) =>\n Math.floor(ctx.history.length / n) > Math.floor(lastTriggeredAt / n),\n async (ctx) => {\n lastTriggeredAt = ctx.history.length;\n return await step(ctx);\n },\n );\n};\n\nexport const everyNTokens = (n: number, step: StepFunction): StepFunction => {\n let lastTriggeredAt = 0;\n\n return when(\n (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n return Math.floor(totalTokens / n) > Math.floor(lastTriggeredAt / n);\n },\n async (ctx) => {\n const totalTokens = ctx.history.reduce(\n (acc, msg) => acc + Math.ceil(msg.content.length / 4),\n 0,\n );\n lastTriggeredAt = totalTokens;\n return await step(ctx);\n },\n );\n};\n\nexport const appendToLastRequest = (content: string): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return ctx;\n\n const newHistory = [...ctx.history];\n newHistory[lastUserIndex] = {\n ...newHistory[lastUserIndex],\n content: newHistory[lastUserIndex].content + content,\n };\n\n return {\n ...ctx,\n history: newHistory,\n };\n };\n};\n\n/**\n * toolNotUsedInNTurns({ toolName: \"search_web\", times: 10 }, appendToLastRequest(\"consider using web search...\"))\n */\nexport const toolNotUsedInNTurns = (\n { toolName, times }: { toolName: string; times: number },\n step: StepFunction,\n): StepFunction => {\n let turnsSinceLastUsed = 0;\n let lastProcessedTurn = -1;\n\n return when((ctx) => {\n const currentTurn = getCurrentTurn(ctx);\n\n // only check once per turn\n if (currentTurn === lastProcessedTurn) return false;\n lastProcessedTurn = currentTurn;\n\n // check if tool was used in this turn\n const toolUsedInTurn = wasToolUsedInCurrentTurn(ctx, toolName);\n\n if (toolUsedInTurn) {\n turnsSinceLastUsed = 0;\n return false;\n } else {\n turnsSinceLastUsed++;\n return turnsSinceLastUsed >= times;\n }\n }, step);\n};\n\nconst getCurrentTurn = (ctx: ConversationContext): number => {\n let turns = 0;\n for (const msg of ctx.history) {\n if (msg.role === \"user\") turns++;\n }\n return turns;\n};\n\nconst wasToolUsedInCurrentTurn = (\n ctx: ConversationContext,\n toolName: string,\n): boolean => {\n // find the last user message and check all messages after it for tool usage\n let lastUserIndex = -1;\n for (let i = ctx.history.length - 1; i >= 0; i--) {\n if (ctx.history[i].role === \"user\") {\n lastUserIndex = i;\n break;\n }\n }\n\n if (lastUserIndex === -1) return false;\n\n // check messages after last user message for tool calls\n for (let i = lastUserIndex + 1; i < ctx.history.length; i++) {\n const msg = ctx.history[i];\n if (msg.role === \"assistant\" && ctx.lastResponse?.tool_calls) {\n return ctx.lastResponse.tool_calls.some(\n (call) => call.function.name === toolName,\n );\n }\n }\n\n return false;\n};\n\nexport const toolWasCalled =\n (name: string) =>\n (ctx: ConversationContext): boolean => {\n return (\n !!ctx.lastResponse?.tool_calls &&\n ctx.lastResponse.tool_calls.some((call) => call.function.name === name)\n );\n };\n","import { ConversationContext, StepFunction } from \"../types\";\n\nexport const tap = (\n fn: (ctx: ConversationContext) => Promise<void> | void,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n await fn(ctx);\n return ctx;\n };\n};\n","import { StepFunction, ConversationContext, RetryOptions } from \"../types\";\n\n/**\n * scope({}, retry({ times: 2 }, model(...)))\n */\nexport const retry = (\n { times = 3 }: RetryOptions = {},\n step: StepFunction,\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let err: Error;\n\n for (let i = 0; i < times; i++) {\n try {\n return await step(ctx);\n } catch (e) {\n err = e as Error;\n }\n }\n\n throw err!;\n };\n};\n","import { ComposedFunction, ConversationContext, StepFunction } from \"../types\";\n\nconst enrichContext = (ctx: ConversationContext): ConversationContext => {\n const lastUserMessage = [...ctx.history]\n .reverse()\n .find((msg) => msg.role === \"user\");\n return {\n ...ctx,\n lastRequest: lastUserMessage,\n };\n};\n\nexport const compose = (...steps: StepFunction[]): ComposedFunction => {\n return async (ctxOrMessage: ConversationContext | string): Promise<ConversationContext> => {\n let initialContext: ConversationContext;\n\n if (typeof ctxOrMessage === \"string\") {\n initialContext = {\n history: [{ role: \"user\", content: ctxOrMessage }],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n } else {\n initialContext = ctxOrMessage || {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n }\n\n let next = enrichContext(initialContext);\n\n for (const step of steps) {\n next = await step(enrichContext(next));\n }\n\n return next;\n };\n};\n","import { compose } from \"./compose\";\nimport {\n ConversationContext,\n Inherit,\n ScopeConfig,\n StepFunction,\n} from \"../types\";\nimport { toolConfigToToolDefinition } from \"../utils\";\n\nconst scopeContext = (\n config: ScopeConfig,\n ctx: ConversationContext,\n): ConversationContext => {\n // const inherit = config.inherit ?? Inherit.Nothing;\n const inherit = config.inherit ?? Inherit.Conversation;\n\n let scopedCtx: ConversationContext = {\n history: [],\n tools: [],\n toolExecutors: {},\n toolLimits: {},\n toolCallCounts: {},\n };\n\n // inheritance\n\n if (inherit & Inherit.Conversation) {\n scopedCtx.history = ctx.history;\n scopedCtx.lastResponse = ctx.lastResponse;\n scopedCtx.lastRequest = ctx.lastRequest;\n }\n\n if (inherit & Inherit.Tools) {\n scopedCtx.tools = [...(ctx.tools || [])];\n scopedCtx.toolExecutors = { ...(ctx.toolExecutors || {}) };\n scopedCtx.toolLimits = { ...(ctx.toolLimits || {}) };\n scopedCtx.toolCallCounts = { ...(ctx.toolCallCounts || {}) };\n scopedCtx.toolConfig = ctx.toolConfig ? { ...ctx.toolConfig } : undefined;\n }\n\n scopedCtx.stream = ctx.stream;\n scopedCtx.abortSignal = ctx.abortSignal;\n\n if (config.tools) {\n const toolDefinitions = config.tools.map(toolConfigToToolDefinition);\n const toolExecutors = config.tools.reduce(\n (acc, tool) => {\n acc[tool.name] = tool.execute;\n\n return acc;\n },\n {} as Record<string, Function>,\n );\n const toolLimits = config.tools.reduce(\n (acc, tool) => {\n if (tool._maxCalls) {\n acc[tool.name] = tool._maxCalls;\n }\n\n return acc;\n },\n {} as Record<string, number>,\n );\n\n scopedCtx.tools = toolDefinitions;\n scopedCtx.toolExecutors = toolExecutors;\n scopedCtx.toolLimits = toolLimits;\n }\n\n if (config.toolConfig) {\n scopedCtx.toolConfig = { ...config.toolConfig };\n }\n\n if (config.system) {\n const [first, ...rest] = scopedCtx.history;\n if (first?.role === \"system\") {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...rest];\n } else {\n scopedCtx.history = [{ role: \"system\", content: config.system }, ...scopedCtx.history];\n }\n }\n\n if (config.stream) {\n scopedCtx.stream = config.stream;\n }\n\n return scopedCtx;\n};\n\nexport const scope = (\n config: ScopeConfig,\n ...steps: StepFunction[]\n): StepFunction => {\n return async (ctx: ConversationContext): Promise<ConversationContext> => {\n let scopedCtx = scopeContext(config, ctx);\n\n if (config.until) {\n do {\n scopedCtx = await compose(...steps)(scopedCtx);\n } while (!config.until(scopedCtx));\n } else {\n scopedCtx = await compose(...steps)(scopedCtx);\n }\n\n return {\n ...ctx,\n history: config.silent ? ctx.history : scopedCtx.history,\n lastResponse: config.silent ? ctx.lastResponse : scopedCtx.lastResponse,\n lastRequest: config.silent ? ctx.lastRequest : scopedCtx.lastRequest,\n stopReason: config.silent ? ctx.stopReason : scopedCtx.stopReason,\n };\n };\n};\n","type RateLimitConfig = {\n rps: number;\n burst: number;\n concurrency: number;\n};\n\ntype QueueItem = {\n fn: () => Promise<any>;\n resolve: (value: any) => void;\n reject: (error: any) => void;\n};\n\n/**\n * creates a rate limiter that wraps async functions with burst, rate, and concurrency controls\n *\n * @param config - rate limit configuration\n * @param config.rps - maximum requests per second\n * @param config.burst - maximum burst size (initial token bucket capacity)\n * @param config.concurrency - maximum concurrent in-flight requests\n *\n * @example\n * const limiter = rateLimited({ rps: 10, burst: 20, concurrency: 5 });\n *\n * const workflow = limiter(\n * compose(\n * scope({ tools: [searchTool] }, model())\n * )\n * );\n *\n * await workflow(\"hello\");\n */\nexport const rateLimited =\n (config: RateLimitConfig) =>\n <T extends (...args: any[]) => Promise<any>>(fn: T): T => {\n const { rps, burst, concurrency } = config;\n\n let tokens = burst;\n let inFlight = 0;\n const queue: QueueItem[] = [];\n let intervalId: NodeJS.Timeout | null = null;\n\n const refillTokens = () => {\n tokens = Math.min(tokens + 1, burst);\n processQueue();\n };\n\n const startInterval = () => {\n if (!intervalId) {\n intervalId = setInterval(refillTokens, 1000 / rps);\n }\n };\n\n const stopInterval = () => {\n if (intervalId && queue.length === 0 && inFlight === 0) {\n clearInterval(intervalId);\n intervalId = null;\n }\n };\n\n const processQueue = () => {\n while (queue.length > 0 && tokens > 0 && inFlight < concurrency) {\n tokens--;\n inFlight++;\n\n const item = queue.shift()!;\n\n item\n .fn()\n .then((result) => {\n inFlight--;\n item.resolve(result);\n processQueue();\n stopInterval();\n })\n .catch((error) => {\n inFlight--;\n item.reject(error);\n processQueue();\n stopInterval();\n });\n }\n };\n\n return (async (...args: any[]) => {\n return new Promise((resolve, reject) => {\n queue.push({\n fn: () => fn(...args),\n resolve,\n reject,\n });\n startInterval();\n processQueue();\n });\n }) as T;\n };\n"],"mappings":";AACA,SAAS,SAAuB;AAEzB,IAAM,mBAAmB,CAAC,WAA0C;AACzE,SAAO,UAAU,OAAO,WAAW,YAAY,eAAe;AAChE;AAEO,IAAM,oCAAoC,CAC/C,gBACA,OAAe,aACA;AACf,QAAM,aAAa,EAAE,aAAa,cAAyB;AAC3D,SAAO;AAAA,IACL;AAAA,IACA,QAAQ;AAAA,EACV;AACF;AAEO,IAAM,+BAA+B,CAC1C,cACmC;AACnC,MAAI,CAAC,WAAW,WAAY,QAAO,CAAC;AAEpC,QAAM,SAAyC,CAAC;AAChD,aAAW,CAAC,KAAK,KAAK,KAAK,OAAO,QAAQ,UAAU,UAAU,GAAG;AAC/D,UAAM,OAAO;AACb,WAAO,GAAG,IAAI;AAAA,MACZ,MAAM,KAAK,QAAQ;AAAA,MACnB,aAAa,KAAK,eAAe;AAAA,MACjC,UAAU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tD,oBAAc,UAAU;AACxB,mBAAa;AAAA,IACf;AAAA,EACF;AAEA,QAAM,eAAe,MAAM;AACzB,WAAO,MAAM,SAAS,KAAK,SAAS,KAAK,WAAW,aAAa;AAC/D;AACA;AAEA,YAAM,OAAO,MAAM,MAAM;AAEzB,WACG,GAAG,EACH,KAAK,CAAC,WAAW;AAChB;AACA,aAAK,QAAQ,MAAM;AACnB,qBAAa;AACb,qBAAa;AAAA,MACf,CAAC,EACA,MAAM,CAAC,UAAU;AAChB;AACA,aAAK,OAAO,KAAK;AACjB,qBAAa;AACb,qBAAa;AAAA,MACf,CAAC;AAAA,IACL;AAAA,EACF;AAEA,UAAQ,UAAU,SAAgB;AAChC,WAAO,IAAI,QAAQ,CAAC,SAAS,WAAW;AACtC,YAAM,KAAK;AAAA,QACT,IAAI,MAAM,GAAG,GAAG,IAAI;AAAA,QACpB;AAAA,QACA;AAAA,MACF,CAAC;AACD,oBAAc;AACd,mBAAa;AAAA,IACf,CAAC;AAAA,EACH;AACF;","names":["Inherit","model","maxCalls","model","extractor","model","model","model","msg","model","model","maxCalls","error","results"]}
|