@fifthrevision/axle 0.8.0 → 0.8.1
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +40 -1
- package/dist/cli.js +3 -3
- package/dist/index.d.ts +21 -31
- package/dist/index.js +1 -1
- package/dist/simple-Cn_DeT3l.js +36 -0
- package/package.json +1 -1
- package/dist/simple-DbMOgdiX.js +0 -36
package/README.md
CHANGED
|
@@ -185,6 +185,42 @@ const agent = new Agent({
|
|
|
185
185
|
Axle includes several built-in tools: `braveSearchTool`, `calculatorTool`,
|
|
186
186
|
`execTool`, `readFileTool`, `writeFileTool`, and `patchFileTool`.
|
|
187
187
|
|
|
188
|
+
### Server Tools
|
|
189
|
+
|
|
190
|
+
Server tools are provider-managed tools that execute on the provider's side
|
|
191
|
+
(e.g. web search, code interpreter). Pass them alongside regular tools using
|
|
192
|
+
`{ type: "server", name: "..." }`.
|
|
193
|
+
|
|
194
|
+
```typescript
|
|
195
|
+
import { Agent } from "@fifthrevision/axle";
|
|
196
|
+
import type { ServerTool } from "@fifthrevision/axle";
|
|
197
|
+
|
|
198
|
+
const agent = new Agent({
|
|
199
|
+
provider,
|
|
200
|
+
model,
|
|
201
|
+
tools: [
|
|
202
|
+
{ type: "server", name: "web_search" },
|
|
203
|
+
calculatorTool, // regular tools work alongside server tools
|
|
204
|
+
],
|
|
205
|
+
});
|
|
206
|
+
```
|
|
207
|
+
|
|
208
|
+
Axle maps common names to provider-specific identifiers automatically:
|
|
209
|
+
|
|
210
|
+
| Name | Anthropic | OpenAI | Gemini |
|
|
211
|
+
| ---------------- | ------------------------ | -------------------- | ---------------- |
|
|
212
|
+
| `web_search` | `web_search_20250305` | `web_search_preview` | `googleSearch` |
|
|
213
|
+
| `code_execution` | — | `code_interpreter` | `codeExecution` |
|
|
214
|
+
|
|
215
|
+
You can also pass provider-specific names directly. Use the optional `config`
|
|
216
|
+
field for provider-specific options:
|
|
217
|
+
|
|
218
|
+
```typescript
|
|
219
|
+
{ type: "server", name: "web_search", config: { max_results: 5 } }
|
|
220
|
+
```
|
|
221
|
+
|
|
222
|
+
Server tool events stream as `internal-tool:start` and `internal-tool:complete`.
|
|
223
|
+
|
|
188
224
|
### MCP (Model Context Protocol)
|
|
189
225
|
|
|
190
226
|
Axle supports connecting to MCP servers via stdio or HTTP transport. Create an
|
|
@@ -248,7 +284,7 @@ const result = await handle.final;
|
|
|
248
284
|
|
|
249
285
|
Event types include `text:start`, `text:delta`, `text:end`, `thinking:start`,
|
|
250
286
|
`thinking:delta`, `thinking:end`, `tool:start`, `tool:execute`,
|
|
251
|
-
`tool:complete`, and `error`.
|
|
287
|
+
`tool:complete`, `internal-tool:start`, `internal-tool:complete`, and `error`.
|
|
252
288
|
|
|
253
289
|
Callbacks are registered once and fire on every subsequent `send()`.
|
|
254
290
|
|
|
@@ -293,6 +329,9 @@ task: |
|
|
|
293
329
|
tools:
|
|
294
330
|
- calculator
|
|
295
331
|
|
|
332
|
+
server_tools:
|
|
333
|
+
- web_search
|
|
334
|
+
|
|
296
335
|
files:
|
|
297
336
|
- ./data/report.txt
|
|
298
337
|
```
|
package/dist/cli.js
CHANGED
|
@@ -1,8 +1,8 @@
|
|
|
1
1
|
#!/usr/bin/env node
|
|
2
|
-
var Z=Object.defineProperty;var l=(e,t)=>Z(e,"name",{value:t,configurable:!0});import{Command as K}from"@commander-js/extra-typings";import U from"yaml";import{t as D,m as Q,a as X,o as ee,D as te,j as oe,d as re,q as ne,u as J,i as ie,p as x,I as N,h as _,w as ae,v as se,x as ce,y as le,l as pe,k as ue,T as fe,S as B}from"./simple-
|
|
2
|
+
var Z=Object.defineProperty;var l=(e,t)=>Z(e,"name",{value:t,configurable:!0});import{Command as K}from"@commander-js/extra-typings";import U from"yaml";import{t as D,m as Q,a as X,o as ee,D as te,j as oe,d as re,q as ne,u as J,i as ie,p as x,I as N,h as _,w as ae,v as se,x as ce,y as le,l as pe,k as ue,T as fe,S as B}from"./simple-Cn_DeT3l.js";import{z as o}from"zod";import{glob as me}from"glob";import{readFile as G,mkdir as de,appendFile as ge}from"node:fs/promises";import{createInterface as he}from"node:readline";import{createHash as we}from"node:crypto";import{dirname as ye}from"node:path";import"mime";import"@anthropic-ai/sdk";import"@google/genai";import"openai";import"node:child_process";import"node:util";import"@modelcontextprotocol/sdk/client/index.js";import"@modelcontextprotocol/sdk/client/stdio.js";import"@modelcontextprotocol/sdk/client/streamableHttp.js";import"marked";import"marked-terminal";function ve(e,t){if(!t||Object.keys(t).length===0)throw new D(`The provider ${e} is not configured. Please check your configuration.`);switch(e){case"openai":return{provider:ne(t["api-key"]),model:t.model||re};case"anthropic":return{provider:oe(t["api-key"]),model:t.model||te};case"gemini":return{provider:ee(t["api-key"]),model:t.model||X};case"chatcompletions":{const r=t;return{provider:Q(r["base-url"],r["api-key"]),model:r.model}}default:throw new D("The provider is unsupported")}}l(ve,"getProvider");var be="0.8.1",Se={version:be};o.object({value:o.string()});const ke=o.object({"api-key":o.string(),rateLimit:o.number().optional()});o.object({timeout:o.number().optional(),maxBuffer:o.number().optional(),cwd:o.string().optional()});const Ee=o.object({type:o.literal("chatcompletions")}).loose(),Te=o.object({type:o.literal("anthropic")}).loose(),je=o.object({type:o.literal("openai")}).loose(),Ae=o.object({type:o.literal("gemini")}).loose(),Ce=o.discriminatedUnion("type",[Ee,Te,je,Ae]),Oe=o.object({chatcompletions:o.custom().optional(),anthropic:o.custom().optional(),openai:o.custom().optional(),gemini:o.custom().optional(),brave:ke.optional()}).loose(),xe=o.object({transport:o.literal("stdio"),name:o.string().optional(),command:o.string(),args:o.array(o.string()).optional(),env:o.record(o.string(),o.string()).optional()}),Fe=o.object({transport:o.literal("http"),name:o.string().optional(),url:o.string(),headers:o.record(o.string(),o.string()).optional()}),Le=o.discriminatedUnion("transport",[xe,Fe]),Ie=o.object({files:o.string(),resume:o.boolean().default(!1),concurrency:o.number().int().positive().default(3)}),Me=o.object({provider:Ce,task:o.string(),tools:o.array(o.string()).optional(),server_tools:o.array(o.string()).optional(),files:o.array(o.string()).optional(),mcps:o.array(Le).optional(),batch:Ie.optional()}),Pe="axle.job",$e=["yaml","yml","json"];async function Ue(e,t){const{tracer:r}=t,{content:s,format:c}=await J(e,{defaults:{name:Pe,formats:$e},tag:"Job File"});let i=null;if(c==="json")i=JSON.parse(s);else if(c==="yaml"||c==="yml")i=U.parse(s);else throw new Error("Invalid job file format");r?.debug("Job config: "+JSON.stringify(i,null,2));const a=Me.safeParse(i);if(!a.success)throw new Error(`The job file is not valid:
|
|
3
3
|
${H(a.error)}`);return a.data}l(Ue,"getJobConfig");const De="axle.config",Je=["yaml","yml","json"];async function Ne(e,t){const{tracer:r}=t,{content:s,format:c}=await J(e,{defaults:{name:De,formats:Je},tag:"Config File"});let i=null;if(c==="json")i=JSON.parse(s);else if(c==="yaml"||c==="yml")i=U.parse(s);else throw new Error("Invalid config file format");r?.debug("Service config: "+JSON.stringify(i,null,2));const a=Oe.safeParse(i);if(!a.success)throw new Error(`The config file is not valid:
|
|
4
4
|
${H(a.error)}`);return a.data}l(Ne,"getServiceConfig");function H(e){return e.issues.map(t=>` - ${t.path.join(".")||"root"}: ${t.message}`).join(`
|
|
5
5
|
`)}l(H,"formatZodError");async function _e(e,t){const r=[];for(const s of e){const c=new ie(s);await c.connect({tracer:t}),r.push(c)}return r}l(_e,"connectMcps");async function Be(e,t){for(const r of e)try{await r.close({tracer:t})}catch{}}l(Be,"closeMcps");const W=".axle/batch.jsonl";function Ge(e,t){const r=we("sha256");return r.update(e),r.update("\0"),r.update(t),r.digest("hex")}l(Ge,"computeHash");async function He(e=W){const t=new Map;let r;try{r=await G(e,"utf-8")}catch{return t}for(const s of r.split(`
|
|
6
6
|
`)){const c=s.trim();if(c)try{const i=JSON.parse(c);i.file&&i.hash&&t.set(i.file,i)}catch{}}return t}l(He,"loadLedger");async function We(e,t=W){await de(ye(t),{recursive:!0}),await ge(t,JSON.stringify(e)+`
|
|
7
|
-
`,"utf-8")}l(We,"appendLedgerEntry");async function Re(e,t,r,s,c,i,a,f,h){const
|
|
8
|
-
> `);if(i===null||i.trim()==="")break;try{const a=await e.send(i.trim()).final;if(t.in+=a.usage.in,t.out+=a.usage.out,a.response){const f=typeof a.response=="string"?a.response:JSON.stringify(a.response,null,2);r.info(f,{markdown:!0})}}catch(a){const f=a instanceof Error?a.message:String(a);r.error(f)}}}finally{s.close()}}l(qe,"runInteractiveLoop");async function ze(e,t,r,s,c,i,a,f,h){const
|
|
7
|
+
`,"utf-8")}l(We,"appendLedgerEntry");async function Re(e,t,r,s,c,i,a,f,h){const d=new N(e.task);if(e.files)for(const p of e.files)d.addFile(await x(p));const w=h.startSpan("job",{type:"workflow"}),E=new _({provider:t,model:r,tools:s,mcps:c,tracer:w});try{const p=await E.send(d,i).final;if(f.in+=p.usage.in,f.out+=p.usage.out,p.response){const v=typeof p.response=="string"?p.response:JSON.stringify(p.response,null,2);h.info(v,{markdown:!0})}a.interactive&&await qe(E,f,h),w.end()}catch(p){const v=p instanceof Error?p.message:String(p);throw w.error(v),w.end("error"),p}}l(Re,"runSingle");async function qe(e,t,r){const s=he({input:process.stdin,output:process.stdout});s.on("SIGINT",()=>{s.close()});const c=l(i=>new Promise(a=>{s.question(i,a),s.once("close",()=>a(null))}),"prompt");try{for(;;){const i=await c(`
|
|
8
|
+
> `);if(i===null||i.trim()==="")break;try{const a=await e.send(i.trim()).final;if(t.in+=a.usage.in,t.out+=a.usage.out,a.response){const f=typeof a.response=="string"?a.response:JSON.stringify(a.response,null,2);r.info(f,{markdown:!0})}}catch(a){const f=a instanceof Error?a.message:String(a);r.error(f)}}}finally{s.close()}}l(qe,"runInteractiveLoop");async function ze(e,t,r,s,c,i,a,f,h){const d=e.batch,w=await me(d.files);if(w.length===0){h.warn(`No files matched pattern: ${d.files}`);return}h.info(`Batch: ${w.length} file(s) matched "${d.files}"`);const E=d.resume?await He():new Map,p=e.files?await Promise.all(e.files.map(y=>x(y))):[];let v=0,I=0,M=0;const z=d.concurrency??3;await Ve(z,w,async y=>{const b=h.startSpan(`batch:${y}`,{type:"workflow"});try{const S=await G(y),T=Ge(e.task,S),P=E.get(y);if(d.resume&&P&&P.hash===T){b.info("Skipped (already completed)"),b.end(),I++;return}const O=new N(e.task);for(const Y of p)O.addFile(Y);O.addFile(await x(y));const V={...i,file:y},$=await new _({provider:t,model:r,tools:s,mcps:c,tracer:b}).send(O,V).final;f.in+=$.usage.in,f.out+=$.usage.out,await We({file:y,hash:T,timestamp:Date.now()}),b.end(),v++}catch(S){const T=S instanceof Error?S.message:String(S);b.error(`Failed: ${T}`),b.end("error"),M++}}),h.info(`Batch complete: ${v} completed, ${I} skipped, ${M} failed`)}l(ze,"runBatch");async function Ve(e,t,r){let s=0;async function c(){for(;s<t.length;){const a=s++;await r(t[a])}}l(c,"worker");const i=Array.from({length:Math.min(e,t.length)},()=>c());await Promise.all(i)}l(Ve,"runWithConcurrency");function Ye(e,t){switch(e){case"brave":return ue;case"calculator":return pe;case"exec":return le;case"patch-file":return ce;case"read-file":return se;case"write-file":return ae;default:throw new Error(`Unknown tool: ${e}`)}}l(Ye,"createTool");function Ze(e,t){return e.map(r=>Ye(r))}l(Ze,"createTools");const j=new K().name("axle").description("Axle is a CLI tool for running AI workflows").version(Se.version).option("-c, --config <path>","Path to the config file").option("-j, --job <path>","Path to the job file").option("--no-log","Do not write the output to a log file").option("-d, --debug","Print additional debug information").option("-i, --interactive","Continue the conversation interactively after the initial task").option("--args <args...>","Additional arguments in the form key=value");j.parse(process.argv);const u=j.opts(),A={date:new Date().toISOString().split("T")[0],datetime:new Date().toISOString(),cwd:process.cwd()};u.args&&u.args.forEach(e=>{const[t,r]=e.split("=");t&&r&&(A[t.trim()]=r.trim())});const g=new fe;u.debug&&(g.minLevel="debug");const Ke=new B({minLevel:u.debug?"debug":"info",showInternal:u.debug,showTimestamp:!0,markdown:!0});if(g.addWriter(Ke),u.log){const e=new B({minLevel:"debug",showInternal:!0,showTimestamp:!0,output:l(t=>{},"output")});g.addWriter(e)}const n=g.startSpan("cli",{type:"root"});process.on("uncaughtException",async e=>{console.error("Uncaught exception:"),console.error(e),n.error("Uncaught exception:"),n.error(e.message),n.error(e.stack||""),n.end("error"),await g.flush(),process.exit(1)}),u.debug&&(n.debug("Options: "+JSON.stringify(u,null,2)),n.debug("Additional Arguments: "+JSON.stringify(A,null,2)));let R,m;try{R=await Ne(u.config??null,{tracer:n}),m=await Ue(u.job??null,{tracer:n})}catch(e){const t=e instanceof Error?e:new Error(String(e));n.error(t.message),n.debug(t.stack??""),n.end("error"),await g.flush(),j.outputHelp(),process.exit(1)}let F,L;try{const{type:e,...t}=m.provider,r={...R[e],...t};({provider:F,model:L}=ve(e,r))}catch(e){const t=e instanceof Error?e:new Error(String(e));n.error(t.message),n.error(t.stack??""),n.end("error"),await g.flush(),j.outputHelp(),process.exit(1)}n.info("All systems operational. Running job...");const Qe=(m.server_tools??[]).map(e=>({type:"server",name:e})),q=[...m.tools?.length?Ze(m.tools):[],...Qe];let k=[];if(m.mcps?.length)try{k=await _e(m.mcps,n)}catch(e){const t=e instanceof Error?e:new Error(String(e));n.error("Failed to connect MCP servers: "+t.message),n.end("error"),await g.flush(),process.exit(1)}const C={in:0,out:0},Xe=performance.now();try{m.batch?await ze(m,F,L,q,k,A,u,C,n):await Re(m,F,L,q,k,A,u,C,n)}catch(e){const t=e instanceof Error?e:new Error(String(e));n.error(t.message),n.debug(t.stack??"")}finally{k.length>0&&await Be(k,n)}const et=performance.now()-Xe;n.info(`Total run time: ${Math.round(et)}ms`),n.info(`Input tokens: ${C.in}`),n.info(`Output tokens: ${C.out}`),n.info("Complete. Goodbye"),n.end(),await g.flush();
|
package/dist/index.d.ts
CHANGED
|
@@ -365,7 +365,8 @@ interface ContentPartInternalTool {
|
|
|
365
365
|
output?: unknown;
|
|
366
366
|
}
|
|
367
367
|
|
|
368
|
-
interface
|
|
368
|
+
interface ExecutableTool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
369
|
+
type?: "function";
|
|
369
370
|
name: string;
|
|
370
371
|
description: string;
|
|
371
372
|
schema: TSchema;
|
|
@@ -373,7 +374,13 @@ interface Tool<TSchema extends ZodObject<any> = ZodObject<any>> {
|
|
|
373
374
|
configure?(config: Record<string, any>): void;
|
|
374
375
|
summarize?(input: z$1.infer<TSchema>): string;
|
|
375
376
|
}
|
|
376
|
-
|
|
377
|
+
interface ServerTool {
|
|
378
|
+
type: "server";
|
|
379
|
+
name: string;
|
|
380
|
+
config?: Record<string, unknown>;
|
|
381
|
+
}
|
|
382
|
+
type AxleTool = ExecutableTool | ServerTool;
|
|
383
|
+
type ToolDefinition = Pick<ExecutableTool, "name" | "description" | "schema">;
|
|
377
384
|
|
|
378
385
|
interface MCPStdioConfig {
|
|
379
386
|
transport: "stdio";
|
|
@@ -404,12 +411,12 @@ declare class MCP {
|
|
|
404
411
|
listTools(options?: {
|
|
405
412
|
prefix?: string;
|
|
406
413
|
tracer?: TracingContext;
|
|
407
|
-
}): Promise<
|
|
414
|
+
}): Promise<ExecutableTool[]>;
|
|
408
415
|
listToolDefinitions(options?: {
|
|
409
416
|
prefix?: string;
|
|
410
417
|
tracer?: TracingContext;
|
|
411
418
|
}): Promise<ToolDefinition[]>;
|
|
412
|
-
refreshTools(): Promise<
|
|
419
|
+
refreshTools(): Promise<ExecutableTool[]>;
|
|
413
420
|
close(options?: {
|
|
414
421
|
tracer?: TracingContext;
|
|
415
422
|
}): Promise<void>;
|
|
@@ -557,6 +564,7 @@ interface StreamOptions {
|
|
|
557
564
|
messages: Array<AxleMessage>;
|
|
558
565
|
system?: string;
|
|
559
566
|
tools?: Array<ToolDefinition>;
|
|
567
|
+
serverTools?: Array<ServerTool>;
|
|
560
568
|
onToolCall?: ToolCallCallback;
|
|
561
569
|
maxIterations?: number;
|
|
562
570
|
tracer?: TracingContext;
|
|
@@ -599,7 +607,7 @@ interface AgentConfig {
|
|
|
599
607
|
provider: AIProvider;
|
|
600
608
|
model: string;
|
|
601
609
|
system?: string;
|
|
602
|
-
tools?:
|
|
610
|
+
tools?: AxleTool[];
|
|
603
611
|
mcps?: MCP[];
|
|
604
612
|
tracer?: TracingContext;
|
|
605
613
|
}
|
|
@@ -619,13 +627,14 @@ declare class Agent {
|
|
|
619
627
|
readonly history: History;
|
|
620
628
|
readonly tracer?: TracingContext;
|
|
621
629
|
system: string | undefined;
|
|
622
|
-
tools: Record<string,
|
|
630
|
+
tools: Record<string, ExecutableTool>;
|
|
631
|
+
serverTools: ServerTool[];
|
|
623
632
|
private mcps;
|
|
624
633
|
private mcpToolsResolved;
|
|
625
634
|
private eventCallbacks;
|
|
626
635
|
constructor(config: AgentConfig);
|
|
627
|
-
addTool(tool:
|
|
628
|
-
addTools(tools:
|
|
636
|
+
addTool(tool: AxleTool): void;
|
|
637
|
+
addTools(tools: AxleTool[]): void;
|
|
629
638
|
addMcp(mcp: MCP): void;
|
|
630
639
|
addMcps(mcps: MCP[]): void;
|
|
631
640
|
hasTools(): boolean;
|
|
@@ -673,22 +682,14 @@ declare const Gemini: {
|
|
|
673
682
|
readonly GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS: "gemini-3.1-pro-preview-customtools";
|
|
674
683
|
readonly GEMINI_3_PRO_PREVIEW: "gemini-3-pro-preview";
|
|
675
684
|
readonly GEMINI_3_FLASH_PREVIEW: "gemini-3-flash-preview";
|
|
676
|
-
readonly GEMINI_3_PRO_IMAGE_PREVIEW: "gemini-3-pro-image-preview";
|
|
677
685
|
readonly GEMINI_2_5_PRO: "gemini-2.5-pro";
|
|
678
686
|
readonly GEMINI_2_5_FLASH: "gemini-2.5-flash";
|
|
679
|
-
readonly GEMINI_2_5_FLASH_PREVIEW_09_2025: "gemini-2.5-flash-preview-09-2025";
|
|
680
|
-
readonly GEMINI_2_5_FLASH_IMAGE: "gemini-2.5-flash-image";
|
|
681
687
|
readonly GEMINI_2_5_FLASH_LITE: "gemini-2.5-flash-lite";
|
|
682
688
|
readonly GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025: "gemini-2.5-flash-lite-preview-09-2025";
|
|
683
|
-
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_LATEST: "gemini-2.5-flash-native-audio-latest";
|
|
684
|
-
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025: "gemini-2.5-flash-native-audio-preview-09-2025";
|
|
685
|
-
readonly GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025: "gemini-2.5-flash-native-audio-preview-12-2025";
|
|
686
|
-
readonly GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025: "gemini-2.5-computer-use-preview-10-2025";
|
|
687
689
|
readonly GEMINI_2_0_FLASH: "gemini-2.0-flash";
|
|
688
690
|
readonly GEMINI_2_0_FLASH_001: "gemini-2.0-flash-001";
|
|
689
691
|
readonly GEMINI_2_0_FLASH_LITE: "gemini-2.0-flash-lite";
|
|
690
692
|
readonly GEMINI_2_0_FLASH_LITE_001: "gemini-2.0-flash-lite-001";
|
|
691
|
-
readonly GEMINI_EXP_1206: "gemini-exp-1206";
|
|
692
693
|
readonly GEMINI_FLASH_LATEST: "gemini-flash-latest";
|
|
693
694
|
readonly GEMINI_FLASH_LITE_LATEST: "gemini-flash-lite-latest";
|
|
694
695
|
readonly GEMINI_PRO_LATEST: "gemini-pro-latest";
|
|
@@ -698,12 +699,8 @@ declare const Gemini: {
|
|
|
698
699
|
readonly GEMMA_3_1B_IT: "gemma-3-1b-it";
|
|
699
700
|
readonly GEMMA_3N_E4B_IT: "gemma-3n-e4b-it";
|
|
700
701
|
readonly GEMMA_3N_E2B_IT: "gemma-3n-e2b-it";
|
|
701
|
-
readonly DEEP_RESEARCH_PRO_PREVIEW_12_2025: "deep-research-pro-preview-12-2025";
|
|
702
|
-
readonly GEMINI_ROBOTICS_ER_1_5_PREVIEW: "gemini-robotics-er-1.5-preview";
|
|
703
|
-
readonly NANO_BANANA_PRO_PREVIEW: "nano-banana-pro-preview";
|
|
704
|
-
readonly AQA: "aqa";
|
|
705
702
|
};
|
|
706
|
-
readonly DefaultModel: "gemini-
|
|
703
|
+
readonly DefaultModel: "gemini-3-flash-preview";
|
|
707
704
|
};
|
|
708
705
|
|
|
709
706
|
interface GenerateOptions {
|
|
@@ -767,23 +764,16 @@ declare const OpenAI: {
|
|
|
767
764
|
readonly GPT_4_TURBO_2024_04_09: "gpt-4-turbo-2024-04-09";
|
|
768
765
|
readonly O4_MINI: "o4-mini";
|
|
769
766
|
readonly O4_MINI_2025_04_16: "o4-mini-2025-04-16";
|
|
770
|
-
readonly O4_MINI_DEEP_RESEARCH: "o4-mini-deep-research";
|
|
771
|
-
readonly O4_MINI_DEEP_RESEARCH_2025_06_26: "o4-mini-deep-research-2025-06-26";
|
|
772
767
|
readonly O3: "o3";
|
|
773
768
|
readonly O3_2025_04_16: "o3-2025-04-16";
|
|
774
769
|
readonly O3_PRO: "o3-pro";
|
|
775
770
|
readonly O3_PRO_2025_06_10: "o3-pro-2025-06-10";
|
|
776
771
|
readonly O3_MINI: "o3-mini";
|
|
777
772
|
readonly O3_MINI_2025_01_31: "o3-mini-2025-01-31";
|
|
778
|
-
readonly O3_DEEP_RESEARCH: "o3-deep-research";
|
|
779
|
-
readonly O3_DEEP_RESEARCH_2025_06_26: "o3-deep-research-2025-06-26";
|
|
780
773
|
readonly O1: "o1";
|
|
781
774
|
readonly O1_2024_12_17: "o1-2024-12-17";
|
|
782
775
|
readonly O1_PRO: "o1-pro";
|
|
783
776
|
readonly O1_PRO_2025_03_19: "o1-pro-2025-03-19";
|
|
784
|
-
readonly COMPUTER_USE_PREVIEW: "computer-use-preview";
|
|
785
|
-
readonly COMPUTER_USE_PREVIEW_2025_03_11: "computer-use-preview-2025-03-11";
|
|
786
|
-
readonly CHATGPT_IMAGE_LATEST: "chatgpt-image-latest";
|
|
787
777
|
};
|
|
788
778
|
readonly DefaultModel: "gpt-5-mini";
|
|
789
779
|
};
|
|
@@ -797,7 +787,7 @@ type BraveProviderConfig = z$1.infer<typeof BraveProviderConfigSchema>;
|
|
|
797
787
|
declare const braveSearchSchema: z.ZodObject<{
|
|
798
788
|
searchTerm: z.ZodString;
|
|
799
789
|
}, z.core.$strip>;
|
|
800
|
-
declare class BraveSearchTool implements
|
|
790
|
+
declare class BraveSearchTool implements ExecutableTool<typeof braveSearchSchema> {
|
|
801
791
|
name: string;
|
|
802
792
|
description: string;
|
|
803
793
|
schema: z.ZodObject<{
|
|
@@ -822,7 +812,7 @@ declare const calculatorSchema: z$1.ZodObject<{
|
|
|
822
812
|
a: z$1.ZodNumber;
|
|
823
813
|
b: z$1.ZodNumber;
|
|
824
814
|
}, z$1.core.$strip>;
|
|
825
|
-
declare const calculatorTool:
|
|
815
|
+
declare const calculatorTool: ExecutableTool<typeof calculatorSchema>;
|
|
826
816
|
|
|
827
817
|
/**
|
|
828
818
|
* Root tracer that manages writers and creates spans.
|
|
@@ -907,4 +897,4 @@ declare class SimpleWriter implements TraceWriter {
|
|
|
907
897
|
}
|
|
908
898
|
|
|
909
899
|
export { Agent, Anthropic, AxleStopReason, Gemini, History, Instruct, MCP, OpenAI, SimpleWriter, Tracer, anthropic, braveSearchTool, calculatorTool, chatCompletions, compileInstruct, gemini, generate, generateTurn, loadFileContent, openai, parseResponse, stream };
|
|
910
|
-
export type { AIProvider, AgentConfig, AgentHandle, AgentResult, AxleAssistantMessage, AxleMessage, AxleToolCallMessage, AxleToolCallResult, AxleUserMessage, ContentPart, ContentPartFile, ContentPartText, ContentPartThinking, ContentPartToolCall, EventLevel, FileInfo, MCPConfig, MCPHttpConfig, MCPStdioConfig, SimpleWriterOptions, SpanData, SpanOptions, SpanType, StreamEvent, StreamEventCallback,
|
|
900
|
+
export type { AIProvider, AgentConfig, AgentHandle, AgentResult, AxleAssistantMessage, AxleMessage, AxleTool, AxleToolCallMessage, AxleToolCallResult, AxleUserMessage, ContentPart, ContentPartFile, ContentPartText, ContentPartThinking, ContentPartToolCall, EventLevel, ExecutableTool, FileInfo, MCPConfig, MCPHttpConfig, MCPStdioConfig, ServerTool, SimpleWriterOptions, SpanData, SpanOptions, SpanType, StreamEvent, StreamEventCallback, ToolDefinition, ToolResultPart, TraceWriter, TracingContext };
|
package/dist/index.js
CHANGED
|
@@ -1 +1 @@
|
|
|
1
|
-
var E=Object.defineProperty;var r=(n,a)=>E(n,"name",{value:a,configurable:!0});import{D as I,M as L,a as $,b as w,c as F,A as x,g as O,e as q,d as U,f as S}from"./simple-
|
|
1
|
+
var E=Object.defineProperty;var r=(n,a)=>E(n,"name",{value:a,configurable:!0});import{D as I,M as L,a as $,b as w,c as F,A as x,g as O,e as q,d as U,f as S}from"./simple-Cn_DeT3l.js";import{h as ae,H as ie,I as le,i as ce,S as ue,T as me,j as pe,k as de,l as ge,m as fe,n as Me,o as he,p as Te,q as Re,r as ye,s as De}from"./simple-Cn_DeT3l.js";import"@anthropic-ai/sdk";import"zod";import"@google/genai";import"openai";import"glob";import"mime";import"node:fs/promises";import"node:path";import"node:child_process";import"node:util";import"@modelcontextprotocol/sdk/client/index.js";import"@modelcontextprotocol/sdk/client/stdio.js";import"@modelcontextprotocol/sdk/client/streamableHttp.js";import"marked";import"marked-terminal";const _={Models:L,DefaultModel:I},b={Models:w,DefaultModel:$};async function A(n){const{provider:a,model:i,messages:u,system:p,tools:d,tracer:g,options:l}=n;return a.createGenerationRequest(i,{messages:u,system:p,tools:d,context:{tracer:g},options:l})}r(A,"generateTurn");async function G(n){const{provider:a,model:i,messages:u,system:p,tools:d,onToolCall:g,maxIterations:l,tracer:m,options:C}=n,f=[...u],o=[],t={in:0,out:0};let M=0,h;const T=r(e=>{f.push(e),o.push(e)},"addMessage"),c=r(e=>(m?.setResult({kind:"llm",model:i,request:{messages:u},response:{content:e.result==="success"?e.final?.content:null},usage:e.usage?{inputTokens:e.usage.in,outputTokens:e.usage.out}:void 0,finishReason:e.result==="success"?e.final?.finishReason:void 0}),m?.end(e.result==="error"?"error":"ok"),e),"endWithResult"),v=r((e,s)=>{if(!e||s.type==="error"){e?.end("error");return}e.setResult({kind:"llm",model:s.model??i,request:{messages:f},response:{content:s.content},usage:s.usage?{inputTokens:s.usage.in,outputTokens:s.usage.out}:void 0,finishReason:s.finishReason}),e.end()},"setTurnResult");for(;;){if(l!==void 0&&M>=l)return c({result:"error",messages:o,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${l})`}}},usage:t});M+=1;const e=m?.startSpan(`turn-${M}`,{type:"llm"}),s=await A({provider:a,model:i,messages:f,system:p,tools:d,tracer:e,options:C});if(F(t,s),v(e,s),s.type==="error")return c({result:"error",messages:o,error:{type:"model",error:s},usage:t});const R={role:"assistant",id:s.id,model:s.model,content:s.content,finishReason:s.finishReason};if(T(R),h=R,s.finishReason!==x.FunctionCall)return c({result:"success",messages:o,final:h,usage:t});const y=O(s.content);if(y.length===0)return c({result:"success",messages:o,final:h,usage:t});const{results:D,missingTool:k}=await q(y,g,m);if(D.length>0&&T({role:"tool",content:D}),k)return c({result:"error",messages:o,error:{type:"tool",error:k},usage:t})}}r(G,"generate");const H={Models:S,DefaultModel:U};export{ae as Agent,_ as Anthropic,x as AxleStopReason,b as Gemini,ie as History,le as Instruct,ce as MCP,H as OpenAI,ue as SimpleWriter,me as Tracer,pe as anthropic,de as braveSearchTool,ge as calculatorTool,fe as chatCompletions,Me as compileInstruct,he as gemini,G as generate,A as generateTurn,Te as loadFileContent,Re as openai,ye as parseResponse,De as stream};
|
|
@@ -0,0 +1,36 @@
|
|
|
1
|
+
var je=Object.defineProperty;var i=(t,e)=>je(t,"name",{value:e,configurable:!0});import*as O from"zod";import F,{z as $}from"zod";import"glob";import Be from"mime";import{readFile as J,access as qe,stat as He,writeFile as ie,mkdir as Je}from"node:fs/promises";import{resolve as Q,extname as ce,dirname as We}from"node:path";import ze from"@anthropic-ai/sdk";import{FinishReason as R,GoogleGenAI as Ke}from"@google/genai";import Ve from"openai";import{exec as Xe}from"node:child_process";import{promisify as Ze}from"node:util";import{Client as Ye}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Qe}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as et}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{marked as le}from"marked";import{markedTerminal as tt}from"marked-terminal";class V extends Error{static{i(this,"AxleError")}code;id;details;constructor(e,n){super(e,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||"AXLE_ERROR",this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,V.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id&&{id:this.id},...this.details&&{details:this.details},...this.cause&&{cause:ue(this.cause)}}}}function ue(t){return t instanceof Error?{name:t.name,message:t.message,...t.stack&&{stack:t.stack},..."cause"in t&&t.cause&&{cause:ue(t.cause)}}:t}i(ue,"serializeError");var T=(t=>(t.Stop="stop",t.Length="length",t.FunctionCall="function_call",t.Error="error",t.Custom="custom",t.Cancelled="cancelled",t))(T||{});class pe{static{i(this,"History")}system;_messages=[];constructor(e){e&&(this._messages=e)}get messages(){return[...this._messages]}addSystem(e){this.system=e}addUser(e){typeof e=="string"?this._messages.push({role:"user",content:[{type:"text",text:e}]}):this._messages.push({role:"user",content:e})}addAssistant(e){if(typeof e=="string"){const n=e;this._messages.push({role:"assistant",id:crypto.randomUUID(),content:[{type:"text",text:n}],model:"user",finishReason:T.Custom})}else this._messages.push({role:"assistant",...e})}addToolResults(e){this._messages.push({role:"tool",content:e})}add(e){Array.isArray(e)?this._messages.push(...e):this._messages.push(e)}latest(){return this._messages[this._messages.length-1]}toString(){return JSON.stringify({system:this.system,messages:this._messages})}}function nt(t){const{text:e,files:n}=t,s=[];if(e&&s.push({type:"text",text:e}),n)for(const r of n)s.push({type:"file",file:r});return s}i(nt,"toContentParts");function H(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
+
|
|
3
|
+
`)}i(H,"getTextContent");function st(t){return t.filter(e=>e.type==="tool-call")}i(st,"getToolCalls");function rt(t,e){const n=e.usage??{in:0,out:0};t.in+=n.in??0,t.out+=n.out??0}i(rt,"appendUsage");function de(t){return JSON.stringify({error:t})}i(de,"serializeToolError");async function me(t,e,n){const s=[];let r;for(const o of t){const a=n?.startSpan(o.name,{type:"tool"});let l;try{l=await e(o.name,o.parameters)}catch(p){l={type:"error",error:{type:"exception",message:p instanceof Error?p.message:String(p)}}}if(l==null){r={name:o.name,message:`Tool not found: ${o.name}`},a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:null}),a?.end("error"),s.push({id:o.id,name:o.name,content:de({type:"not-found",message:r.message}),isError:!0});break}l.type==="success"?(a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:l.content}),a?.end("ok"),s.push({id:o.id,name:o.name,content:l.content})):(a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:l.error}),a?.end("error"),s.push({id:o.id,name:o.name,content:de(l.error),isError:!0}))}return{results:s,missingTool:r}}i(me,"executeToolCalls");function C(t,e){for(const n of t)n(e)}i(C,"emit");function fe(t){const e=[],n=new AbortController;let s=!1,r,o;const a=new Promise((l,p)=>{r=i(d=>{s=!0,l(d)},"resolveResult"),o=i(d=>{s=!0,p(d)},"rejectResult")});return Promise.resolve().then(()=>ot(t,n.signal,e).then(r,o)),{on(l){e.push(l)},cancel(){s||n.abort()},get final(){return a}}}i(fe,"stream");async function ot(t,e,n){const{provider:s,model:r,messages:o,system:a,tools:l,serverTools:p,onToolCall:d,maxIterations:m,tracer:u,options:c}=t,_=[...o],h=[],f={in:0,out:0};let g=0,x=0;const S=i(E=>{_.push(E),h.push(E)},"addMessage"),k=i(E=>{E.result==="error"&&C(n,{type:"error",error:E.error});const G=E.result==="success"?E.final?.content:E.result==="cancelled"?E.partial?.content:null,D=E.result==="success"?E.final?.finishReason:E.result==="cancelled"?T.Cancelled:void 0;return u?.setResult({kind:"llm",model:r,request:{messages:o},response:{content:G??null},usage:E.usage?{inputTokens:E.usage.in,outputTokens:E.usage.out}:void 0,finishReason:D}),u?.end(E.result==="error"?"error":"ok"),E},"endWithResult"),L=i((E,G,D,I)=>{I();const M=E.length>0?{role:"assistant",id:G,model:D,content:E,finishReason:T.Cancelled}:void 0;return M&&S(M),u?.end("ok"),{result:"cancelled",messages:h,partial:M,usage:f}},"buildCancelledResult");for(;;){if(e.aborted)return L([],"","",()=>{});if(m!==void 0&&x>=m)return k({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${m})`}}},usage:f});x+=1;const E=u?.startSpan(`turn-${x}`,{type:"llm"});E?.startLLMStream();const G=p?{...c,serverTools:p}:c,D=s.createStreamingRequest?.(r,{messages:_,system:a,tools:l,context:{tracer:E},signal:e,options:G});if(!D)throw E?.end("error"),new Error("Provider does not support streaming. Use generate() instead.");const I=[];let j="",M="",B=null,q={in:0,out:0},P=-1,W=null,v="";const ne=new Map;let U=-1;const N=i(()=>{W!==null&&P>=0&&(C(n,{type:W==="text"?"text:end":"thinking:end",index:P,final:v}),W=null,v="",P=-1)},"closePart");for await(const y of D){switch(y.type){case"start":j=y.id,M=y.data.model;break;case"text-start":{N(),I.push({type:"text",text:""}),U=I.length-1,P=g++,W="text",v="",C(n,{type:"text:start",index:P});break}case"text-delta":{const w=I[U];w.text+=y.data.text,v=w.text,E?.appendLLMStream(y.data.text),C(n,{type:"text:delta",index:P,delta:y.data.text,accumulated:v});break}case"text-complete":{N();break}case"thinking-start":{N(),I.push({type:"thinking",text:""}),U=I.length-1,P=g++,W="thinking",v="",C(n,{type:"thinking:start",index:P});break}case"thinking-delta":{const w=I[U];w.text+=y.data.text,v=w.text,C(n,{type:"thinking:delta",index:P,delta:y.data.text,accumulated:v});break}case"thinking-summary-delta":{const w=I[U];w.text+=y.data.text,v=w.text,C(n,{type:"thinking:delta",index:P,delta:y.data.text,accumulated:v});break}case"thinking-complete":{N();break}case"tool-call-start":{N();const w=g++;I.push({type:"tool-call",id:y.data.id,name:y.data.name,parameters:{}}),U=I.length-1,ne.set(y.data.id,w),C(n,{type:"tool:start",index:w,id:y.data.id,name:y.data.name});break}case"tool-call-complete":{const w=I[U];y.data.id&&(w.id=y.data.id),y.data.name&&(w.name=y.data.name),w.parameters=y.data.arguments,y.data.providerMetadata&&(w.providerMetadata=y.data.providerMetadata);break}case"internal-tool-start":{N();const w=g++;I.push({type:"internal-tool",id:y.data.id,name:y.data.name}),U=I.length-1,C(n,{type:"internal-tool:start",index:w,id:y.data.id,name:y.data.name});break}case"internal-tool-complete":{const w=I[U];y.data.output!=null&&(w.output=y.data.output),C(n,{type:"internal-tool:complete",index:y.data.index,id:y.data.id,name:y.data.name,output:y.data.output});break}case"complete":{N(),B=y.data.finishReason,q=y.data.usage;break}case"error":{N();const w=y.data.usage??{in:0,out:0};return f.in+=w.in??0,f.out+=w.out??0,E?.end("error"),k({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:y.data.type,message:y.data.message}}},usage:f})}default:console.warn("[WARN] Unhandled chunk type. Should never happen")}if(e.aborted)break}if(e.aborted)return E?.end("ok"),L(I,j,M,N);if(B===null)return N(),E?.end("error"),k({result:"error",messages:h,error:{type:"model",error:{type:"error",error:{type:"IncompleteStream",message:"Stream ended without a completion signal"}}},usage:f});f.in+=q.in??0,f.out+=q.out??0;const Ue={kind:"llm",model:M,request:{messages:_},response:{content:I},usage:{inputTokens:q.in,outputTokens:q.out},finishReason:B};E?.endLLMStream(Ue),E?.end();const X={role:"assistant",id:j,model:M,content:I,finishReason:B};if(S(X),B!==T.FunctionCall)return k({result:"success",messages:h,final:X,usage:f});const Z=I.filter(y=>y.type==="tool-call");if(Z.length===0)return k({result:"success",messages:h,final:X,usage:f});if(e.aborted)return u?.end("ok"),{result:"cancelled",messages:h,usage:f};const Ge=d?async(y,w)=>d(y,w):async()=>null;let De=0;const Fe=i(async(y,w)=>{const Y=Z[De++],oe=ne.get(Y.id)??-1;C(n,{type:"tool:execute",index:oe,id:Y.id,name:y,parameters:w});const ae=await Ge(y,w);return C(n,{type:"tool:complete",index:oe,id:Y.id,name:y,result:ae??null}),ae},"emittingToolCall"),{results:se,missingTool:re}=await me(Z,Fe,u);if(se.length>0&&S({role:"tool",content:se}),re)return k({result:"error",messages:h,error:{type:"tool",error:re},usage:f})}}i(ot,"run");function at(t,e,n="{{}}"){const s=n==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(s,(r,o)=>{if(o=o.trim(),Object.prototype.hasOwnProperty.call(e,o)){const a=e[o];return a==null?"":String(a)}return r}),t}i(at,"replaceVariables");function z(t){if(t instanceof O.ZodString)return["string","Your answer"];if(t instanceof O.ZodNumber)return["number",42];if(t instanceof O.ZodBoolean)return["boolean",!0];if(t instanceof O.ZodArray){const e=t.element;if(e instanceof O.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof O.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof O.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof O.ZodObject){const[n,s]=z(e);return["object array",[s,s]]}return["array",[]]}if(t instanceof O.ZodObject){const e=t.shape,n={};for(const[s,r]of Object.entries(e)){const[o,a]=z(r);n[s]=a}return["JSON object",n]}if(t instanceof O.ZodOptional){const e=t.unwrap(),[n,s]=z(e);return[`${n} | undefined`,s]}}i(z,"zodToExample");function he(t,e){if(!e)return t;if(Object.keys(e).length===0){if(t.trim()==="{}"||t.trim()==="")return{};throw new Error("Schema is empty, but rawValue is not an empty object representation or empty string.")}const s=it(t),r={};for(const[o,a]of Object.entries(e)){const l=s.tags[o];if(l!==void 0)r[o]=_e(a,l);else if(a.def.type!=="optional")throw new Error(`Expected results with tag ${o} but it does not exist`)}try{const o={};for(const[a,l]of Object.entries(e))a in r&&(o[a]=l.parse(r[a]));return o}catch(o){if(o&&typeof o=="object"&&"issues"in o){const a=o.issues.map(l=>`${l.path.join(".")}: ${l.message}`).join(", ");throw new Error(`Validation failed: ${a}`)}throw o}}i(he,"parseResponse");function _e(t,e){switch(e=e.trim(),t.def.type){case"string":try{return JSON.parse(e)}catch{if(typeof e=="string")return e;throw new Error(`Cannot parse '${e}' as string. Ensure it is a valid JSON string or a plain string.`)}case"number":{const n=parseFloat(e);if(isNaN(n))throw new Error(`Cannot parse '${e}' as number`);return n}case"boolean":{const n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;throw new Error(`Cannot parse '${e}' as boolean. Expected 'true' or 'false'`)}case"array":{if(e==="")return[];try{const n=JSON.parse(e);if(Array.isArray(n))return n}catch{}if(e.includes(","))return e.split(",").map(n=>{const s=n.trim();try{return JSON.parse(s)}catch{return s}}).filter(n=>n!=="")}case"object":{e.includes("```json")&&(e=e.replace(/```json/g,"").replace(/```/g,""));try{return JSON.parse(e)}catch(n){throw new Error(`Cannot parse object as JSON: ${n.message}`)}}case"optional":{const n=t.def.innerType;return _e(n,e)}default:return e}}i(_e,"preprocessValue");function it(t){t.trim().startsWith("```json")&&t.trim().endsWith("```")&&(t=t.trim().slice(7,-3).trim());const e=/<(\w+)>(.*?)<\/\1>/gs,n={};let s=t;s=s.replace(e,(o,a,l)=>(n[a]=l,""));const r=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return s=s.replace(r,(o,a,l)=>(n[a]=l,"")),{tags:n,remaining:s.trim()}}i(it,"parseTaggedSections");function ge(t,e={}){const n={...e,...t.inputs};let s=at(t.prompt,n);if(t.textReferences.length>0)for(const[a,l]of t.textReferences.entries()){const p=l.name?`: ${l.name}`:"";s+=`
|
|
4
|
+
|
|
5
|
+
## Reference ${a+1}${p}
|
|
6
|
+
|
|
7
|
+
\`\`\`${l.content}'''`}let r=`# Instructions
|
|
8
|
+
|
|
9
|
+
`;if((t.schema?Object.keys(t.schema):[]).length>0){r+=`## Output Format Instructions
|
|
10
|
+
`,r+=`
|
|
11
|
+
Here is how you should format your output. Follow the instructions strictly.
|
|
12
|
+
`;for(const[a,l]of Object.entries(t.schema)){const[p,d]=z(l);r+=`
|
|
13
|
+
- Use <${a}></${a}> tags to indicate the answer for ${a}. The answer must be a ${p}.
|
|
14
|
+
Example: <${a}>${JSON.stringify(d)}</${a}>
|
|
15
|
+
`}}if(t.instructions.length>0){r+=`
|
|
16
|
+
## Additional Instructions
|
|
17
|
+
|
|
18
|
+
`;for(const a of t.instructions)r+=`- ${a}
|
|
19
|
+
`}return r+s}i(ge,"compileInstruct");function ct(t){return t.type==="server"}i(ct,"isServerTool");class lt{static{i(this,"Agent")}provider;model;history;tracer;system;tools={};serverTools=[];mcps=[];mcpToolsResolved=!1;eventCallbacks=[];constructor(e){this.provider=e.provider,this.model=e.model,this.history=new pe,this.tracer=e.tracer,this.system=e.system,e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps])}addTool(e){ct(e)?this.serverTools.push(e):this.tools[e.name]=e}addTools(e){for(const n of e)this.addTool(n)}addMcp(e){this.mcps.push(e),this.mcpToolsResolved=!1}addMcps(e){this.mcps.push(...e),this.mcpToolsResolved=!1}hasTools(){return Object.keys(this.tools).length>0||this.serverTools.length>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}send(e,n){let s;if(typeof e=="string")this.history.addUser(e);else{const r=ge(e,n),o=e.files;this.history.addUser(nt({text:r,files:o})),s=e.schema}return this.execute(s)}async resolveMcpTools(){if(!this.mcpToolsResolved){this.tracer?.debug("resolving MCP tools",{count:this.mcps.length});for(const e of this.mcps){const n=await e.listTools({prefix:e.name,tracer:this.tracer});this.addTools(n)}this.mcpToolsResolved=!0}}execute(e){let n=!1,s;const r=(async()=>{if(await this.resolveMcpTools(),n)return{response:null,messages:[],final:void 0,usage:{in:0,out:0}};const o=this.tools,a=Object.values(o).map(u=>({name:u.name,description:u.description,schema:u.schema}));s=fe({provider:this.provider,model:this.model,messages:this.history.messages,system:this.system,tools:a.length>0?a:void 0,serverTools:this.serverTools.length>0?this.serverTools:void 0,tracer:this.tracer,onToolCall:i(async(u,c)=>{const _=o[u];if(!_)return null;try{return{type:"success",content:await _.execute(c)}}catch(h){return{type:"error",error:{type:"execution",message:h instanceof Error?h.message:String(h)}}}},"onToolCall")});for(const u of this.eventCallbacks)s.on(u);const l=await s.final;l.messages.length>0&&this.history.add(l.messages);let p=null,d;if(l.result==="error")throw new V(ut(l.error),{code:l.error.type==="model"?"MODEL_ERROR":"TOOL_ERROR",details:{error:l.error}});if(l.result==="success"){if(d=l.final,d){const u=H(d.content);p=he(u,e)}}else l.result==="cancelled"&&(d=l.partial);const m=l.usage??{in:0,out:0};return{response:p,messages:l.messages,final:d,usage:m}})();return{cancel:i(()=>{n=!0,s?.cancel()},"cancel"),get final(){return r}}}}function ut(t){return t.type==="model"?`Model error: ${t.error.error.message}`:`Tool error (${t.error.name}): ${t.error.message}`}i(ut,"formatGenerateError");async function pt(t,e){const{defaults:n,tag:s}=e;let r=null,o="";if(t)try{o=Q(t),r=await J(o,{encoding:"utf-8"})}catch{throw new Error(`${s} not found, see --help for details`)}else{for(const a of n.formats)try{o=Q(n.name+"."+a),r=await J(o,{encoding:"utf-8"});break}catch{continue}if(r===null)throw new Error(`${s} not found, see --help for details`)}return{content:r,format:o.split(".").pop()??""}}i(pt,"searchAndLoadFile");const ye=20*1024*1024;function dt(t){return t.type==="text"}i(dt,"isTextFileInfo");function mt(t){return t.type==="image"||t.type==="document"}i(mt,"isBase64FileInfo");const ft=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/toml"]);function ht(t){return t.startsWith("text/")||ft.has(t)}i(ht,"isTextLikeMimeType");function _t(t){const e=Be.getType(t);if(!e){const n=ce(t).toLowerCase();throw new Error(`Unsupported file type: ${n||"(no extension)"}`)}if(e.startsWith("image/"))return{type:"image",mimeType:e};if(e==="application/pdf")return{type:"document",mimeType:e};if(ht(e))return{type:"text",mimeType:e};{const n=ce(t).toLowerCase();throw new Error(`Unsupported file type: ${n} (${e})`)}}i(_t,"getFileCategory");async function gt(t,e){const n=Q(t);try{await qe(n)}catch{throw new Error(`File not found: ${t}`)}const s=await He(n);if(s.size>ye)throw new Error(`File too large: ${s.size} bytes. Maximum allowed: ${ye} bytes`);const r=n.split("/").pop()||"",o=_t(n);if((e||(o.type==="text"?"utf-8":"base64"))==="utf-8"){if(o.type!=="text")throw new Error(`Cannot read ${o.type} file as text: ${t}`);const l=await J(n,"utf-8");return{path:n,content:l,mimeType:o.mimeType,size:s.size,name:r,type:"text"}}else{if(o.type==="text")throw new Error(`Cannot read text file as binary: ${t}`);const p=(await J(n)).toString("base64");return{path:n,base64:p,mimeType:o.mimeType,size:s.size,name:r,type:o.type}}}i(gt,"loadFileContent");class yt{static{i(this,"Instruct")}prompt;inputs={};files=[];textReferences=[];instructions=[];schema;constructor(e,n){this.prompt=e,this.schema=n}setInputs(e){this.inputs=e}addInput(e,n){this.inputs[e]=n}addFile(e,n){if(typeof e=="string"){this.textReferences.push({content:e,name:n?.name});return}mt(e)?this.files.push(e):dt(e)&&this.textReferences.push({content:e.content,name:n?.name??e.name})}addInstructions(e){if(typeof e!="string"||e.trim()==="")throw new Error("Instruction must be a non-empty string");this.instructions.push(e)}hasFiles(){return this.files.length>0}}const A={CLAUDE_SONNET_4_6:"claude-sonnet-4-6",CLAUDE_OPUS_4_6:"claude-opus-4-6",CLAUDE_OPUS_4_5_20251101:"claude-opus-4-5-20251101",CLAUDE_OPUS_4_5:"claude-opus-4-5-20251101",CLAUDE_HAIKU_4_5_20251001:"claude-haiku-4-5-20251001",CLAUDE_HAIKU_4_5:"claude-haiku-4-5-20251001",CLAUDE_SONNET_4_5_20250929:"claude-sonnet-4-5-20250929",CLAUDE_SONNET_4_5:"claude-sonnet-4-5-20250929",CLAUDE_OPUS_4_1_20250805:"claude-opus-4-1-20250805",CLAUDE_OPUS_4_1:"claude-opus-4-1-20250805",CLAUDE_OPUS_4_20250514:"claude-opus-4-20250514",CLAUDE_OPUS_4:"claude-opus-4-20250514",CLAUDE_SONNET_4_20250514:"claude-sonnet-4-20250514",CLAUDE_SONNET_4:"claude-sonnet-4-20250514",CLAUDE_3_HAIKU_20240307:"claude-3-haiku-20240307",CLAUDE_3_HAIKU:"claude-3-haiku-20240307"};A.CLAUDE_SONNET_4_6,A.CLAUDE_OPUS_4_6,A.CLAUDE_OPUS_4_5_20251101,A.CLAUDE_HAIKU_4_5_20251001,A.CLAUDE_SONNET_4_5_20250929,A.CLAUDE_OPUS_4_1_20250805,A.CLAUDE_OPUS_4_20250514,A.CLAUDE_SONNET_4_20250514,A.CLAUDE_3_HAIKU_20240307;const xt=A.CLAUDE_HAIKU_4_5;function xe(t){return Array.isArray(t)?t:[t]}i(xe,"arrayify");function Et(t){return new Promise(e=>setTimeout(e,t))}i(Et,"delay");function K(t){if(t==null)return{type:"error",error:{type:"Undetermined",message:"Unknown error occurred"},usage:{in:0,out:0},raw:t};if(t instanceof Error)return{type:"error",error:{type:t.name||"Error",message:t.message||"Unexpected error"},usage:{in:0,out:0},raw:t};if(typeof t=="object"){const e=t,n=e?.error?.error?.type||e?.error?.type||e?.type||e?.code||e?.status||"Undetermined",s=e?.error?.error?.message||e?.error?.message||e?.message||e?.error||"Unexpected error";return{type:"error",error:{type:String(n),message:String(s)},usage:{in:0,out:0},raw:t}}return{type:"error",error:{type:"Undetermined",message:String(t)},usage:{in:0,out:0},raw:t}}i(K,"getUndefinedError");function Ee(t){return t.map(e=>{if(e.role==="assistant"){const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="thinking"?s.redacted?n.push({type:"redacted_thinking",data:s.text}):n.push({type:"thinking",thinking:s.text,signature:s.signature}):s.type==="tool-call"?n.push({type:"tool_use",id:s.id,name:s.name,input:s.parameters}):s.type==="internal-tool"&&(n.push({type:"server_tool_use",id:s.id,name:s.name,input:s.input??{}}),s.output!=null&&n.push({type:"web_search_tool_result",tool_use_id:s.id,content:s.output}));return{role:"assistant",content:n}}if(e.role==="tool")return{role:"user",content:e.content.map(n=>({type:"tool_result",tool_use_id:n.id,content:typeof n.content=="string"?n.content:wt(n.content),...n.isError?{is_error:!0}:{}}))};if(typeof e.content=="string")return{role:"user",content:e.content};{const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="file"&&(s.file.type==="image"?n.push({type:"image",source:{type:"base64",media_type:s.file.mimeType,data:s.file.base64}}):s.file.type==="document"&&s.file.mimeType==="application/pdf"&&n.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:s.file.base64}}));return{role:"user",content:n}}})}i(Ee,"convertToProviderMessages");function Te(t){return t.map(e=>{const n=F.toJSONSchema(e.schema);if(!Tt(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}i(Te,"convertToProviderTools");function we(t){const e=[];for(const n of t)if(n.type==="text")e.push({type:"text",text:n.text});else if(n.type==="thinking")e.push({type:"thinking",text:n.text||"",redacted:!1});else if(n.type==="redacted_thinking")e.push({type:"thinking",text:n.text||"",redacted:!0});else if(n.type==="tool_use"){if(typeof n.input!="object"||n.input===null||Array.isArray(n.input))throw new Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);e.push({type:"tool-call",id:n.id,name:n.name,parameters:n.input})}return e}i(we,"convertToAxleContentParts");function Se(t){switch(t){case"max_tokens":return T.Length;case"end_turn":return T.Stop;case"stop_sequence":return T.Stop;case"tool_use":return T.FunctionCall;case"pause_turn":case"refusal":default:return T.Error}}i(Se,"convertStopReason$1");function Tt(t){return t&&typeof t=="object"&&t.type==="object"}i(Tt,"isObjectSchema");function wt(t){return t.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})}i(wt,"convertToolResultParts");async function St(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,p=a?.tracer,{stop:d,max_tokens:m,...u}=l??{},c={model:n,max_tokens:m??16e3,messages:Ee(s),...r&&{system:r},...d&&{stop_sequences:xe(d)},...o&&{tools:Te(o)},...u};p?.debug("Anthropic request",{request:c});let _;try{const h=await e.messages.create(c);_=It(h)}catch(h){_=K(h)}return p?.debug("Anthropic response",{result:_}),_}i(St,"createGenerationRequest$3");function It(t){const e=Se(t.stop_reason);if(e===T.Error)return{type:"error",error:{type:"Uncaught error",message:`Stop reason is not recognized or unhandled: ${t.stop_reason}`},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t};if(e===T.FunctionCall){const n=we(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:T.FunctionCall,content:n,text:H(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=we(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:H(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}i(It,"convertToAIResponse");function bt(){const t=new Map,e=new Map,n=new Map;function s(r){const o=[];switch(r.type){case"message_start":o.push({type:"start",id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case"message_delta":r.delta.stop_reason&&o.push({type:"complete",data:{finishReason:Se(r.delta.stop_reason),usage:r.usage?{in:r.usage.input_tokens||0,out:r.usage.output_tokens||0}:void 0}});case"message_stop":break;case"content_block_start":if(r.content_block.type==="text")t.set(r.index,"text"),o.push({type:"text-start",data:{index:r.index}});else if(r.content_block.type==="tool_use"){t.set(r.index,"tool");const a=r.content_block;n.set(r.index,{id:a.id,name:a.name,argumentsBuffer:""}),o.push({type:"tool-call-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!1}});else if(r.content_block.type==="redacted_thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!0}});else if(r.content_block.type==="server_tool_use"){t.set(r.index,"internal-tool");const a=r.content_block;e.set(a.id,{index:r.index,name:a.name}),o.push({type:"internal-tool-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="web_search_tool_result"){const a=r.content_block,l=e.get(a.tool_use_id);l&&(o.push({type:"internal-tool-complete",data:{index:l.index,id:a.tool_use_id,name:l.name,output:a.content}}),e.delete(a.tool_use_id))}break;case"content_block_delta":if(r.delta.type==="text_delta")o.push({type:"text-delta",data:{text:r.delta.text,index:r.index}});else if(r.delta.type==="input_json_delta"){const a=n.get(r.index);a&&(a.argumentsBuffer+=r.delta.partial_json)}else r.delta.type==="thinking_delta"?o.push({type:"thinking-delta",data:{text:r.delta.thinking,index:r.index}}):r.delta.type==="signature_delta"||r.delta.type;break;case"content_block_stop":{const a=t.get(r.index);if(a==="text")o.push({type:"text-complete",data:{index:r.index}});else if(a==="thinking")o.push({type:"thinking-complete",data:{index:r.index}});else if(a!=="internal-tool"){if(a==="tool"){const l=n.get(r.index);if(l){try{const p=l.argumentsBuffer?JSON.parse(l.argumentsBuffer):{};o.push({type:"tool-call-complete",data:{index:r.index,id:l.id,name:l.name,arguments:p}})}catch(p){throw new Error(`Failed to parse tool call arguments for ${l.name}: ${p instanceof Error?p.message:String(p)}
|
|
20
|
+
Raw buffer: ${l.argumentsBuffer}`)}n.delete(r.index)}}}t.delete(r.index);break}}return o}return i(s,"handleEvent"),{handleEvent:s}}i(bt,"createAnthropicStreamingAdapter");async function*kt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:p}=t,d=a?.tracer,{stop:m,max_tokens:u,serverTools:c,..._}=p??{},h=o?Te(o):[];if(c){const x={web_search:"web_search_20250305"};for(const S of c){const k=x[S.name]??S.name;h.push({type:k,name:S.name,...S.config})}}const f={model:n,max_tokens:u??At(n),messages:Ee(s),...r&&{system:r},...m&&{stop_sequences:xe(m)},...h.length>0&&{tools:h},..._};d?.debug("Anthropic streaming request",{request:f});const g=bt();try{const x=await e.messages.create({...f,stream:!0},{signal:l});for await(const S of x){const k=g.handleEvent(S);for(const L of k)yield L}}catch(x){if(l?.aborted)return;yield{type:"error",data:{type:"STREAMING_ERROR",message:x instanceof Error?x.message:String(x),raw:x}}}}i(kt,"createStreamingRequest$3");const Ie={[A.CLAUDE_OPUS_4_6]:128e3,[A.CLAUDE_OPUS_4_5_20251101]:64e3,[A.CLAUDE_HAIKU_4_5_20251001]:64e3,[A.CLAUDE_SONNET_4_5_20250929]:64e3,[A.CLAUDE_SONNET_4_20250514]:64e3,[A.CLAUDE_OPUS_4_1_20250805]:32e3,[A.CLAUDE_OPUS_4_20250514]:32e3,[A.CLAUDE_3_HAIKU_20240307]:4096};function At(t){return t in Ie?Ie[t]:t.includes("opus")?t.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:t.includes("sonnet")||t.includes("haiku")?t.match(/claude-3-[0-5]-/)?8192:64e3:16384}i(At,"getMaxTokens");const $t="anthropic";function Mt(t){const e=new ze({apiKey:t});return{name:$t,async createGenerationRequest(n,s){return await St({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:p,options:d}=s;return kt({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:p,options:d})}}}i(Mt,"anthropic");function be(t,e){const n=t.map(Ot).flat(1);return e?[{role:"system",content:e},...n]:n}i(be,"convertAxleMessages");function ke(t){if(t&&t.length>0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:F.toJSONSchema(e.schema)}}))}i(ke,"convertTools");function ee(t){switch(t){case"stop":return T.Stop;case"length":return T.Length;case"tool_calls":case"function_call":return T.FunctionCall;case"content_filter":return T.Error;default:return T.Stop}}i(ee,"convertFinishReason");function Ot(t){switch(t.role){case"tool":return Rt(t);case"assistant":return Ct(t);default:return Lt(t)}}i(Ot,"convertMessage$2");function Rt(t){return t.content.map(e=>({role:"tool",content:typeof e.content=="string"?e.content:e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
21
|
+
`),tool_call_id:e.id}))}i(Rt,"convertToolMessage$2");function Ct(t){const e=t.content.filter(r=>r.type==="tool-call"),n=t.content.filter(r=>r.type==="text"),s=e.length>0?e.map(r=>({type:"function",id:r.id,function:{name:r.name,arguments:JSON.stringify(r.parameters)}})):void 0;return{role:"assistant",content:n.map(r=>r.text).join(""),...s&&{tool_calls:s}}}i(Ct,"convertAssistantMessage$2");function Lt(t){if(typeof t.content=="string")return{role:"user",content:t.content};const e=t.content.map(Pt).filter(n=>n!==null);return e.every(n=>n.type==="text")?{role:"user",content:e.map(n=>n.text).join("")}:{role:"user",content:e}}i(Lt,"convertUserMessage$2");function Pt(t){return t.type==="text"?{type:"text",text:t.text}:t.type==="file"&&t.file.type==="image"?{type:"image_url",image_url:{url:`data:${t.file.mimeType};base64,${t.file.base64}`}}:null}i(Pt,"convertContentPart$2");async function vt(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,apiKey:l,options:p}=t,d=a?.tracer,m=be(s,r),u=ke(o),c={model:n,messages:m,...u&&{tools:u}};p&&(p.temperature!==void 0&&(c.temperature=p.temperature),p.top_p!==void 0&&(c.top_p=p.top_p),p.max_tokens!==void 0&&(c.max_tokens=p.max_tokens),p.frequency_penalty!==void 0&&(c.frequency_penalty=p.frequency_penalty),p.presence_penalty!==void 0&&(c.presence_penalty=p.presence_penalty),p.stop!==void 0&&(c.stop=p.stop)),d?.debug("ChatCompletions request",{request:c});let _;try{const h={"Content-Type":"application/json"};l&&(h.Authorization=`Bearer ${l}`);const f=await fetch(`${e}/chat/completions`,{method:"POST",headers:h,body:JSON.stringify(c)});if(!f.ok){const x=await f.text().catch(()=>"");throw new Error(`HTTP error! status: ${f.status}${x?` - ${x}`:""}`)}const g=await f.json();_=Nt(g)}catch(h){d?.error("Error fetching ChatCompletions response",{error:h instanceof Error?h.message:String(h)}),_=K(h)}return d?.debug("ChatCompletions response",{result:_}),_}i(vt,"createGenerationRequest$2");function Nt(t){const e=t.choices?.[0];if(!e)return{type:"error",error:{type:"ChatCompletionsError",message:"No choices in response"},usage:{in:0,out:0},raw:t};const n=[];if(e.message.reasoning_content&&n.push({type:"thinking",text:e.message.reasoning_content}),e.message.content&&n.push({type:"text",text:e.message.content}),e.message.tool_calls)for(const o of e.message.tool_calls){let a;try{a=JSON.parse(o.function.arguments)}catch(l){throw new Error(`Invalid tool call arguments for ${o.function.name}: ${l instanceof Error?l.message:String(l)}`)}if(typeof a!="object"||a===null||Array.isArray(a))throw new Error(`Invalid tool call arguments for ${o.function.name}: expected object, got ${typeof a}`);n.push({type:"tool-call",id:o.id,name:o.function.name,parameters:a})}const s=n.some(o=>o.type==="tool-call"),r=ee(s?"tool_calls":e.finish_reason);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:r,content:n,text:H(n)??"",usage:{in:t.usage?.prompt_tokens||0,out:t.usage?.completion_tokens||0},raw:t}}i(Nt,"fromModelResponse$2");function Ut(){const t=new Map;let e=0,n=-1,s="",r="",o=null,a,l;function p(u){n<0||(o==="text"?u.push({type:"text-complete",data:{index:n}}):o==="thinking"&&u.push({type:"thinking-complete",data:{index:n}}),o=null,n=-1)}i(p,"closeActivePart");function d(u){const c=[];u.usage&&(l={in:u.usage.prompt_tokens,out:u.usage.completion_tokens});const _=u.choices?.[0];if(!_)return c;s||(s=u.id,r=u.model,c.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}}));const h=_.delta;if(h.reasoning_content&&(o!=="thinking"&&(p(c),n=e++,o="thinking",c.push({type:"thinking-start",data:{index:n}})),c.push({type:"thinking-delta",data:{index:n,text:h.reasoning_content}})),h.content&&(o!=="text"&&(p(c),n=e++,o="text",c.push({type:"text-start",data:{index:n}})),c.push({type:"text-delta",data:{text:h.content,index:n}})),h.tool_calls){p(c);for(const f of h.tool_calls){const g=f.index;if(!t.has(g)){const S=e++,k=f.id||`tool-${S}`;t.set(g,{id:k,name:f.function?.name||"",argumentsBuffer:"",partIdx:S}),c.push({type:"tool-call-start",data:{index:S,id:k,name:f.function?.name||""}})}const x=t.get(g);f.id&&(x.id=f.id),f.function?.name&&(x.name=f.function.name),f.function?.arguments&&(x.argumentsBuffer+=f.function.arguments)}}if(_.finish_reason){p(c);for(const[,f]of t)try{const g=f.argumentsBuffer?JSON.parse(f.argumentsBuffer):{};c.push({type:"tool-call-complete",data:{index:f.partIdx,id:f.id,name:f.name,arguments:g}})}catch(g){throw new Error(`Failed to parse tool call arguments for ${f.name}: ${g instanceof Error?g.message:String(g)}
|
|
22
|
+
Raw buffer: ${f.argumentsBuffer}`)}a=ee(_.finish_reason)}return c}i(d,"handleChunk");function m(){return a===void 0?[]:[{type:"complete",data:{finishReason:a,usage:l??{in:0,out:0}}}]}return i(m,"finalize"),{handleChunk:d,finalize:m}}i(Ut,"createStreamingAdapter$1");async function*Gt(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,signal:l,apiKey:p,options:d}=t,m=a?.tracer;d?.serverTools&&m?.warn("serverTools not supported by ChatCompletions provider");const u=be(s,r),c=ke(o),_={model:n,messages:u,stream:!0,stream_options:{include_usage:!0},...c&&{tools:c}};d&&(d.temperature!==void 0&&(_.temperature=d.temperature),d.top_p!==void 0&&(_.top_p=d.top_p),d.max_tokens!==void 0&&(_.max_tokens=d.max_tokens),d.frequency_penalty!==void 0&&(_.frequency_penalty=d.frequency_penalty),d.presence_penalty!==void 0&&(_.presence_penalty=d.presence_penalty),d.stop!==void 0&&(_.stop=d.stop)),m?.debug("ChatCompletions streaming request",{request:_});const h=Ut();try{const f={"Content-Type":"application/json"};p&&(f.Authorization=`Bearer ${p}`);const g=await fetch(`${e}/chat/completions`,{method:"POST",headers:f,body:JSON.stringify(_),signal:l});if(!g.ok){const L=await g.text().catch(()=>"");throw new Error(`HTTP error! status: ${g.status}${L?` - ${L}`:""}`)}if(!g.body)throw new Error("Response body is null");const x=g.body.getReader(),S=new TextDecoder;let k="";for(;;){const{done:L,value:E}=await x.read();if(L)break;k+=S.decode(E,{stream:!0});const G=k.split(`
|
|
23
|
+
`);k=G.pop()||"";for(const D of G){const I=D.trim();if(!I||I.startsWith(":")||!I.startsWith("data: "))continue;const j=I.slice(6);if(j!=="[DONE]")try{const M=JSON.parse(j),B=h.handleChunk(M);for(const q of B)yield q}catch(M){m?.error("Error parsing ChatCompletions stream chunk",{error:M instanceof Error?M.message:String(M),line:I})}}}for(const L of h.finalize())yield L}catch(f){if(l?.aborted)return;m?.error("Error in ChatCompletions streaming request",{error:f instanceof Error?f.message:String(f)}),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}i(Gt,"createStreamingRequest$2");function Dt(t,e){return{name:"ChatCompletions",async createGenerationRequest(n,s){return await vt({baseUrl:t,model:n,apiKey:e,...s})},createStreamingRequest(n,s){return Gt({baseUrl:t,model:n,apiKey:e,...s})}}}i(Dt,"chatCompletions");const b={GEMINI_3_1_PRO_PREVIEW:"gemini-3.1-pro-preview",GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS:"gemini-3.1-pro-preview-customtools",GEMINI_3_PRO_PREVIEW:"gemini-3-pro-preview",GEMINI_3_FLASH_PREVIEW:"gemini-3-flash-preview",GEMINI_2_5_PRO:"gemini-2.5-pro",GEMINI_2_5_FLASH:"gemini-2.5-flash",GEMINI_2_5_FLASH_LITE:"gemini-2.5-flash-lite",GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:"gemini-2.5-flash-lite-preview-09-2025",GEMINI_2_0_FLASH:"gemini-2.0-flash",GEMINI_2_0_FLASH_001:"gemini-2.0-flash-001",GEMINI_2_0_FLASH_LITE:"gemini-2.0-flash-lite",GEMINI_2_0_FLASH_LITE_001:"gemini-2.0-flash-lite-001",GEMINI_FLASH_LATEST:"gemini-flash-latest",GEMINI_FLASH_LITE_LATEST:"gemini-flash-lite-latest",GEMINI_PRO_LATEST:"gemini-pro-latest",GEMMA_3_27B_IT:"gemma-3-27b-it",GEMMA_3_12B_IT:"gemma-3-12b-it",GEMMA_3_4B_IT:"gemma-3-4b-it",GEMMA_3_1B_IT:"gemma-3-1b-it",GEMMA_3N_E4B_IT:"gemma-3n-e4b-it",GEMMA_3N_E2B_IT:"gemma-3n-e2b-it"};b.GEMINI_3_1_PRO_PREVIEW,b.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,b.GEMINI_3_PRO_PREVIEW,b.GEMINI_3_FLASH_PREVIEW,b.GEMINI_2_5_PRO,b.GEMINI_2_5_FLASH,b.GEMINI_2_5_FLASH_LITE,b.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025,b.GEMINI_2_0_FLASH,b.GEMINI_2_0_FLASH_001,b.GEMINI_2_0_FLASH_LITE,b.GEMINI_2_0_FLASH_LITE_001,b.GEMINI_FLASH_LATEST,b.GEMINI_FLASH_LITE_LATEST,b.GEMINI_PRO_LATEST,b.GEMMA_3_27B_IT,b.GEMMA_3_12B_IT,b.GEMMA_3_4B_IT,b.GEMMA_3_1B_IT,b.GEMMA_3N_E4B_IT,b.GEMMA_3N_E2B_IT;const Ft=b.GEMINI_3_FLASH_PREVIEW;function Ae(t,e,n){const s={};return e&&(s.systemInstruction=e),t&&t.length>0&&(s.tools=t.map(r=>({functionDeclarations:[{name:r.name,description:r.description,parametersJsonSchema:F.toJSONSchema(r.schema)}]}))),n&&Object.assign(s,n),s}i(Ae,"prepareConfig");function $e(t){return t.map(jt).filter(e=>e!==void 0)}i($e,"convertAxleMessagesToGemini");function jt(t){switch(t.role){case"tool":return Bt(t);case"assistant":return qt(t);case"user":return Ht(t)}}i(jt,"convertMessage$1");function Bt(t){return{role:"user",parts:t.content.flatMap(e=>{const n={functionResponse:{id:e.id??void 0,name:e.name,response:{output:typeof e.content=="string"?e.content:e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
24
|
+
`)}}};if(typeof e.content=="string")return[n];const s=e.content.filter(r=>r.type==="image").map(r=>({inlineData:{mimeType:r.mimeType,data:r.data}}));return[n,...s]})}}i(Bt,"convertToolMessage$1");function qt(t){const e=[],n=t.content.filter(r=>r.type==="text");if(n.length>0){const r=n.map(o=>o.text).join("");r&&e.push({text:r})}const s=t.content.filter(r=>r.type==="tool-call");return s.length>0&&e.push(...s.map(r=>{const o={functionCall:{id:r.id??void 0,name:r.name,args:r.parameters}};return r.providerMetadata?.thoughtSignature&&(o.thoughtSignature=r.providerMetadata.thoughtSignature),o})),{role:"model",parts:e}}i(qt,"convertAssistantMessage$1");function Ht(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map(Jt).filter(n=>n!==null)}}i(Ht,"convertUserMessage$1");function Jt(t){return t.type==="text"?{text:t.text}:t.type==="file"&&(t.file.type==="image"||t.file.type==="document")?{inlineData:{mimeType:t.file.mimeType,data:t.file.base64}}:null}i(Jt,"convertContentPart$1");function Me(t){switch(t){case R.STOP:return[!0,T.Stop];case R.MAX_TOKENS:return[!0,T.Length];case R.FINISH_REASON_UNSPECIFIED:case R.SAFETY:case R.RECITATION:case R.LANGUAGE:case R.OTHER:case R.BLOCKLIST:case R.PROHIBITED_CONTENT:case R.SPII:case R.MALFORMED_FUNCTION_CALL:case R.IMAGE_SAFETY:return[!1,T.Error]}}i(Me,"convertStopReason");async function Wt(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,p=a?.tracer,d=l?{...l}:{};d.max_tokens&&(d.maxOutputTokens=d.max_tokens,delete d.max_tokens),d.stop&&(d.stopSequences=Array.isArray(d.stop)?d.stop:[d.stop],delete d.stop),d.top_p!==void 0&&(d.topP=d.top_p,delete d.top_p);const m={contents:$e(s),config:Ae(o,r,d)};p?.debug("Gemini request",{request:m});let u;try{const c=await e.models.generateContent({model:n,...m});u=zt(c,{tracer:p})}catch(c){p?.error(c instanceof Error?c.message:String(c)),u=K(c)}return p?.debug("Gemini response",{result:u}),u}i(Wt,"createGenerationRequest$1");function zt(t,e){const{tracer:n}=e,s=t.usageMetadata.promptTokenCount,r=t.usageMetadata.totalTokenCount-s,o={in:s,out:r};if(!t)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};if(t.promptFeedback&&t.promptFeedback.blockReason)return{type:"error",error:{type:"Blocked",message:`Response blocked by Google AI: ${t.promptFeedback.blockReason}, ${t.promptFeedback.blockReasonMessage}`},usage:o,raw:t};if(!t.candidates||t.candidates.length===0)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};t.candidates.length>1&&n?.warn(`We received ${t.candidates.length} response candidates`);const a=t.candidates[0],p=(a.content?.parts||[]).map(u=>u.text).filter(u=>u!==void 0).join(""),[d,m]=Me(a.finishReason);if(d){const u=[];if(p&&u.push({type:"text",text:p}),t.functionCalls)for(const c of t.functionCalls)if(c.args==null)u.push({type:"tool-call",id:c.id,name:c.name,parameters:{}});else{if(typeof c.args!="object"||Array.isArray(c.args))throw new Error(`Invalid tool call arguments for ${c.name}: expected object, got ${typeof c.args}`);u.push({type:"tool-call",id:c.id,name:c.name,parameters:c.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?T.FunctionCall:m,content:u,text:H(u)??"",usage:o,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${m}`},usage:o,raw:t}}i(zt,"fromModelResponse$1");function Kt(){let t=0,e=-1,n=!1,s="",r="",o=0,a=0,l=null;function p(m){e<0||(l==="text"?m.push({type:"text-complete",data:{index:e}}):l==="thinking"&&m.push({type:"thinking-complete",data:{index:e}}),l=null,e=-1)}i(p,"closeActivePart");function d(m){const u=[];s||(s=m.responseId||`gemini-${Date.now()}`,r=m.modelVersion||"gemini",u.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}})),m.usageMetadata&&(o=m.usageMetadata.promptTokenCount||0,a=(m.usageMetadata.totalTokenCount||0)-o);const c=m.candidates?.[0];if(!c)return u;const _=c.content?.parts||[];for(const h of _){const f="thought"in h&&h.thought===!0;if(f&&h.text?(l!=="thinking"&&(p(u),e=t++,l="thinking",u.push({type:"thinking-start",data:{index:e}})),u.push({type:"thinking-delta",data:{index:e,text:h.text}})):h.text&&!f?(l!=="text"&&(p(u),e=t++,l="text",u.push({type:"text-start",data:{index:e}})),u.push({type:"text-delta",data:{text:h.text,index:e}})):h.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(h))}`),h.functionCall){p(u),n=!0;const g=t++,x=h.functionCall.id||`tool-${g}`;u.push({type:"tool-call-start",data:{index:g,id:x,name:h.functionCall.name}});const S={index:g,id:x,name:h.functionCall.name,arguments:h.functionCall.args??{}},k=h;k.thoughtSignature&&(S.providerMetadata={thoughtSignature:k.thoughtSignature}),u.push({type:"tool-call-complete",data:S})}}if(c.finishReason&&c.finishReason!==R.FINISH_REASON_UNSPECIFIED){p(u);const[h,f]=Me(c.finishReason),g=n?T.FunctionCall:f;!h&&!n?u.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${c.finishReason}`,usage:{in:o,out:a},raw:m}}):u.push({type:"complete",data:{finishReason:g,usage:{in:o,out:a}}})}return u}return i(d,"handleChunk"),{handleChunk:d}}i(Kt,"createGeminiStreamingAdapter");async function*Vt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:p}=t,d=a?.tracer,{serverTools:m,...u}=p??{},c=u?{...u}:{};c.max_tokens&&(c.maxOutputTokens=c.max_tokens,delete c.max_tokens),c.stop&&(c.stopSequences=Array.isArray(c.stop)?c.stop:[c.stop],delete c.stop),c.top_p!==void 0&&(c.topP=c.top_p,delete c.top_p);const _=Ae(o,r,c);if(m){const g={web_search:"googleSearch",code_execution:"codeExecution"};_.tools||(_.tools=[]);for(const x of m){const S=g[x.name]??x.name;_.tools.push({[S]:x.config??{}})}}const h={contents:$e(s),config:_};d?.debug("Gemini streaming request",{request:h});const f=Kt();try{const g=await e.models.generateContentStream({model:n,...h});for await(const x of g){const S=f.handleChunk(x);for(const k of S)yield k}}catch(g){if(l?.aborted)return;d?.error(g instanceof Error?g.message:String(g)),yield{type:"error",data:{type:"STREAMING_ERROR",message:g instanceof Error?g.message:String(g),raw:g}}}}i(Vt,"createStreamingRequest$1");const Xt="Gemini";function Zt(t){const e=new Ke({apiKey:t});return{name:Xt,async createGenerationRequest(n,s){return await Wt({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:p,options:d}=s;return Vt({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:p,options:d})}}}i(Zt,"gemini");const Oe={GPT_5_2:"gpt-5.2",GPT_5_2_2025_12_11:"gpt-5.2-2025-12-11",GPT_5_2_CHAT_LATEST:"gpt-5.2-chat-latest",GPT_5_2_PRO:"gpt-5.2-pro",GPT_5_2_PRO_2025_12_11:"gpt-5.2-pro-2025-12-11",GPT_5_2_CODEX:"gpt-5.2-codex",GPT_5_1:"gpt-5.1",GPT_5_1_2025_11_13:"gpt-5.1-2025-11-13",GPT_5_1_CHAT_LATEST:"gpt-5.1-chat-latest",GPT_5_1_CODEX:"gpt-5.1-codex",GPT_5_1_CODEX_MAX:"gpt-5.1-codex-max",GPT_5_1_CODEX_MINI:"gpt-5.1-codex-mini",GPT_5:"gpt-5",GPT_5_2025_08_07:"gpt-5-2025-08-07",GPT_5_CHAT_LATEST:"gpt-5-chat-latest",GPT_5_CODEX:"gpt-5-codex",GPT_5_MINI:"gpt-5-mini",GPT_5_MINI_2025_08_07:"gpt-5-mini-2025-08-07",GPT_5_NANO:"gpt-5-nano",GPT_5_NANO_2025_08_07:"gpt-5-nano-2025-08-07",GPT_5_PRO:"gpt-5-pro",GPT_5_PRO_2025_10_06:"gpt-5-pro-2025-10-06",GPT_5_SEARCH_API:"gpt-5-search-api",GPT_5_SEARCH_API_2025_10_14:"gpt-5-search-api-2025-10-14",GPT_4_1:"gpt-4.1",GPT_4_1_2025_04_14:"gpt-4.1-2025-04-14",GPT_4_1_MINI:"gpt-4.1-mini",GPT_4_1_MINI_2025_04_14:"gpt-4.1-mini-2025-04-14",GPT_4_1_NANO:"gpt-4.1-nano",GPT_4_1_NANO_2025_04_14:"gpt-4.1-nano-2025-04-14",GPT_4O:"gpt-4o",GPT_4O_2024_11_20:"gpt-4o-2024-11-20",GPT_4O_2024_08_06:"gpt-4o-2024-08-06",GPT_4O_2024_05_13:"gpt-4o-2024-05-13",GPT_4O_MINI:"gpt-4o-mini",GPT_4O_MINI_2024_07_18:"gpt-4o-mini-2024-07-18",GPT_4O_SEARCH_PREVIEW:"gpt-4o-search-preview",GPT_4O_SEARCH_PREVIEW_2025_03_11:"gpt-4o-search-preview-2025-03-11",GPT_4O_MINI_SEARCH_PREVIEW:"gpt-4o-mini-search-preview",GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",GPT_4_TURBO:"gpt-4-turbo",GPT_4_TURBO_2024_04_09:"gpt-4-turbo-2024-04-09",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16",O3:"o3",O3_2025_04_16:"o3-2025-04-16",O3_PRO:"o3-pro",O3_PRO_2025_06_10:"o3-pro-2025-06-10",O3_MINI:"o3-mini",O3_MINI_2025_01_31:"o3-mini-2025-01-31",O1:"o1",O1_2024_12_17:"o1-2024-12-17",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19"},Yt=Oe.GPT_5_MINI;function Re(t){if(t&&t.length>0)return t.map(e=>({type:"function",strict:!0,name:e.name,description:e.description,parameters:F.toJSONSchema(e.schema)}))}i(Re,"prepareTools");function Ce(t){return t.map(Qt).flat(1)}i(Ce,"convertAxleMessageToResponseInput");function Qt(t){switch(t.role){case"tool":return en(t);case"assistant":return tn(t);default:return nn(t)}}i(Qt,"convertMessage");function en(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:typeof e.content=="string"?e.content:e.content.map(n=>n.type==="text"?{type:"input_text",text:n.text}:{type:"input_image",image_url:`data:${n.mimeType};base64,${n.data}`})}))}i(en,"convertToolMessage");function tn(t){const e=[],n=H(t.content);n&&e.push({role:t.role,content:n});const s=t.content.filter(o=>o.type==="tool-call");for(const o of s)e.push({type:"function_call",call_id:o.id,name:o.name,arguments:JSON.stringify(o.parameters)});const r=t.content.filter(o=>o.type==="internal-tool");for(const o of r)o.output!=null&&e.push(o.output);return e}i(tn,"convertAssistantMessage");function nn(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(sn).filter(n=>n!==null);return{role:t.role,content:e}}}i(nn,"convertUserMessage");function sn(t){if(t.type==="text")return{type:"input_text",text:t.text};if(t.type==="file"){if(t.file.type==="image")return{type:"input_image",image_url:`data:${t.file.mimeType};base64,${t.file.base64}`,detail:"auto"};if(t.file.type==="document")return{type:"input_file",filename:t.file.path,file_data:`data:${t.file.mimeType};base64,${t.file.base64}`}}return t.type==="thinking",null}i(sn,"convertContentPart");async function rn(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:l}=t,p=a?.tracer,d=Re(o),m={model:n,input:Ce(s),...r&&{instructions:r},...d?{tools:d}:{},...l};p?.debug("OpenAI ResponsesAPI request",{request:m});let u;try{const c=await e.responses.create(m);u=on(c)}catch(c){p?.error(c instanceof Error?c.message:String(c)),u=K(c)}return p?.debug("OpenAI ResponsesAPI response",{result:u}),u}i(rn,"createGenerationRequest");function on(t){if(t.error)return{type:"error",error:{type:t.error.code||"undetermined",message:t.error.message||"Response generation failed"},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t};const e=t.output?.filter(r=>r.type==="reasoning")?.map(r=>r),n=[];if(e&&e.length>0)for(const r of e){const o=r.summary?.[0]?.text||r.content?.[0]?.text||"";(o||r.encrypted_content)&&n.push({type:"thinking",text:o,...r.encrypted_content&&{encrypted:r.encrypted_content}})}t.output_text&&n.push({type:"text",text:t.output_text});const s=t.output?.filter(r=>r.type==="function_call");if(s&&s.length>0)for(const r of s){const o=r;try{n.push({type:"tool-call",id:o.id||"",name:o.name||"",parameters:o.arguments?JSON.parse(o.arguments):{}})}catch(a){throw new Error(`Failed to parse tool call arguments for ${o.name}: ${a instanceof Error?a.message:String(a)}
|
|
25
|
+
Raw value: ${o.arguments}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?T.Error:T.Stop,content:n,text:H(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}i(on,"fromModelResponse");function an(){let t="",e="",n=0,s=-1,r=!1;const o=new Map,a=new Map,l=new Set(["web_search_call","file_search_call","code_interpreter_call"]),p=new Map;function d(m){const u=[];switch(m.type){case"response.created":{t=m.response.id||`openai-${Date.now()}`,e=m.response.model,u.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{s===-1&&(s=n++,u.push({type:"text-start",data:{index:s}})),u.push({type:"text-delta",data:{text:m.delta,index:s}});break}case"response.output_text.done":{s>=0&&(u.push({type:"text-complete",data:{index:s}}),s=-1);break}case"response.function_call_arguments.delta":{const c=m.item_id;if(!p.has(c)){const h=o.get(c),f=h?.name||"",g=h?.callId||c,x=n++;p.set(c,{id:c,callId:g,name:f,argumentsBuffer:"",partIdx:x}),u.push({type:"tool-call-start",data:{index:x,id:g,name:f}})}const _=p.get(c);_.argumentsBuffer+=m.delta;break}case"response.function_call_arguments.done":{r=!0;const c=m.item_id,_=p.get(c),h=m.name||_?.name||"";if(_){try{const f=m.arguments?JSON.parse(m.arguments):{};u.push({type:"tool-call-complete",data:{index:_.partIdx,id:_.callId,name:h,arguments:f}})}catch(f){throw new Error(`Failed to parse function call arguments for ${h}: ${f instanceof Error?f.message:String(f)}
|
|
26
|
+
Raw value: ${m.arguments}`)}p.delete(c)}break}case"response.completed":{const c=m.response.usage;u.push({type:"complete",data:{finishReason:m.response.incomplete_details?T.Error:r?T.FunctionCall:T.Stop,usage:{in:c?.input_tokens||0,out:c?.output_tokens||0}}});break}case"response.failed":{u.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${m.response.status}`,raw:m}});break}case"response.output_item.added":{if(m.item?.type==="reasoning")s=n++,u.push({type:"thinking-start",data:{index:s}});else if(m.item?.type==="function_call"){const c=m.item,_=c.id||c.call_id;_&&o.set(_,{name:c.name||"",callId:c.call_id||_})}else if(m.item&&l.has(m.item.type)){const c=m.item,_=n++;a.set(c.id,_),u.push({type:"internal-tool-start",data:{index:_,id:c.id,name:c.type}})}break}case"response.output_item.done":{if(m.item?.type==="reasoning"&&s>=0)u.push({type:"thinking-complete",data:{index:s}}),s=-1;else if(m.item&&l.has(m.item.type)){const c=m.item,_=a.get(c.id);_!==void 0&&(u.push({type:"internal-tool-complete",data:{index:_,id:c.id,name:c.type,output:m.item}}),a.delete(c.id))}break}case"response.reasoning_text.delta":{m.delta&&u.push({type:"thinking-delta",data:{index:s,text:m.delta}});break}case"response.reasoning_summary_text.delta":{m.delta&&u.push({type:"thinking-summary-delta",data:{index:s,text:m.delta}});break}case"response.in_progress":case"response.content_part.added":case"response.content_part.done":case"response.reasoning_summary_part.added":case"response.reasoning_summary_part.done":case"response.reasoning_summary_text.done":case"response.reasoning_text.done":case"response.web_search_call.in_progress":case"response.web_search_call.searching":case"response.web_search_call.completed":break;default:console.log(`[OpenAI] unhandled stream event: ${m.type}`)}return u}return i(d,"handleEvent"),{handleEvent:d}}i(an,"createStreamingAdapter");async function*cn(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:l,options:p}=t,d=a?.tracer,{serverTools:m,...u}=p??{},c=Re(o)??[];if(m){const f={web_search:"web_search_preview",code_execution:"code_interpreter"};for(const g of m){const x=f[g.name]??g.name;c.push({type:x,...g.config})}}const _={model:n,input:Ce(s),...r&&{instructions:r},stream:!0,...c.length>0?{tools:c}:{},...u};d?.debug("OpenAI ResponsesAPI streaming request",{request:_});const h=an();try{const f=e.responses.stream(_,...l?[{signal:l}]:[]);for await(const g of f){const x=h.handleEvent(g);for(const S of x)yield S}}catch(f){if(l?.aborted)return;d?.error(f instanceof Error?f.message:String(f)),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}i(cn,"createStreamingRequest");const ln="OpenAI";function un(t){const e=new Ve({apiKey:t});return{name:ln,async createGenerationRequest(n,s){return await rn({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:l,signal:p,options:d}=s;return cn({client:e,model:n,messages:r,system:o,tools:a,runtime:l,signal:p,options:d})}}}i(un,"openai");const pn=O.object({searchTerm:O.string().describe("The search term to query")});class dn{static{i(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=pn;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){const{rateLimit:n}=e;this.apiKey=e["api-key"],this.throttle=n?1100/n:void 0}async execute(e){const{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await Et(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const s=this.apiKey,r="https://api.search.brave.com/res/v1/web/search",o=new URL(r);o.searchParams.append("q",n),o.searchParams.append("format","json");const a=await fetch(o.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":s}});if(!a.ok)throw new Error(`[Brave] HTTP error ${a.status}: ${a.statusText}`);const l=await a.json();return JSON.stringify(l)}catch(s){throw s instanceof Error?new Error(`[Brave] Error fetching search results: ${s.message}`):s}}}const mn=new dn,fn=$.object({operation:$.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:$.number().describe("First operand"),b:$.number().describe("Second operand")}),hn={name:"calculator",description:"Performs basic arithmetic operations",schema:fn,execute:i(async({operation:t,a:e,b:n})=>{switch(t){case"add":return`${e} + ${n} = ${e+n}`;case"subtract":return`${e} - ${n} = ${e-n}`;case"multiply":return`${e} * ${n} = ${e*n}`;case"divide":if(n===0)throw new Error("Cannot divide by zero");return`${e} / ${n} = ${e/n}`;default:throw new Error(`Unknown operation: ${t}`)}},"execute")},_n=Ze(Xe),gn=3e4,yn=1024*1024;async function xn(t,e={}){const{stdout:n,stderr:s}=await _n(t,{cwd:e.cwd,timeout:e.timeout??gn,maxBuffer:e.maxBuffer??yn});return{stdout:n,stderr:s}}i(xn,"runCommand");function En(t){if(t instanceof Error){const e=t;let n=`Error executing command: ${t.message}`;return e.stdout&&(n+=`
|
|
27
|
+
[stdout]: ${e.stdout}`),e.stderr&&(n+=`
|
|
28
|
+
[stderr]: ${e.stderr}`),n}return`Error executing command: ${String(t)}`}i(En,"formatExecError");function Tn(t,e){return e&&e.trim()?`${t}
|
|
29
|
+
[stderr]: ${e}`:t}i(Tn,"formatOutput");const wn=O.object({command:O.string().describe("The shell command to execute")});class Sn{static{i(this,"ExecTool")}name="exec";description="Execute a shell command and return the output.";schema=wn;timeout=3e4;maxBuffer=1024*1024;cwd;constructor(e){e&&this.configure(e)}configure(e){this.timeout=e.timeout??3e4,this.maxBuffer=e.maxBuffer??1024*1024,this.cwd=e.cwd}summarize(e){return e.command}async execute(e){const{command:n}=e;try{const s=await xn(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return Tn(s.stdout,s.stderr)}catch(s){return En(s)}}}const In=new Sn,bn=$.object({path:$.string().describe("The file path to patch"),old_string:$.string().describe("The exact text to find and replace"),new_string:$.string().describe("The replacement text"),start_line:$.number().int().positive().describe("1-indexed start line of the region to match within"),end_line:$.number().int().positive().describe("1-indexed end line (inclusive) of the region to match within")}),kn={name:"patch-file",description:"Patch a file by replacing an exact string match within a specified line range",schema:bn,summarize:i(({path:t,start_line:e,end_line:n})=>`${t}:${e}:${n}`,"summarize"),execute:i(async({path:t,old_string:e,new_string:n,start_line:s,end_line:r})=>{if(r<s)throw new Error(`end_line (${r}) must be >= start_line (${s})`);let o;try{o=await J(t,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to read file "${t}": ${h.message}`):h}const a=o.split(`
|
|
30
|
+
`);if(s>a.length)throw new Error(`start_line (${s}) exceeds file length (${a.length} lines)`);if(r>a.length)throw new Error(`end_line (${r}) exceeds file length (${a.length} lines)`);const p=a.slice(s-1,r).join(`
|
|
31
|
+
`),d=p.indexOf(e);if(d===-1)throw new Error(`old_string not found within lines ${s}-${r} of "${t}"`);if(p.indexOf(e,d+1)!==-1)throw new Error(`old_string matches multiple times within lines ${s}-${r} of "${t}"`);const u=p.replace(e,n),_=[...a.slice(0,s-1),...u.split(`
|
|
32
|
+
`),...a.slice(r)].join(`
|
|
33
|
+
`);try{await ie(t,_,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to write file "${t}": ${h.message}`):h}return`Successfully patched "${t}" (lines ${s}-${r})`},"execute")},An=$.object({path:$.string().describe("The file path to read from")}),$n={name:"read-file",description:"Read the contents of a file from disk",schema:An,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t})=>{try{return await J(t,"utf-8")}catch(e){throw e instanceof Error?new Error(`Failed to read file "${t}": ${e.message}`):e}},"execute")},Mn=$.object({path:$.string().describe("The file path to write to"),content:$.string().describe("The content to write to the file")}),On={name:"write-file",description:"Write content to a file on disk, creating directories if needed",schema:Mn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t,content:e})=>{try{return await Je(We(t),{recursive:!0}),await ie(t,e,"utf-8"),`Successfully wrote ${e.length} characters to "${t}"`}catch(n){throw n instanceof Error?new Error(`Failed to write file "${t}": ${n.message}`):n}},"execute")};function Le(t){try{const e=F.fromJSONSchema(t);return e instanceof F.ZodObject?e.strict():F.object({}).passthrough()}catch{return F.object({}).passthrough()}}i(Le,"jsonSchemaToZod");function Rn(t,e,n){return t.map(s=>Ln(s,e,n))}i(Rn,"createMcpTools");function Cn(t,e){return t.map(n=>{const s=e?`${e}_${n.name}`:n.name,r=Le(n.inputSchema);return{name:s,description:n.description??"",schema:r}})}i(Cn,"createMcpToolDefinitions");function Ln(t,e,n){const s=n?`${n}_${t.name}`:t.name,r=Le(t.inputSchema);return{name:s,description:t.description??"",schema:r,async execute(o){const a=await e.callTool({name:t.name,arguments:o});if("isError"in a&&a.isError)throw new Error(vn(a.content));return Pn(a.content)}}}i(Ln,"createMcpTool");function Pn(t){return t.some(n=>n.type==="image")?t.filter(n=>n.type==="text"||n.type==="image").map(n=>{if(n.type==="text")return{type:"text",text:n.text};const s=n;return{type:"image",data:s.data,mimeType:s.mimeType}}):t.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
34
|
+
`)}i(Pn,"formatToolResult");function vn(t){return t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
35
|
+
`)||"MCP tool execution error"}i(vn,"formatErrorContent");class Nn{static{i(this,"MCP")}config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;const n=e?.tracer?.startSpan("mcp:connect",{type:"internal"});this.client=new Ye({name:"axle",version:"1.0.0"}),this.config.transport==="stdio"?this.transport=new Qe({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new et(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport),this._connected=!0,n?.end("ok")}catch(s){throw n?.end("error"),s}}async listTools(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return Rn(s,n,e?.prefix)}async listToolDefinitions(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return Cn(s,e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.tracer?.debug("mcp:close"),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,n){if(this.cachedMcpTools)return this.cachedMcpTools;n?.debug("mcp:listTools");const s=await e.listTools();return this.cachedMcpTools=s.tools.map(r=>({name:r.name,description:r.description,inputSchema:r.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw new Error("MCP not connected. Call connect() first.");return this.client}}const Pe={debug:0,info:1,warn:2,error:3};class Un{static{i(this,"Tracer")}writers=[];_minLevel="info";get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){const n=this.writers.indexOf(e);n!==-1&&this.writers.splice(n,1)}startSpan(e,n){const s={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.writers.forEach(r=>r.onSpanStart(s)),new te(s,this)}async flush(){for(const e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(n=>n.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(n=>n.onSpanUpdate?.(e))}_notifyEvent(e,n){this.writers.forEach(s=>s.onEvent?.(e,n))}_notifySpanStart(e){this.writers.forEach(n=>n.onSpanStart(e))}_notifyLLMStreamStart(e){this.writers.forEach(n=>n.onLLMStreamStart?.(e))}_notifyLLMStreamChunk(e,n){this.writers.forEach(s=>s.onLLMStreamChunk?.(e,n))}_notifyLLMStreamEnd(e,n){this.writers.forEach(s=>s.onLLMStreamEnd?.(e,n))}_shouldLog(e){return Pe[e]>=Pe[this._minLevel]}}class te{static{i(this,"Span")}data;tracer;ended=!1;llmStreamBuffer="";llmStreamActive=!1;constructor(e,n){this.data=e,this.tracer=n}startSpan(e,n){const s={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.tracer._notifySpanStart(s),new te(s,this.tracer)}end(e="ok"){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,n,s){if(this.ended||!this.tracer._shouldLog(n))return;const r={name:e,timestamp:performance.now(),level:n,attributes:s};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,n){this.addEvent(e,"debug",n)}info(e,n){this.addEvent(e,"info",n)}warn(e,n){this.addEvent(e,"warn",n)}error(e,n){this.addEvent(e,"error",n)}setAttribute(e,n){this.ended||(this.data.attributes[e]=n,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}startLLMStream(){this.ended||(this.llmStreamActive=!0,this.llmStreamBuffer="",this.tracer._notifyLLMStreamStart(this.data))}appendLLMStream(e){this.ended||!this.llmStreamActive||(this.llmStreamBuffer+=e,this.tracer._notifyLLMStreamChunk(this.data,e))}endLLMStream(e){if(this.ended||!this.llmStreamActive)return;this.llmStreamActive=!1;const n={...e,response:{...e.response,content:e.response.content??this.llmStreamBuffer}};this.data.result=n,this.tracer._notifyLLMStreamEnd(this.data,n)}}const ve={debug:0,info:1,warn:2,error:3};let Ne=!1;function Gn(){Ne||(le.use(tt()),Ne=!0)}i(Gn,"ensureMarkedInit");class Dn{static{i(this,"SimpleWriter")}minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??"info",this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return ve[e]>=ve[this.minLevel]}isSpanVisible(e){return!(e.type==="internal"&&!this.showInternal)}findVisibleAncestor(e){let n=e.parentSpanId;for(;n;){const s=this.spans.get(n);if(!s)break;if(this.isSpanVisible(s))return s;n=s.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;const n=this.findVisibleAncestor(e);return n?(this.visibleDepths.get(n.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return"";const e=new Date,n=e.toTimeString().slice(0,8),s=e.getMilliseconds().toString().padStart(3,"0");return`[${n}.${s}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return"";const n=e.endTime-e.startTime;return n<1e3?` (${Math.round(n)}ms)`:` (${(n/1e3).toFixed(2)}s)`}formatIndent(e){return" ".repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return Gn(),le.parse(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,s);const r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatSpanName(e);this.output(`${o}${r}START ${a}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatDuration(e),l=this.formatSpanName(e),p=e.status==="error"?" [ERROR]":"";this.output(`${o}${r}END ${l}${a}${p}`)}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,n){if(!this.shouldShowEvent(n.level))return;this.spans.set(e.spanId,e);let s;if(this.isSpanVisible(e))s=this.visibleDepths.get(e.spanId)??0;else{const u=this.findVisibleAncestor(e);u?s=this.visibleDepths.get(u.spanId)??0:s=0}const r=this.formatIndent(s+1),o=this.formatTimestamp(),a=n.level.toUpperCase().padEnd(5),l=this.markdown&&n.attributes?.markdown===!0,p=n.attributes?Object.entries(n.attributes).filter(([u])=>u!=="markdown"):[];let d=n.name;l&&(d=this.renderMarkdown(d));let m=`${o}${r}${a} ${d}`;if(p.length>0){const u=p.map(([c,_])=>`${c}=${JSON.stringify(_)}`).join(" ");m+=` ${u}`}this.output(m)}onLLMStreamStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const n=this.visibleDepths.get(e.spanId)??0,s=this.formatIndent(n+1),r=this.formatTimestamp();this.output(`${r}${s}INFO LLM streaming started`)}onLLMStreamChunk(e,n){}onLLMStreamEnd(e,n){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s+1),o=this.formatTimestamp(),a=[`model=${n.model}`];if(n.finishReason&&a.push(`finishReason=${n.finishReason}`),n.usage&&(n.usage.inputTokens!==void 0&&a.push(`inputTokens=${n.usage.inputTokens}`),n.usage.outputTokens!==void 0&&a.push(`outputTokens=${n.usage.outputTokens}`)),this.output(`${o}${r}INFO LLM complete ${a.join(" ")}`),this.shouldShowEvent("debug")&&n.response.content){const p=(typeof n.response.content=="string"?n.response.content:JSON.stringify(n.response.content,null,2)).split(`
|
|
36
|
+
`);for(const d of p)this.output(`${o}${r}DEBUG ${d}`)}}}export{T as A,xt as D,pe as H,yt as I,A as M,Dn as S,Un as T,Ft as a,b,rt as c,Yt as d,me as e,Oe as f,st as g,lt as h,Nn as i,Mt as j,mn as k,hn as l,Dt as m,ge as n,Zt as o,gt as p,un as q,he as r,fe as s,V as t,pt as u,$n as v,On as w,kn as x,In as y};
|
package/package.json
CHANGED
package/dist/simple-DbMOgdiX.js
DELETED
|
@@ -1,36 +0,0 @@
|
|
|
1
|
-
var Ue=Object.defineProperty;var i=(t,e)=>Ue(t,"name",{value:e,configurable:!0});import*as R from"zod";import D,{z as k}from"zod";import"glob";import De from"mime";import{readFile as B,access as Fe,stat as je,writeFile as re,mkdir as He}from"node:fs/promises";import{resolve as X,extname as oe,dirname as Be}from"node:path";import qe from"@anthropic-ai/sdk";import{FinishReason as M,GoogleGenAI as We}from"@google/genai";import Ve from"openai";import{exec as Je}from"node:child_process";import{promisify as Ke}from"node:util";import{Client as ze}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as Xe}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as Ze}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import{marked as ae}from"marked";import{markedTerminal as Ye}from"marked-terminal";class V extends Error{static{i(this,"AxleError")}code;id;details;constructor(e,n){super(e,{cause:n?.cause}),this.name=this.constructor.name,this.code=n?.code||"AXLE_ERROR",this.id=n?.id,this.details=n?.details,Object.setPrototypeOf(this,V.prototype)}toJSON(){return{name:this.name,message:this.message,code:this.code,...this.id&&{id:this.id},...this.details&&{details:this.details},...this.cause&&{cause:ie(this.cause)}}}}function ie(t){return t instanceof Error?{name:t.name,message:t.message,...t.stack&&{stack:t.stack},..."cause"in t&&t.cause&&{cause:ie(t.cause)}}:t}i(ie,"serializeError");var I=(t=>(t.Stop="stop",t.Length="length",t.FunctionCall="function_call",t.Error="error",t.Custom="custom",t.Cancelled="cancelled",t))(I||{});class ce{static{i(this,"History")}system;_messages=[];constructor(e){e&&(this._messages=e)}get messages(){return[...this._messages]}addSystem(e){this.system=e}addUser(e){typeof e=="string"?this._messages.push({role:"user",content:[{type:"text",text:e}]}):this._messages.push({role:"user",content:e})}addAssistant(e){if(typeof e=="string"){const n=e;this._messages.push({role:"assistant",id:crypto.randomUUID(),content:[{type:"text",text:n}],model:"user",finishReason:I.Custom})}else this._messages.push({role:"assistant",...e})}addToolResults(e){this._messages.push({role:"tool",content:e})}add(e){Array.isArray(e)?this._messages.push(...e):this._messages.push(e)}latest(){return this._messages[this._messages.length-1]}toString(){return JSON.stringify({system:this.system,messages:this._messages})}}function Qe(t){const{text:e,files:n}=t,s=[];if(e&&s.push({type:"text",text:e}),n)for(const r of n)s.push({type:"file",file:r});return s}i(Qe,"toContentParts");function H(t){return typeof t=="string"?t:t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
2
|
-
|
|
3
|
-
`)}i(H,"getTextContent");function et(t){return t.filter(e=>e.type==="tool-call")}i(et,"getToolCalls");function tt(t,e){const n=e.usage??{in:0,out:0};t.in+=n.in??0,t.out+=n.out??0}i(tt,"appendUsage");function le(t){return JSON.stringify({error:t})}i(le,"serializeToolError");async function ue(t,e,n){const s=[];let r;for(const o of t){const a=n?.startSpan(o.name,{type:"tool"});let c;try{c=await e(o.name,o.parameters)}catch(d){c={type:"error",error:{type:"exception",message:d instanceof Error?d.message:String(d)}}}if(c==null){r={name:o.name,message:`Tool not found: ${o.name}`},a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:null}),a?.end("error"),s.push({id:o.id,name:o.name,content:le({type:"not-found",message:r.message}),isError:!0});break}c.type==="success"?(a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:c.content}),a?.end("ok"),s.push({id:o.id,name:o.name,content:c.content})):(a?.setResult({kind:"tool",name:o.name,input:o.parameters,output:c.error}),a?.end("error"),s.push({id:o.id,name:o.name,content:le(c.error),isError:!0}))}return{results:s,missingTool:r}}i(ue,"executeToolCalls");function P(t,e){for(const n of t)n(e)}i(P,"emit");function pe(t){const e=[],n=new AbortController;let s=!1,r,o;const a=new Promise((c,d)=>{r=i(m=>{s=!0,c(m)},"resolveResult"),o=i(m=>{s=!0,d(m)},"rejectResult")});return Promise.resolve().then(()=>nt(t,n.signal,e).then(r,o)),{on(c){e.push(c)},cancel(){s||n.abort()},get final(){return a}}}i(pe,"stream");async function nt(t,e,n){const{provider:s,model:r,messages:o,system:a,tools:c,onToolCall:d,maxIterations:m,tracer:p,options:u}=t,l=[...o],f=[],h={in:0,out:0};let _=0,E=0;const w=i(y=>{l.push(y),f.push(y)},"addMessage"),b=i(y=>{y.result==="error"&&P(n,{type:"error",error:y.error});const U=y.result==="success"?y.final?.content:y.result==="cancelled"?y.partial?.content:null,A=y.result==="success"?y.final?.finishReason:y.result==="cancelled"?I.Cancelled:void 0;return p?.setResult({kind:"llm",model:r,request:{messages:o},response:{content:U??null},usage:y.usage?{inputTokens:y.usage.in,outputTokens:y.usage.out}:void 0,finishReason:A}),p?.end(y.result==="error"?"error":"ok"),y},"endWithResult"),O=i((y,U,A,F)=>{F();const $=y.length>0?{role:"assistant",id:U,model:A,content:y,finishReason:I.Cancelled}:void 0;return $&&w($),p?.end("ok"),{result:"cancelled",messages:f,partial:$,usage:h}},"buildCancelledResult");for(;;){if(e.aborted)return O([],"","",()=>{});if(m!==void 0&&E>=m)return b({result:"error",messages:f,error:{type:"model",error:{type:"error",error:{type:"MaxIterations",message:`Exceeded max iterations (${m})`}}},usage:h});E+=1;const y=p?.startSpan(`turn-${E}`,{type:"llm"});y?.startLLMStream();const U=s.createStreamingRequest?.(r,{messages:l,system:a,tools:c,context:{tracer:y},signal:e,options:u});if(!U)throw y?.end("error"),new Error("Provider does not support streaming. Use generate() instead.");const A=[];let F="",L="",$=null,N={in:0,out:0},C=-1,j=null,v="";const Q=new Map,G=i(()=>{j!==null&&C>=0&&(P(n,{type:j==="text"?"text:end":"thinking:end",index:C,final:v}),j=null,v="",C=-1)},"closePart");for await(const g of U){switch(g.type){case"start":F=g.id,L=g.data.model;break;case"text-start":{G(),A.push({type:"text",text:""}),C=_++,j="text",v="",P(n,{type:"text:start",index:C});break}case"text-delta":{const T=A[g.data.index];T.text+=g.data.text,v=T.text,y?.appendLLMStream(g.data.text),P(n,{type:"text:delta",index:C,delta:g.data.text,accumulated:v});break}case"text-complete":{G();break}case"thinking-start":{G(),A.push({type:"thinking",text:""}),C=_++,j="thinking",v="",P(n,{type:"thinking:start",index:C});break}case"thinking-delta":{const T=A[g.data.index];T.text+=g.data.text,v=T.text,P(n,{type:"thinking:delta",index:C,delta:g.data.text,accumulated:v});break}case"thinking-summary-delta":{const T=A[g.data.index];T.text+=g.data.text,v=T.text,P(n,{type:"thinking:delta",index:C,delta:g.data.text,accumulated:v});break}case"thinking-complete":{G();break}case"tool-call-start":{G();const T=_++;A.push({type:"tool-call",id:g.data.id,name:g.data.name,parameters:{}}),Q.set(g.data.id,T),P(n,{type:"tool:start",index:T,id:g.data.id,name:g.data.name});break}case"tool-call-complete":{const T=A[g.data.index];g.data.id&&(T.id=g.data.id),g.data.name&&(T.name=g.data.name),T.parameters=g.data.arguments,g.data.providerMetadata&&(T.providerMetadata=g.data.providerMetadata);break}case"internal-tool-start":{G();const T=_++;A.push({type:"internal-tool",id:g.data.id,name:g.data.name}),P(n,{type:"internal-tool:start",index:T,id:g.data.id,name:g.data.name});break}case"internal-tool-complete":{const T=A[g.data.index];g.data.output!=null&&(T.output=g.data.output),P(n,{type:"internal-tool:complete",index:g.data.index,id:g.data.id,name:g.data.name,output:g.data.output});break}case"complete":{G(),$=g.data.finishReason,N=g.data.usage;break}case"error":{G();const T=g.data.usage??{in:0,out:0};return h.in+=T.in??0,h.out+=T.out??0,y?.end("error"),b({result:"error",messages:f,error:{type:"model",error:{type:"error",error:{type:g.data.type,message:g.data.message}}},usage:h})}default:console.warn("[WARN] Unhandled chunk type. Should never happen")}if(e.aborted)break}if(e.aborted)return y?.end("ok"),O(A,F,L,G);if($===null)return G(),y?.end("error"),b({result:"error",messages:f,error:{type:"model",error:{type:"error",error:{type:"IncompleteStream",message:"Stream ended without a completion signal"}}},usage:h});h.in+=N.in??0,h.out+=N.out??0;const Le={kind:"llm",model:L,request:{messages:l},response:{content:A},usage:{inputTokens:N.in,outputTokens:N.out},finishReason:$};y?.endLLMStream(Le),y?.end();const J={role:"assistant",id:F,model:L,content:A,finishReason:$};if(w(J),$!==I.FunctionCall)return b({result:"success",messages:f,final:J,usage:h});const K=A.filter(g=>g.type==="tool-call");if(K.length===0)return b({result:"success",messages:f,final:J,usage:h});if(e.aborted)return p?.end("ok"),{result:"cancelled",messages:f,usage:h};const Ne=d?async(g,T)=>d(g,T):async()=>null;let ve=0;const Ge=i(async(g,T)=>{const z=K[ve++],ne=Q.get(z.id)??-1;P(n,{type:"tool:execute",index:ne,id:z.id,name:g,parameters:T});const se=await Ne(g,T);return P(n,{type:"tool:complete",index:ne,id:z.id,name:g,result:se??null}),se},"emittingToolCall"),{results:ee,missingTool:te}=await ue(K,Ge,p);if(ee.length>0&&w({role:"tool",content:ee}),te)return b({result:"error",messages:f,error:{type:"tool",error:te},usage:h})}}i(nt,"run");function st(t,e,n="{{}}"){const s=n==="{{}}"?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g;return t=t.replace(s,(r,o)=>{if(o=o.trim(),Object.prototype.hasOwnProperty.call(e,o)){const a=e[o];return a==null?"":String(a)}return r}),t}i(st,"replaceVariables");function q(t){if(t instanceof R.ZodString)return["string","Your answer"];if(t instanceof R.ZodNumber)return["number",42];if(t instanceof R.ZodBoolean)return["boolean",!0];if(t instanceof R.ZodArray){const e=t.element;if(e instanceof R.ZodString)return["string array",["answer 1","answer 2","third answer"]];if(e instanceof R.ZodNumber)return["number array",[42,59,3.14]];if(e instanceof R.ZodBoolean)return["boolean array",[!0,!1,!1]];if(e instanceof R.ZodObject){const[n,s]=q(e);return["object array",[s,s]]}return["array",[]]}if(t instanceof R.ZodObject){const e=t.shape,n={};for(const[s,r]of Object.entries(e)){const[o,a]=q(r);n[s]=a}return["JSON object",n]}if(t instanceof R.ZodOptional){const e=t.unwrap(),[n,s]=q(e);return[`${n} | undefined`,s]}}i(q,"zodToExample");function de(t,e){if(!e)return t;if(Object.keys(e).length===0){if(t.trim()==="{}"||t.trim()==="")return{};throw new Error("Schema is empty, but rawValue is not an empty object representation or empty string.")}const s=rt(t),r={};for(const[o,a]of Object.entries(e)){const c=s.tags[o];if(c!==void 0)r[o]=me(a,c);else if(a.def.type!=="optional")throw new Error(`Expected results with tag ${o} but it does not exist`)}try{const o={};for(const[a,c]of Object.entries(e))a in r&&(o[a]=c.parse(r[a]));return o}catch(o){if(o&&typeof o=="object"&&"issues"in o){const a=o.issues.map(c=>`${c.path.join(".")}: ${c.message}`).join(", ");throw new Error(`Validation failed: ${a}`)}throw o}}i(de,"parseResponse");function me(t,e){switch(e=e.trim(),t.def.type){case"string":try{return JSON.parse(e)}catch{if(typeof e=="string")return e;throw new Error(`Cannot parse '${e}' as string. Ensure it is a valid JSON string or a plain string.`)}case"number":{const n=parseFloat(e);if(isNaN(n))throw new Error(`Cannot parse '${e}' as number`);return n}case"boolean":{const n=e.toLowerCase();if(n==="true")return!0;if(n==="false")return!1;throw new Error(`Cannot parse '${e}' as boolean. Expected 'true' or 'false'`)}case"array":{if(e==="")return[];try{const n=JSON.parse(e);if(Array.isArray(n))return n}catch{}if(e.includes(","))return e.split(",").map(n=>{const s=n.trim();try{return JSON.parse(s)}catch{return s}}).filter(n=>n!=="")}case"object":{e.includes("```json")&&(e=e.replace(/```json/g,"").replace(/```/g,""));try{return JSON.parse(e)}catch(n){throw new Error(`Cannot parse object as JSON: ${n.message}`)}}case"optional":{const n=t.def.innerType;return me(n,e)}default:return e}}i(me,"preprocessValue");function rt(t){t.trim().startsWith("```json")&&t.trim().endsWith("```")&&(t=t.trim().slice(7,-3).trim());const e=/<(\w+)>(.*?)<\/\1>/gs,n={};let s=t;s=s.replace(e,(o,a,c)=>(n[a]=c,""));const r=/<(\w+)>(.*?)(?:<\/?\w+>|$)/gs;return s=s.replace(r,(o,a,c)=>(n[a]=c,"")),{tags:n,remaining:s.trim()}}i(rt,"parseTaggedSections");function fe(t,e={}){const n={...e,...t.inputs};let s=st(t.prompt,n);if(t.textReferences.length>0)for(const[a,c]of t.textReferences.entries()){const d=c.name?`: ${c.name}`:"";s+=`
|
|
4
|
-
|
|
5
|
-
## Reference ${a+1}${d}
|
|
6
|
-
|
|
7
|
-
\`\`\`${c.content}'''`}let r=`# Instructions
|
|
8
|
-
|
|
9
|
-
`;if((t.schema?Object.keys(t.schema):[]).length>0){r+=`## Output Format Instructions
|
|
10
|
-
`,r+=`
|
|
11
|
-
Here is how you should format your output. Follow the instructions strictly.
|
|
12
|
-
`;for(const[a,c]of Object.entries(t.schema)){const[d,m]=q(c);r+=`
|
|
13
|
-
- Use <${a}></${a}> tags to indicate the answer for ${a}. The answer must be a ${d}.
|
|
14
|
-
Example: <${a}>${JSON.stringify(m)}</${a}>
|
|
15
|
-
`}}if(t.instructions.length>0){r+=`
|
|
16
|
-
## Additional Instructions
|
|
17
|
-
|
|
18
|
-
`;for(const a of t.instructions)r+=`- ${a}
|
|
19
|
-
`}return r+s}i(fe,"compileInstruct");class ot{static{i(this,"Agent")}provider;model;history;tracer;system;tools={};mcps=[];mcpToolsResolved=!1;eventCallbacks=[];constructor(e){this.provider=e.provider,this.model=e.model,this.history=new ce,this.tracer=e.tracer,this.system=e.system,e.tools&&this.addTools(e.tools),e.mcps&&(this.mcps=[...e.mcps])}addTool(e){this.tools[e.name]=e}addTools(e){for(const n of e)this.tools[n.name]=n}addMcp(e){this.mcps.push(e),this.mcpToolsResolved=!1}addMcps(e){this.mcps.push(...e),this.mcpToolsResolved=!1}hasTools(){return Object.keys(this.tools).length>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}send(e,n){let s;if(typeof e=="string")this.history.addUser(e);else{const r=fe(e,n),o=e.files;this.history.addUser(Qe({text:r,files:o})),s=e.schema}return this.execute(s)}async resolveMcpTools(){if(!this.mcpToolsResolved){this.tracer?.info("resolving MCP tools",{count:this.mcps.length});for(const e of this.mcps){const n=await e.listTools({prefix:e.name,tracer:this.tracer});this.addTools(n)}this.mcpToolsResolved=!0}}execute(e){let n=!1,s;const r=(async()=>{if(await this.resolveMcpTools(),n)return{response:null,messages:[],final:void 0,usage:{in:0,out:0}};const o=this.tools,a=Object.values(o).map(u=>({name:u.name,description:u.description,schema:u.schema}));s=pe({provider:this.provider,model:this.model,messages:this.history.messages,system:this.system,tools:a.length>0?a:void 0,tracer:this.tracer,onToolCall:i(async(u,l)=>{const f=o[u];if(!f)return null;try{return{type:"success",content:await f.execute(l)}}catch(h){return{type:"error",error:{type:"execution",message:h instanceof Error?h.message:String(h)}}}},"onToolCall")});for(const u of this.eventCallbacks)s.on(u);const c=await s.final;c.messages.length>0&&this.history.add(c.messages);let d=null,m;if(c.result==="error")throw new V(at(c.error),{code:c.error.type==="model"?"MODEL_ERROR":"TOOL_ERROR",details:{error:c.error}});if(c.result==="success"){if(m=c.final,m){const u=H(m.content);d=de(u,e)}}else c.result==="cancelled"&&(m=c.partial);const p=c.usage??{in:0,out:0};return{response:d,messages:c.messages,final:m,usage:p}})();return{cancel:i(()=>{n=!0,s?.cancel()},"cancel"),get final(){return r}}}}function at(t){return t.type==="model"?`Model error: ${t.error.error.message}`:`Tool error (${t.error.name}): ${t.error.message}`}i(at,"formatGenerateError");async function it(t,e){const{defaults:n,tag:s}=e;let r=null,o="";if(t)try{o=X(t),r=await B(o,{encoding:"utf-8"})}catch{throw new Error(`${s} not found, see --help for details`)}else{for(const a of n.formats)try{o=X(n.name+"."+a),r=await B(o,{encoding:"utf-8"});break}catch{continue}if(r===null)throw new Error(`${s} not found, see --help for details`)}return{content:r,format:o.split(".").pop()??""}}i(it,"searchAndLoadFile");const he=20*1024*1024;function ct(t){return t.type==="text"}i(ct,"isTextFileInfo");function lt(t){return t.type==="image"||t.type==="document"}i(lt,"isBase64FileInfo");const ut=new Set(["application/json","application/xml","application/yaml","application/x-yaml","application/toml"]);function pt(t){return t.startsWith("text/")||ut.has(t)}i(pt,"isTextLikeMimeType");function dt(t){const e=De.getType(t);if(!e){const n=oe(t).toLowerCase();throw new Error(`Unsupported file type: ${n||"(no extension)"}`)}if(e.startsWith("image/"))return{type:"image",mimeType:e};if(e==="application/pdf")return{type:"document",mimeType:e};if(pt(e))return{type:"text",mimeType:e};{const n=oe(t).toLowerCase();throw new Error(`Unsupported file type: ${n} (${e})`)}}i(dt,"getFileCategory");async function mt(t,e){const n=X(t);try{await Fe(n)}catch{throw new Error(`File not found: ${t}`)}const s=await je(n);if(s.size>he)throw new Error(`File too large: ${s.size} bytes. Maximum allowed: ${he} bytes`);const r=n.split("/").pop()||"",o=dt(n);if((e||(o.type==="text"?"utf-8":"base64"))==="utf-8"){if(o.type!=="text")throw new Error(`Cannot read ${o.type} file as text: ${t}`);const c=await B(n,"utf-8");return{path:n,content:c,mimeType:o.mimeType,size:s.size,name:r,type:"text"}}else{if(o.type==="text")throw new Error(`Cannot read text file as binary: ${t}`);const d=(await B(n)).toString("base64");return{path:n,base64:d,mimeType:o.mimeType,size:s.size,name:r,type:o.type}}}i(mt,"loadFileContent");class ft{static{i(this,"Instruct")}prompt;inputs={};files=[];textReferences=[];instructions=[];schema;constructor(e,n){this.prompt=e,this.schema=n}setInputs(e){this.inputs=e}addInput(e,n){this.inputs[e]=n}addFile(e,n){if(typeof e=="string"){this.textReferences.push({content:e,name:n?.name});return}lt(e)?this.files.push(e):ct(e)&&this.textReferences.push({content:e.content,name:n?.name??e.name})}addInstructions(e){if(typeof e!="string"||e.trim()==="")throw new Error("Instruction must be a non-empty string");this.instructions.push(e)}hasFiles(){return this.files.length>0}}const S={CLAUDE_SONNET_4_6:"claude-sonnet-4-6",CLAUDE_OPUS_4_6:"claude-opus-4-6",CLAUDE_OPUS_4_5_20251101:"claude-opus-4-5-20251101",CLAUDE_OPUS_4_5:"claude-opus-4-5-20251101",CLAUDE_HAIKU_4_5_20251001:"claude-haiku-4-5-20251001",CLAUDE_HAIKU_4_5:"claude-haiku-4-5-20251001",CLAUDE_SONNET_4_5_20250929:"claude-sonnet-4-5-20250929",CLAUDE_SONNET_4_5:"claude-sonnet-4-5-20250929",CLAUDE_OPUS_4_1_20250805:"claude-opus-4-1-20250805",CLAUDE_OPUS_4_1:"claude-opus-4-1-20250805",CLAUDE_OPUS_4_20250514:"claude-opus-4-20250514",CLAUDE_OPUS_4:"claude-opus-4-20250514",CLAUDE_SONNET_4_20250514:"claude-sonnet-4-20250514",CLAUDE_SONNET_4:"claude-sonnet-4-20250514",CLAUDE_3_HAIKU_20240307:"claude-3-haiku-20240307",CLAUDE_3_HAIKU:"claude-3-haiku-20240307"};S.CLAUDE_SONNET_4_6,S.CLAUDE_OPUS_4_6,S.CLAUDE_OPUS_4_5_20251101,S.CLAUDE_HAIKU_4_5_20251001,S.CLAUDE_SONNET_4_5_20250929,S.CLAUDE_OPUS_4_1_20250805,S.CLAUDE_OPUS_4_20250514,S.CLAUDE_SONNET_4_20250514,S.CLAUDE_3_HAIKU_20240307;const ht=S.CLAUDE_HAIKU_4_5;function _e(t){return Array.isArray(t)?t:[t]}i(_e,"arrayify");function _t(t){return new Promise(e=>setTimeout(e,t))}i(_t,"delay");function W(t){if(t==null)return{type:"error",error:{type:"Undetermined",message:"Unknown error occurred"},usage:{in:0,out:0},raw:t};if(t instanceof Error)return{type:"error",error:{type:t.name||"Error",message:t.message||"Unexpected error"},usage:{in:0,out:0},raw:t};if(typeof t=="object"){const e=t,n=e?.error?.error?.type||e?.error?.type||e?.type||e?.code||e?.status||"Undetermined",s=e?.error?.error?.message||e?.error?.message||e?.message||e?.error||"Unexpected error";return{type:"error",error:{type:String(n),message:String(s)},usage:{in:0,out:0},raw:t}}return{type:"error",error:{type:"Undetermined",message:String(t)},usage:{in:0,out:0},raw:t}}i(W,"getUndefinedError");function ge(t){return t.map(e=>{if(e.role==="assistant"){const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="thinking"?s.redacted?n.push({type:"redacted_thinking",data:s.text}):n.push({type:"thinking",thinking:s.text,signature:s.signature}):s.type==="tool-call"&&n.push({type:"tool_use",id:s.id,name:s.name,input:s.parameters});return{role:"assistant",content:n}}if(e.role==="tool")return{role:"user",content:e.content.map(n=>({type:"tool_result",tool_use_id:n.id,content:typeof n.content=="string"?n.content:yt(n.content),...n.isError?{is_error:!0}:{}}))};if(typeof e.content=="string")return{role:"user",content:e.content};{const n=[];for(const s of e.content)s.type==="text"?n.push({type:"text",text:s.text}):s.type==="file"&&(s.file.type==="image"?n.push({type:"image",source:{type:"base64",media_type:s.file.mimeType,data:s.file.base64}}):s.file.type==="document"&&s.file.mimeType==="application/pdf"&&n.push({type:"document",source:{type:"base64",media_type:"application/pdf",data:s.file.base64}}));return{role:"user",content:n}}})}i(ge,"convertToProviderMessages");function ye(t){return t.map(e=>{const n=D.toJSONSchema(e.schema);if(!gt(n))throw new Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:n}})}i(ye,"convertToProviderTools");function Ee(t){const e=[];for(const n of t)if(n.type==="text")e.push({type:"text",text:n.text});else if(n.type==="thinking")e.push({type:"thinking",text:n.text||"",redacted:!1});else if(n.type==="redacted_thinking")e.push({type:"thinking",text:n.text||"",redacted:!0});else if(n.type==="tool_use"){if(typeof n.input!="object"||n.input===null||Array.isArray(n.input))throw new Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);e.push({type:"tool-call",id:n.id,name:n.name,parameters:n.input})}return e}i(Ee,"convertToAxleContentParts");function xe(t){switch(t){case"max_tokens":return I.Length;case"end_turn":return I.Stop;case"stop_sequence":return I.Stop;case"tool_use":return I.FunctionCall;case"pause_turn":case"refusal":default:return I.Error}}i(xe,"convertStopReason$1");function gt(t){return t&&typeof t=="object"&&t.type==="object"}i(gt,"isObjectSchema");function yt(t){return t.map(e=>e.type==="text"?{type:"text",text:e.text}:{type:"image",source:{type:"base64",media_type:e.mimeType,data:e.data}})}i(yt,"convertToolResultParts");async function Et(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:c}=t,d=a?.tracer,{stop:m,max_tokens:p,...u}=c??{},l={model:n,max_tokens:p??16e3,messages:ge(s),...r&&{system:r},...m&&{stop_sequences:_e(m)},...o&&{tools:ye(o)},...u};d?.debug("Anthropic request",{request:l});let f;try{const h=await e.messages.create(l);f=xt(h)}catch(h){f=W(h)}return d?.debug("Anthropic response",{result:f}),f}i(Et,"createGenerationRequest$3");function xt(t){const e=xe(t.stop_reason);if(e===I.Error)return{type:"error",error:{type:"Uncaught error",message:`Stop reason is not recognized or unhandled: ${t.stop_reason}`},usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t};if(e===I.FunctionCall){const n=Ee(t.content);return{type:"success",id:t.id,model:t.model,role:t.role,finishReason:I.FunctionCall,content:n,text:H(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}if(t.type=="message"){const n=Ee(t.content);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:e,content:n,text:H(n)??"",usage:{in:t.usage.input_tokens,out:t.usage.output_tokens},raw:t}}}i(xt,"convertToAIResponse");function It(){const t=new Map,e=new Map,n=new Map;function s(r){const o=[];switch(r.type){case"message_start":o.push({type:"start",id:r.message.id,data:{model:r.message.model,timestamp:Date.now()}});break;case"message_delta":r.delta.stop_reason&&o.push({type:"complete",data:{finishReason:xe(r.delta.stop_reason),usage:r.usage?{in:r.usage.input_tokens||0,out:r.usage.output_tokens||0}:void 0}});case"message_stop":break;case"content_block_start":if(r.content_block.type==="text")t.set(r.index,"text"),o.push({type:"text-start",data:{index:r.index}});else if(r.content_block.type==="tool_use"){t.set(r.index,"tool");const a=r.content_block;n.set(r.index,{id:a.id,name:a.name,argumentsBuffer:""}),o.push({type:"tool-call-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!1}});else if(r.content_block.type==="redacted_thinking")t.set(r.index,"thinking"),o.push({type:"thinking-start",data:{index:r.index,redacted:!0}});else if(r.content_block.type==="server_tool_use"){t.set(r.index,"internal-tool");const a=r.content_block;e.set(a.id,{index:r.index,name:a.name}),o.push({type:"internal-tool-start",data:{index:r.index,id:a.id,name:a.name}})}else if(r.content_block.type==="web_search_tool_result"){const a=r.content_block,c=e.get(a.tool_use_id);c&&(o.push({type:"internal-tool-complete",data:{index:c.index,id:a.tool_use_id,name:c.name,output:a.content}}),e.delete(a.tool_use_id))}break;case"content_block_delta":if(r.delta.type==="text_delta")o.push({type:"text-delta",data:{text:r.delta.text,index:r.index}});else if(r.delta.type==="input_json_delta"){const a=n.get(r.index);a&&(a.argumentsBuffer+=r.delta.partial_json)}else r.delta.type==="thinking_delta"?o.push({type:"thinking-delta",data:{text:r.delta.thinking,index:r.index}}):r.delta.type==="signature_delta"||r.delta.type;break;case"content_block_stop":{const a=t.get(r.index);if(a==="text")o.push({type:"text-complete",data:{index:r.index}});else if(a==="thinking")o.push({type:"thinking-complete",data:{index:r.index}});else if(a!=="internal-tool"){if(a==="tool"){const c=n.get(r.index);if(c){try{const d=c.argumentsBuffer?JSON.parse(c.argumentsBuffer):{};o.push({type:"tool-call-complete",data:{index:r.index,id:c.id,name:c.name,arguments:d}})}catch(d){throw new Error(`Failed to parse tool call arguments for ${c.name}: ${d instanceof Error?d.message:String(d)}
|
|
20
|
-
Raw buffer: ${c.argumentsBuffer}`)}n.delete(r.index)}}}t.delete(r.index);break}}return o}return i(s,"handleEvent"),{handleEvent:s}}i(It,"createAnthropicStreamingAdapter");async function*Tt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:c,options:d}=t,m=a?.tracer,{stop:p,max_tokens:u,...l}=d??{},f={model:n,max_tokens:u??St(n),messages:ge(s),...r&&{system:r},...p&&{stop_sequences:_e(p)},...o&&{tools:ye(o)},...l};m?.debug("Anthropic streaming request",{request:f});const h=It();try{const _=await e.messages.create({...f,stream:!0},{signal:c});for await(const E of _){const w=h.handleEvent(E);for(const b of w)yield b}}catch(_){if(c?.aborted)return;yield{type:"error",data:{type:"STREAMING_ERROR",message:_ instanceof Error?_.message:String(_),raw:_}}}}i(Tt,"createStreamingRequest$3");const Ie={[S.CLAUDE_OPUS_4_6]:128e3,[S.CLAUDE_OPUS_4_5_20251101]:64e3,[S.CLAUDE_HAIKU_4_5_20251001]:64e3,[S.CLAUDE_SONNET_4_5_20250929]:64e3,[S.CLAUDE_SONNET_4_20250514]:64e3,[S.CLAUDE_3_7_SONNET_20250219]:64e3,[S.CLAUDE_OPUS_4_1_20250805]:32e3,[S.CLAUDE_OPUS_4_20250514]:32e3,[S.CLAUDE_3_5_HAIKU_20241022]:8192,[S.CLAUDE_3_HAIKU_20240307]:4096};function St(t){return t in Ie?Ie[t]:t.includes("opus")?t.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:t.includes("sonnet")||t.includes("haiku")?t.match(/claude-3-[0-5]-/)?8192:64e3:16384}i(St,"getMaxTokens");const wt="anthropic";function At(t){const e=new qe({apiKey:t});return{name:wt,async createGenerationRequest(n,s){return await Et({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:c,signal:d,options:m}=s;return Tt({client:e,model:n,messages:r,system:o,tools:a,runtime:c,signal:d,options:m})}}}i(At,"anthropic");function Te(t,e){const n=t.map(bt).flat(1);return e?[{role:"system",content:e},...n]:n}i(Te,"convertAxleMessages");function Se(t){if(t&&t.length>0)return t.map(e=>({type:"function",function:{name:e.name,description:e.description,parameters:D.toJSONSchema(e.schema)}}))}i(Se,"convertTools");function Z(t){switch(t){case"stop":return I.Stop;case"length":return I.Length;case"tool_calls":case"function_call":return I.FunctionCall;case"content_filter":return I.Error;default:return I.Stop}}i(Z,"convertFinishReason");function bt(t){switch(t.role){case"tool":return kt(t);case"assistant":return Rt(t);default:return Mt(t)}}i(bt,"convertMessage$2");function kt(t){return t.content.map(e=>({role:"tool",content:typeof e.content=="string"?e.content:e.content.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
21
|
-
`),tool_call_id:e.id}))}i(kt,"convertToolMessage$2");function Rt(t){const e=t.content.filter(r=>r.type==="tool-call"),n=t.content.filter(r=>r.type==="text"),s=e.length>0?e.map(r=>({type:"function",id:r.id,function:{name:r.name,arguments:JSON.stringify(r.parameters)}})):void 0;return{role:"assistant",content:n.map(r=>r.text).join(""),...s&&{tool_calls:s}}}i(Rt,"convertAssistantMessage$2");function Mt(t){if(typeof t.content=="string")return{role:"user",content:t.content};const e=t.content.map(Ot).filter(n=>n!==null);return e.every(n=>n.type==="text")?{role:"user",content:e.map(n=>n.text).join("")}:{role:"user",content:e}}i(Mt,"convertUserMessage$2");function Ot(t){return t.type==="text"?{type:"text",text:t.text}:t.type==="file"&&t.file.type==="image"?{type:"image_url",image_url:{url:`data:${t.file.mimeType};base64,${t.file.base64}`}}:null}i(Ot,"convertContentPart$2");async function $t(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,apiKey:c,options:d}=t,m=a?.tracer,p=Te(s,r),u=Se(o),l={model:n,messages:p,...u&&{tools:u}};d&&(d.temperature!==void 0&&(l.temperature=d.temperature),d.top_p!==void 0&&(l.top_p=d.top_p),d.max_tokens!==void 0&&(l.max_tokens=d.max_tokens),d.frequency_penalty!==void 0&&(l.frequency_penalty=d.frequency_penalty),d.presence_penalty!==void 0&&(l.presence_penalty=d.presence_penalty),d.stop!==void 0&&(l.stop=d.stop)),m?.debug("ChatCompletions request",{request:l});let f;try{const h={"Content-Type":"application/json"};c&&(h.Authorization=`Bearer ${c}`);const _=await fetch(`${e}/chat/completions`,{method:"POST",headers:h,body:JSON.stringify(l)});if(!_.ok){const w=await _.text().catch(()=>"");throw new Error(`HTTP error! status: ${_.status}${w?` - ${w}`:""}`)}const E=await _.json();f=Ct(E)}catch(h){m?.error("Error fetching ChatCompletions response",{error:h instanceof Error?h.message:String(h)}),f=W(h)}return m?.debug("ChatCompletions response",{result:f}),f}i($t,"createGenerationRequest$2");function Ct(t){const e=t.choices?.[0];if(!e)return{type:"error",error:{type:"ChatCompletionsError",message:"No choices in response"},usage:{in:0,out:0},raw:t};const n=[];if(e.message.reasoning_content&&n.push({type:"thinking",text:e.message.reasoning_content}),e.message.content&&n.push({type:"text",text:e.message.content}),e.message.tool_calls)for(const o of e.message.tool_calls){let a;try{a=JSON.parse(o.function.arguments)}catch(c){throw new Error(`Invalid tool call arguments for ${o.function.name}: ${c instanceof Error?c.message:String(c)}`)}if(typeof a!="object"||a===null||Array.isArray(a))throw new Error(`Invalid tool call arguments for ${o.function.name}: expected object, got ${typeof a}`);n.push({type:"tool-call",id:o.id,name:o.function.name,parameters:a})}const s=n.some(o=>o.type==="tool-call"),r=Z(s?"tool_calls":e.finish_reason);return{type:"success",id:t.id,model:t.model,role:"assistant",finishReason:r,content:n,text:H(n)??"",usage:{in:t.usage?.prompt_tokens||0,out:t.usage?.completion_tokens||0},raw:t}}i(Ct,"fromModelResponse$2");function Pt(){const t=new Map;let e=0,n=-1,s="",r="",o=null,a,c;function d(u){n<0||(o==="text"?u.push({type:"text-complete",data:{index:n}}):o==="thinking"&&u.push({type:"thinking-complete",data:{index:n}}),o=null,n=-1)}i(d,"closeActivePart");function m(u){const l=[];u.usage&&(c={in:u.usage.prompt_tokens,out:u.usage.completion_tokens});const f=u.choices?.[0];if(!f)return l;s||(s=u.id,r=u.model,l.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}}));const h=f.delta;if(h.reasoning_content&&(o!=="thinking"&&(d(l),n=e++,o="thinking",l.push({type:"thinking-start",data:{index:n}})),l.push({type:"thinking-delta",data:{index:n,text:h.reasoning_content}})),h.content&&(o!=="text"&&(d(l),n=e++,o="text",l.push({type:"text-start",data:{index:n}})),l.push({type:"text-delta",data:{text:h.content,index:n}})),h.tool_calls){d(l);for(const _ of h.tool_calls){const E=_.index;if(!t.has(E)){const b=e++,O=_.id||`tool-${b}`;t.set(E,{id:O,name:_.function?.name||"",argumentsBuffer:"",partIdx:b}),l.push({type:"tool-call-start",data:{index:b,id:O,name:_.function?.name||""}})}const w=t.get(E);_.id&&(w.id=_.id),_.function?.name&&(w.name=_.function.name),_.function?.arguments&&(w.argumentsBuffer+=_.function.arguments)}}if(f.finish_reason){d(l);for(const[,_]of t)try{const E=_.argumentsBuffer?JSON.parse(_.argumentsBuffer):{};l.push({type:"tool-call-complete",data:{index:_.partIdx,id:_.id,name:_.name,arguments:E}})}catch(E){throw new Error(`Failed to parse tool call arguments for ${_.name}: ${E instanceof Error?E.message:String(E)}
|
|
22
|
-
Raw buffer: ${_.argumentsBuffer}`)}a=Z(f.finish_reason)}return l}i(m,"handleChunk");function p(){return a===void 0?[]:[{type:"complete",data:{finishReason:a,usage:c??{in:0,out:0}}}]}return i(p,"finalize"),{handleChunk:m,finalize:p}}i(Pt,"createStreamingAdapter$1");async function*Lt(t){const{baseUrl:e,model:n,messages:s,system:r,tools:o,context:a,signal:c,apiKey:d,options:m}=t,p=a?.tracer,u=Te(s,r),l=Se(o),f={model:n,messages:u,stream:!0,stream_options:{include_usage:!0},...l&&{tools:l}};m&&(m.temperature!==void 0&&(f.temperature=m.temperature),m.top_p!==void 0&&(f.top_p=m.top_p),m.max_tokens!==void 0&&(f.max_tokens=m.max_tokens),m.frequency_penalty!==void 0&&(f.frequency_penalty=m.frequency_penalty),m.presence_penalty!==void 0&&(f.presence_penalty=m.presence_penalty),m.stop!==void 0&&(f.stop=m.stop)),p?.debug("ChatCompletions streaming request",{request:f});const h=Pt();try{const _={"Content-Type":"application/json"};d&&(_.Authorization=`Bearer ${d}`);const E=await fetch(`${e}/chat/completions`,{method:"POST",headers:_,body:JSON.stringify(f),signal:c});if(!E.ok){const y=await E.text().catch(()=>"");throw new Error(`HTTP error! status: ${E.status}${y?` - ${y}`:""}`)}if(!E.body)throw new Error("Response body is null");const w=E.body.getReader(),b=new TextDecoder;let O="";for(;;){const{done:y,value:U}=await w.read();if(y)break;O+=b.decode(U,{stream:!0});const A=O.split(`
|
|
23
|
-
`);O=A.pop()||"";for(const F of A){const L=F.trim();if(!L||L.startsWith(":")||!L.startsWith("data: "))continue;const $=L.slice(6);if($!=="[DONE]")try{const N=JSON.parse($),C=h.handleChunk(N);for(const j of C)yield j}catch(N){p?.error("Error parsing ChatCompletions stream chunk",{error:N instanceof Error?N.message:String(N),line:L})}}}for(const y of h.finalize())yield y}catch(_){if(c?.aborted)return;p?.error("Error in ChatCompletions streaming request",{error:_ instanceof Error?_.message:String(_)}),yield{type:"error",data:{type:"STREAMING_ERROR",message:_ instanceof Error?_.message:String(_),raw:_}}}}i(Lt,"createStreamingRequest$2");function Nt(t,e){return{name:"ChatCompletions",async createGenerationRequest(n,s){return await $t({baseUrl:t,model:n,apiKey:e,...s})},createStreamingRequest(n,s){return Lt({baseUrl:t,model:n,apiKey:e,...s})}}}i(Nt,"chatCompletions");const x={GEMINI_3_1_PRO_PREVIEW:"gemini-3.1-pro-preview",GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS:"gemini-3.1-pro-preview-customtools",GEMINI_3_PRO_PREVIEW:"gemini-3-pro-preview",GEMINI_3_FLASH_PREVIEW:"gemini-3-flash-preview",GEMINI_3_PRO_IMAGE_PREVIEW:"gemini-3-pro-image-preview",GEMINI_2_5_PRO:"gemini-2.5-pro",GEMINI_2_5_FLASH:"gemini-2.5-flash",GEMINI_2_5_FLASH_PREVIEW_09_2025:"gemini-2.5-flash-preview-09-2025",GEMINI_2_5_FLASH_IMAGE:"gemini-2.5-flash-image",GEMINI_2_5_FLASH_LITE:"gemini-2.5-flash-lite",GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025:"gemini-2.5-flash-lite-preview-09-2025",GEMINI_2_5_FLASH_NATIVE_AUDIO_LATEST:"gemini-2.5-flash-native-audio-latest",GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025:"gemini-2.5-flash-native-audio-preview-09-2025",GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025:"gemini-2.5-flash-native-audio-preview-12-2025",GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025:"gemini-2.5-computer-use-preview-10-2025",GEMINI_2_0_FLASH:"gemini-2.0-flash",GEMINI_2_0_FLASH_001:"gemini-2.0-flash-001",GEMINI_2_0_FLASH_LITE:"gemini-2.0-flash-lite",GEMINI_2_0_FLASH_LITE_001:"gemini-2.0-flash-lite-001",GEMINI_EXP_1206:"gemini-exp-1206",GEMINI_FLASH_LATEST:"gemini-flash-latest",GEMINI_FLASH_LITE_LATEST:"gemini-flash-lite-latest",GEMINI_PRO_LATEST:"gemini-pro-latest",GEMMA_3_27B_IT:"gemma-3-27b-it",GEMMA_3_12B_IT:"gemma-3-12b-it",GEMMA_3_4B_IT:"gemma-3-4b-it",GEMMA_3_1B_IT:"gemma-3-1b-it",GEMMA_3N_E4B_IT:"gemma-3n-e4b-it",GEMMA_3N_E2B_IT:"gemma-3n-e2b-it",DEEP_RESEARCH_PRO_PREVIEW_12_2025:"deep-research-pro-preview-12-2025",GEMINI_ROBOTICS_ER_1_5_PREVIEW:"gemini-robotics-er-1.5-preview",NANO_BANANA_PRO_PREVIEW:"nano-banana-pro-preview",AQA:"aqa"};x.GEMINI_3_1_PRO_PREVIEW,x.GEMINI_3_1_PRO_PREVIEW_CUSTOMTOOLS,x.GEMINI_3_PRO_PREVIEW,x.GEMINI_3_FLASH_PREVIEW,x.GEMINI_3_PRO_IMAGE_PREVIEW,x.GEMINI_2_5_PRO,x.GEMINI_2_5_FLASH,x.GEMINI_2_5_FLASH_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_IMAGE,x.GEMINI_2_5_FLASH_LITE,x.GEMINI_2_5_FLASH_LITE_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_NATIVE_AUDIO_LATEST,x.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_09_2025,x.GEMINI_2_5_FLASH_NATIVE_AUDIO_PREVIEW_12_2025,x.GEMINI_2_5_COMPUTER_USE_PREVIEW_10_2025,x.GEMINI_2_0_FLASH,x.GEMINI_2_0_FLASH_001,x.GEMINI_2_0_FLASH_LITE,x.GEMINI_2_0_FLASH_LITE_001,x.GEMINI_EXP_1206,x.GEMINI_FLASH_LATEST,x.GEMINI_FLASH_LITE_LATEST,x.GEMINI_PRO_LATEST,x.GEMMA_3_27B_IT,x.GEMMA_3_12B_IT,x.GEMMA_3_4B_IT,x.GEMMA_3_1B_IT,x.GEMMA_3N_E4B_IT,x.GEMMA_3N_E2B_IT,x.DEEP_RESEARCH_PRO_PREVIEW_12_2025,x.GEMINI_ROBOTICS_ER_1_5_PREVIEW,x.NANO_BANANA_PRO_PREVIEW;const vt=x.GEMINI_2_5_FLASH_LITE;function we(t,e,n){const s={};return e&&(s.systemInstruction=e),t&&t.length>0&&(s.tools=t.map(r=>({functionDeclarations:[{name:r.name,description:r.description,parametersJsonSchema:D.toJSONSchema(r.schema)}]}))),n&&Object.assign(s,n),s}i(we,"prepareConfig");function Ae(t){return t.map(Gt).filter(e=>e!==void 0)}i(Ae,"convertAxleMessagesToGemini");function Gt(t){switch(t.role){case"tool":return Ut(t);case"assistant":return Dt(t);case"user":return Ft(t)}}i(Gt,"convertMessage$1");function Ut(t){return{role:"user",parts:t.content.flatMap(e=>{const n={functionResponse:{id:e.id??void 0,name:e.name,response:{output:typeof e.content=="string"?e.content:e.content.filter(r=>r.type==="text").map(r=>r.text).join(`
|
|
24
|
-
`)}}};if(typeof e.content=="string")return[n];const s=e.content.filter(r=>r.type==="image").map(r=>({inlineData:{mimeType:r.mimeType,data:r.data}}));return[n,...s]})}}i(Ut,"convertToolMessage$1");function Dt(t){const e=[],n=t.content.filter(r=>r.type==="text");if(n.length>0){const r=n.map(o=>o.text).join("");r&&e.push({text:r})}const s=t.content.filter(r=>r.type==="tool-call");return s.length>0&&e.push(...s.map(r=>{const o={functionCall:{id:r.id??void 0,name:r.name,args:r.parameters}};return r.providerMetadata?.thoughtSignature&&(o.thoughtSignature=r.providerMetadata.thoughtSignature),o})),{role:"model",parts:e}}i(Dt,"convertAssistantMessage$1");function Ft(t){return typeof t.content=="string"?{role:"user",parts:[{text:t.content}]}:{role:"user",parts:t.content.map(jt).filter(n=>n!==null)}}i(Ft,"convertUserMessage$1");function jt(t){return t.type==="text"?{text:t.text}:t.type==="file"&&(t.file.type==="image"||t.file.type==="document")?{inlineData:{mimeType:t.file.mimeType,data:t.file.base64}}:null}i(jt,"convertContentPart$1");function be(t){switch(t){case M.STOP:return[!0,I.Stop];case M.MAX_TOKENS:return[!0,I.Length];case M.FINISH_REASON_UNSPECIFIED:case M.SAFETY:case M.RECITATION:case M.LANGUAGE:case M.OTHER:case M.BLOCKLIST:case M.PROHIBITED_CONTENT:case M.SPII:case M.MALFORMED_FUNCTION_CALL:case M.IMAGE_SAFETY:return[!1,I.Error]}}i(be,"convertStopReason");async function Ht(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:c}=t,d=a?.tracer,m=c?{...c}:{};m.max_tokens&&(m.maxOutputTokens=m.max_tokens,delete m.max_tokens),m.stop&&(m.stopSequences=Array.isArray(m.stop)?m.stop:[m.stop],delete m.stop),m.top_p!==void 0&&(m.topP=m.top_p,delete m.top_p);const p={contents:Ae(s),config:we(o,r,m)};d?.debug("Gemini request",{request:p});let u;try{const l=await e.models.generateContent({model:n,...p});u=Bt(l,{tracer:d})}catch(l){d?.error(l instanceof Error?l.message:String(l)),u=W(l)}return d?.debug("Gemini response",{result:u}),u}i(Ht,"createGenerationRequest$1");function Bt(t,e){const{tracer:n}=e,s=t.usageMetadata.promptTokenCount,r=t.usageMetadata.totalTokenCount-s,o={in:s,out:r};if(!t)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};if(t.promptFeedback&&t.promptFeedback.blockReason)return{type:"error",error:{type:"Blocked",message:`Response blocked by Google AI: ${t.promptFeedback.blockReason}, ${t.promptFeedback.blockReasonMessage}`},usage:o,raw:t};if(!t.candidates||t.candidates.length===0)return{type:"error",error:{type:"InvalidResponse",message:"Invalid or empty response from Google AI"},usage:{in:0,out:0},raw:t};t.candidates.length>1&&n?.warn(`We received ${t.candidates.length} response candidates`);const a=t.candidates[0],d=(a.content?.parts||[]).map(u=>u.text).filter(u=>u!==void 0).join(""),[m,p]=be(a.finishReason);if(m){const u=[];if(d&&u.push({type:"text",text:d}),t.functionCalls)for(const l of t.functionCalls)if(l.args==null)u.push({type:"tool-call",id:l.id,name:l.name,parameters:{}});else{if(typeof l.args!="object"||Array.isArray(l.args))throw new Error(`Invalid tool call arguments for ${l.name}: expected object, got ${typeof l.args}`);u.push({type:"tool-call",id:l.id,name:l.name,parameters:l.args})}return{type:"success",id:t.responseId,model:t.modelVersion,role:"assistant",finishReason:t.functionCalls?I.FunctionCall:p,content:u,text:H(u)??"",usage:o,raw:t}}else return{type:"error",error:{type:"Undetermined",message:`Unexpected stop reason: ${p}`},usage:o,raw:t}}i(Bt,"fromModelResponse$1");function qt(){let t=0,e=-1,n=!1,s="",r="",o=0,a=0,c=null;function d(p){e<0||(c==="text"?p.push({type:"text-complete",data:{index:e}}):c==="thinking"&&p.push({type:"thinking-complete",data:{index:e}}),c=null,e=-1)}i(d,"closeActivePart");function m(p){const u=[];s||(s=p.responseId||`gemini-${Date.now()}`,r=p.modelVersion||"gemini",u.push({type:"start",id:s,data:{model:r,timestamp:Date.now()}})),p.usageMetadata&&(o=p.usageMetadata.promptTokenCount||0,a=(p.usageMetadata.totalTokenCount||0)-o);const l=p.candidates?.[0];if(!l)return u;const f=l.content?.parts||[];for(const h of f){const _="thought"in h&&h.thought===!0;if(_&&h.text?(c!=="thinking"&&(d(u),e=t++,c="thinking",u.push({type:"thinking-start",data:{index:e}})),u.push({type:"thinking-delta",data:{index:e,text:h.text}})):h.text&&!_?(c!=="text"&&(d(u),e=t++,c="text",u.push({type:"text-start",data:{index:e}})),u.push({type:"text-delta",data:{text:h.text,index:e}})):h.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(h))}`),h.functionCall){d(u),n=!0;const E=t++,w=h.functionCall.id||`tool-${E}`;u.push({type:"tool-call-start",data:{index:E,id:w,name:h.functionCall.name}});const b={index:E,id:w,name:h.functionCall.name,arguments:h.functionCall.args??{}},O=h;O.thoughtSignature&&(b.providerMetadata={thoughtSignature:O.thoughtSignature}),u.push({type:"tool-call-complete",data:b})}}if(l.finishReason&&l.finishReason!==M.FINISH_REASON_UNSPECIFIED){d(u);const[h,_]=be(l.finishReason),E=n?I.FunctionCall:_;!h&&!n?u.push({type:"error",data:{type:"FinishReasonError",message:`Unexpected finish reason: ${l.finishReason}`,usage:{in:o,out:a},raw:p}}):u.push({type:"complete",data:{finishReason:E,usage:{in:o,out:a}}})}return u}return i(m,"handleChunk"),{handleChunk:m}}i(qt,"createGeminiStreamingAdapter");async function*Wt(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:c,options:d}=t,m=a?.tracer,p=d?{...d}:{};p.max_tokens&&(p.maxOutputTokens=p.max_tokens,delete p.max_tokens),p.stop&&(p.stopSequences=Array.isArray(p.stop)?p.stop:[p.stop],delete p.stop),p.top_p!==void 0&&(p.topP=p.top_p,delete p.top_p);const u={contents:Ae(s),config:we(o,r,p)};m?.debug("Gemini streaming request",{request:u});const l=qt();try{const f=await e.models.generateContentStream({model:n,...u});for await(const h of f){const _=l.handleChunk(h);for(const E of _)yield E}}catch(f){if(c?.aborted)return;m?.error(f instanceof Error?f.message:String(f)),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}i(Wt,"createStreamingRequest$1");const Vt="Gemini";function Jt(t){const e=new We({apiKey:t});return{name:Vt,async createGenerationRequest(n,s){return await Ht({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:c,signal:d,options:m}=s;return Wt({client:e,model:n,messages:r,system:o,tools:a,runtime:c,signal:d,options:m})}}}i(Jt,"gemini");const ke={GPT_5_2:"gpt-5.2",GPT_5_2_2025_12_11:"gpt-5.2-2025-12-11",GPT_5_2_CHAT_LATEST:"gpt-5.2-chat-latest",GPT_5_2_PRO:"gpt-5.2-pro",GPT_5_2_PRO_2025_12_11:"gpt-5.2-pro-2025-12-11",GPT_5_2_CODEX:"gpt-5.2-codex",GPT_5_1:"gpt-5.1",GPT_5_1_2025_11_13:"gpt-5.1-2025-11-13",GPT_5_1_CHAT_LATEST:"gpt-5.1-chat-latest",GPT_5_1_CODEX:"gpt-5.1-codex",GPT_5_1_CODEX_MAX:"gpt-5.1-codex-max",GPT_5_1_CODEX_MINI:"gpt-5.1-codex-mini",GPT_5:"gpt-5",GPT_5_2025_08_07:"gpt-5-2025-08-07",GPT_5_CHAT_LATEST:"gpt-5-chat-latest",GPT_5_CODEX:"gpt-5-codex",GPT_5_MINI:"gpt-5-mini",GPT_5_MINI_2025_08_07:"gpt-5-mini-2025-08-07",GPT_5_NANO:"gpt-5-nano",GPT_5_NANO_2025_08_07:"gpt-5-nano-2025-08-07",GPT_5_PRO:"gpt-5-pro",GPT_5_PRO_2025_10_06:"gpt-5-pro-2025-10-06",GPT_5_SEARCH_API:"gpt-5-search-api",GPT_5_SEARCH_API_2025_10_14:"gpt-5-search-api-2025-10-14",GPT_4_1:"gpt-4.1",GPT_4_1_2025_04_14:"gpt-4.1-2025-04-14",GPT_4_1_MINI:"gpt-4.1-mini",GPT_4_1_MINI_2025_04_14:"gpt-4.1-mini-2025-04-14",GPT_4_1_NANO:"gpt-4.1-nano",GPT_4_1_NANO_2025_04_14:"gpt-4.1-nano-2025-04-14",GPT_4O:"gpt-4o",GPT_4O_2024_11_20:"gpt-4o-2024-11-20",GPT_4O_2024_08_06:"gpt-4o-2024-08-06",GPT_4O_2024_05_13:"gpt-4o-2024-05-13",GPT_4O_MINI:"gpt-4o-mini",GPT_4O_MINI_2024_07_18:"gpt-4o-mini-2024-07-18",GPT_4O_SEARCH_PREVIEW:"gpt-4o-search-preview",GPT_4O_SEARCH_PREVIEW_2025_03_11:"gpt-4o-search-preview-2025-03-11",GPT_4O_MINI_SEARCH_PREVIEW:"gpt-4o-mini-search-preview",GPT_4O_MINI_SEARCH_PREVIEW_2025_03_11:"gpt-4o-mini-search-preview-2025-03-11",GPT_4_TURBO:"gpt-4-turbo",GPT_4_TURBO_2024_04_09:"gpt-4-turbo-2024-04-09",O4_MINI:"o4-mini",O4_MINI_2025_04_16:"o4-mini-2025-04-16",O4_MINI_DEEP_RESEARCH:"o4-mini-deep-research",O4_MINI_DEEP_RESEARCH_2025_06_26:"o4-mini-deep-research-2025-06-26",O3:"o3",O3_2025_04_16:"o3-2025-04-16",O3_PRO:"o3-pro",O3_PRO_2025_06_10:"o3-pro-2025-06-10",O3_MINI:"o3-mini",O3_MINI_2025_01_31:"o3-mini-2025-01-31",O3_DEEP_RESEARCH:"o3-deep-research",O3_DEEP_RESEARCH_2025_06_26:"o3-deep-research-2025-06-26",O1:"o1",O1_2024_12_17:"o1-2024-12-17",O1_PRO:"o1-pro",O1_PRO_2025_03_19:"o1-pro-2025-03-19",COMPUTER_USE_PREVIEW:"computer-use-preview",COMPUTER_USE_PREVIEW_2025_03_11:"computer-use-preview-2025-03-11",CHATGPT_IMAGE_LATEST:"chatgpt-image-latest"},Kt=ke.GPT_5_MINI;function Re(t){if(t&&t.length>0)return t.map(e=>({type:"function",strict:!0,name:e.name,description:e.description,parameters:D.toJSONSchema(e.schema)}))}i(Re,"prepareTools");function Me(t){return t.map(zt).flat(1)}i(Me,"convertAxleMessageToResponseInput");function zt(t){switch(t.role){case"tool":return Xt(t);case"assistant":return Zt(t);default:return Yt(t)}}i(zt,"convertMessage");function Xt(t){return t.content.map(e=>({type:"function_call_output",call_id:e.id,output:typeof e.content=="string"?e.content:e.content.map(n=>n.type==="text"?{type:"input_text",text:n.text}:{type:"input_image",image_url:`data:${n.mimeType};base64,${n.data}`})}))}i(Xt,"convertToolMessage");function Zt(t){const e=[],n=H(t.content);n&&e.push({role:t.role,content:n});const s=t.content.filter(r=>r.type==="tool-call");for(const r of s)e.push({type:"function_call",call_id:r.id,name:r.name,arguments:JSON.stringify(r.parameters)});return e}i(Zt,"convertAssistantMessage");function Yt(t){if(typeof t.content=="string")return{role:t.role,content:t.content};{const e=t.content.map(Qt).filter(n=>n!==null);return{role:t.role,content:e}}}i(Yt,"convertUserMessage");function Qt(t){if(t.type==="text")return{type:"input_text",text:t.text};if(t.type==="file"){if(t.file.type==="image")return{type:"input_image",image_url:`data:${t.file.mimeType};base64,${t.file.base64}`,detail:"auto"};if(t.file.type==="document")return{type:"input_file",filename:t.file.path,file_data:`data:${t.file.mimeType};base64,${t.file.base64}`}}return t.type==="thinking",null}i(Qt,"convertContentPart");async function en(t){const{client:e,model:n,messages:s,system:r,tools:o,context:a,options:c}=t,d=a?.tracer,m=Re(o),p={model:n,input:Me(s),...r&&{instructions:r},...m?{tools:m}:{},...c};d?.debug("OpenAI ResponsesAPI request",{request:p});let u;try{const l=await e.responses.create(p);u=tn(l)}catch(l){d?.error(l instanceof Error?l.message:String(l)),u=W(l)}return d?.debug("OpenAI ResponsesAPI response",{result:u}),u}i(en,"createGenerationRequest");function tn(t){if(t.error)return{type:"error",error:{type:t.error.code||"undetermined",message:t.error.message||"Response generation failed"},usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t};const e=t.output?.filter(r=>r.type==="reasoning")?.map(r=>r),n=[];if(e&&e.length>0)for(const r of e){const o=r.summary?.[0]?.text||r.content?.[0]?.text||"";(o||r.encrypted_content)&&n.push({type:"thinking",text:o,...r.encrypted_content&&{encrypted:r.encrypted_content}})}t.output_text&&n.push({type:"text",text:t.output_text});const s=t.output?.filter(r=>r.type==="function_call");if(s&&s.length>0)for(const r of s){const o=r;try{n.push({type:"tool-call",id:o.id||"",name:o.name||"",parameters:o.arguments?JSON.parse(o.arguments):{}})}catch(a){throw new Error(`Failed to parse tool call arguments for ${o.name}: ${a instanceof Error?a.message:String(a)}
|
|
25
|
-
Raw value: ${o.arguments}`)}}return{type:"success",id:t.id,model:t.model||"",role:"assistant",finishReason:t.incomplete_details?I.Error:I.Stop,content:n,text:H(n)??"",usage:{in:t.usage?.input_tokens??0,out:t.usage?.output_tokens??0},raw:t}}i(tn,"fromModelResponse");function nn(){let t="",e="",n=0,s=-1,r=!1;const o=new Map,a=new Map,c=new Set(["web_search_call","file_search_call","code_interpreter_call"]),d=new Map;function m(p){const u=[];switch(p.type){case"response.created":{t=p.response.id||`openai-${Date.now()}`,e=p.response.model,u.push({type:"start",id:t,data:{model:e,timestamp:Date.now()}});break}case"response.output_text.delta":{s===-1&&(s=n++,u.push({type:"text-start",data:{index:s}})),u.push({type:"text-delta",data:{text:p.delta,index:s}});break}case"response.output_text.done":{s>=0&&(u.push({type:"text-complete",data:{index:s}}),s=-1);break}case"response.function_call_arguments.delta":{const l=p.item_id;if(!d.has(l)){const h=o.get(l),_=h?.name||"",E=h?.callId||l,w=n++;d.set(l,{id:l,callId:E,name:_,argumentsBuffer:"",partIdx:w}),u.push({type:"tool-call-start",data:{index:w,id:E,name:_}})}const f=d.get(l);f.argumentsBuffer+=p.delta;break}case"response.function_call_arguments.done":{r=!0;const l=p.item_id,f=d.get(l),h=p.name||f?.name||"";if(f){try{const _=p.arguments?JSON.parse(p.arguments):{};u.push({type:"tool-call-complete",data:{index:f.partIdx,id:f.callId,name:h,arguments:_}})}catch(_){throw new Error(`Failed to parse function call arguments for ${h}: ${_ instanceof Error?_.message:String(_)}
|
|
26
|
-
Raw value: ${p.arguments}`)}d.delete(l)}break}case"response.completed":{const l=p.response.usage;u.push({type:"complete",data:{finishReason:p.response.incomplete_details?I.Error:r?I.FunctionCall:I.Stop,usage:{in:l?.input_tokens||0,out:l?.output_tokens||0}}});break}case"response.failed":{u.push({type:"error",data:{type:"RESPONSES_API_ERROR",message:`Response failed: ${p.response.status}`,raw:p}});break}case"response.output_item.added":{if(p.item?.type==="reasoning")s=n++,u.push({type:"thinking-start",data:{index:s}});else if(p.item?.type==="function_call"){const l=p.item,f=l.id||l.call_id;f&&o.set(f,{name:l.name||"",callId:l.call_id||f})}else if(p.item&&c.has(p.item.type)){const l=p.item,f=n++;a.set(l.id,f),u.push({type:"internal-tool-start",data:{index:f,id:l.id,name:l.type}})}break}case"response.output_item.done":{if(p.item?.type==="reasoning"&&s>=0)u.push({type:"thinking-complete",data:{index:s}}),s=-1;else if(p.item&&c.has(p.item.type)){const l=p.item,f=a.get(l.id);f!==void 0&&(u.push({type:"internal-tool-complete",data:{index:f,id:l.id,name:l.type,output:p.item}}),a.delete(l.id))}break}case"response.reasoning_text.delta":{p.delta&&u.push({type:"thinking-delta",data:{index:s,text:p.delta}});break}case"response.reasoning_summary_text.delta":{p.delta&&u.push({type:"thinking-summary-delta",data:{index:s,text:p.delta}});break}case"response.in_progress":case"response.content_part.added":case"response.content_part.done":case"response.reasoning_summary_part.added":case"response.reasoning_summary_part.done":case"response.reasoning_summary_text.done":case"response.reasoning_text.done":break;default:console.log(`[OpenAI] unhandled stream event: ${p.type}`)}return u}return i(m,"handleEvent"),{handleEvent:m}}i(nn,"createStreamingAdapter");async function*sn(t){const{client:e,model:n,messages:s,system:r,tools:o,runtime:a,signal:c,options:d}=t,m=a?.tracer,p=Re(o),u={model:n,input:Me(s),...r&&{instructions:r},stream:!0,...p?{tools:p}:{},...d};m?.debug("OpenAI ResponsesAPI streaming request",{request:u});const l=nn();try{const f=e.responses.stream(u,...c?[{signal:c}]:[]);for await(const h of f){const _=l.handleEvent(h);for(const E of _)yield E}}catch(f){if(c?.aborted)return;m?.error(f instanceof Error?f.message:String(f)),yield{type:"error",data:{type:"STREAMING_ERROR",message:f instanceof Error?f.message:String(f),raw:f}}}}i(sn,"createStreamingRequest");const rn="OpenAI";function on(t){const e=new Ve({apiKey:t});return{name:rn,async createGenerationRequest(n,s){return await en({client:e,model:n,...s})},createStreamingRequest(n,s){const{messages:r,system:o,tools:a,context:c,signal:d,options:m}=s;return sn({client:e,model:n,messages:r,system:o,tools:a,runtime:c,signal:d,options:m})}}}i(on,"openai");const an=R.object({searchTerm:R.string().describe("The search term to query")});class cn{static{i(this,"BraveSearchTool")}name="brave";description="Perform a search using the Brave search engine";schema=an;apiKey;throttle;lastExecTime=0;constructor(e){e&&this.configure(e)}configure(e){const{rateLimit:n}=e;this.apiKey=e["api-key"],this.throttle=n?1100/n:void 0}async execute(e){const{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await _t(this.throttle-(Date.now()-this.lastExecTime));this.lastExecTime=Date.now()}try{const s=this.apiKey,r="https://api.search.brave.com/res/v1/web/search",o=new URL(r);o.searchParams.append("q",n),o.searchParams.append("format","json");const a=await fetch(o.toString(),{method:"GET",headers:{Accept:"application/json","X-Subscription-Token":s}});if(!a.ok)throw new Error(`[Brave] HTTP error ${a.status}: ${a.statusText}`);const c=await a.json();return JSON.stringify(c)}catch(s){throw s instanceof Error?new Error(`[Brave] Error fetching search results: ${s.message}`):s}}}const ln=new cn,un=k.object({operation:k.enum(["add","subtract","multiply","divide"]).describe("The operation to perform (add, subtract, multiply, divide)"),a:k.number().describe("First operand"),b:k.number().describe("Second operand")}),pn={name:"calculator",description:"Performs basic arithmetic operations",schema:un,execute:i(async({operation:t,a:e,b:n})=>{switch(t){case"add":return`${e} + ${n} = ${e+n}`;case"subtract":return`${e} - ${n} = ${e-n}`;case"multiply":return`${e} * ${n} = ${e*n}`;case"divide":if(n===0)throw new Error("Cannot divide by zero");return`${e} / ${n} = ${e/n}`;default:throw new Error(`Unknown operation: ${t}`)}},"execute")},dn=Ke(Je),mn=3e4,fn=1024*1024;async function hn(t,e={}){const{stdout:n,stderr:s}=await dn(t,{cwd:e.cwd,timeout:e.timeout??mn,maxBuffer:e.maxBuffer??fn});return{stdout:n,stderr:s}}i(hn,"runCommand");function _n(t){if(t instanceof Error){const e=t;let n=`Error executing command: ${t.message}`;return e.stdout&&(n+=`
|
|
27
|
-
[stdout]: ${e.stdout}`),e.stderr&&(n+=`
|
|
28
|
-
[stderr]: ${e.stderr}`),n}return`Error executing command: ${String(t)}`}i(_n,"formatExecError");function gn(t,e){return e&&e.trim()?`${t}
|
|
29
|
-
[stderr]: ${e}`:t}i(gn,"formatOutput");const yn=R.object({command:R.string().describe("The shell command to execute")});class En{static{i(this,"ExecTool")}name="exec";description="Execute a shell command and return the output.";schema=yn;timeout=3e4;maxBuffer=1024*1024;cwd;constructor(e){e&&this.configure(e)}configure(e){this.timeout=e.timeout??3e4,this.maxBuffer=e.maxBuffer??1024*1024,this.cwd=e.cwd}summarize(e){return e.command}async execute(e){const{command:n}=e;try{const s=await hn(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd});return gn(s.stdout,s.stderr)}catch(s){return _n(s)}}}const xn=new En,In=k.object({path:k.string().describe("The file path to patch"),old_string:k.string().describe("The exact text to find and replace"),new_string:k.string().describe("The replacement text"),start_line:k.number().int().positive().describe("1-indexed start line of the region to match within"),end_line:k.number().int().positive().describe("1-indexed end line (inclusive) of the region to match within")}),Tn={name:"patch-file",description:"Patch a file by replacing an exact string match within a specified line range",schema:In,summarize:i(({path:t,start_line:e,end_line:n})=>`${t}:${e}:${n}`,"summarize"),execute:i(async({path:t,old_string:e,new_string:n,start_line:s,end_line:r})=>{if(r<s)throw new Error(`end_line (${r}) must be >= start_line (${s})`);let o;try{o=await B(t,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to read file "${t}": ${h.message}`):h}const a=o.split(`
|
|
30
|
-
`);if(s>a.length)throw new Error(`start_line (${s}) exceeds file length (${a.length} lines)`);if(r>a.length)throw new Error(`end_line (${r}) exceeds file length (${a.length} lines)`);const d=a.slice(s-1,r).join(`
|
|
31
|
-
`),m=d.indexOf(e);if(m===-1)throw new Error(`old_string not found within lines ${s}-${r} of "${t}"`);if(d.indexOf(e,m+1)!==-1)throw new Error(`old_string matches multiple times within lines ${s}-${r} of "${t}"`);const u=d.replace(e,n),f=[...a.slice(0,s-1),...u.split(`
|
|
32
|
-
`),...a.slice(r)].join(`
|
|
33
|
-
`);try{await re(t,f,"utf-8")}catch(h){throw h instanceof Error?new Error(`Failed to write file "${t}": ${h.message}`):h}return`Successfully patched "${t}" (lines ${s}-${r})`},"execute")},Sn=k.object({path:k.string().describe("The file path to read from")}),wn={name:"read-file",description:"Read the contents of a file from disk",schema:Sn,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t})=>{try{return await B(t,"utf-8")}catch(e){throw e instanceof Error?new Error(`Failed to read file "${t}": ${e.message}`):e}},"execute")},An=k.object({path:k.string().describe("The file path to write to"),content:k.string().describe("The content to write to the file")}),bn={name:"write-file",description:"Write content to a file on disk, creating directories if needed",schema:An,summarize:i(({path:t})=>t,"summarize"),execute:i(async({path:t,content:e})=>{try{return await He(Be(t),{recursive:!0}),await re(t,e,"utf-8"),`Successfully wrote ${e.length} characters to "${t}"`}catch(n){throw n instanceof Error?new Error(`Failed to write file "${t}": ${n.message}`):n}},"execute")};function Oe(t){try{const e=D.fromJSONSchema(t);return e instanceof D.ZodObject?e.strict():D.object({}).passthrough()}catch{return D.object({}).passthrough()}}i(Oe,"jsonSchemaToZod");function kn(t,e,n){return t.map(s=>Mn(s,e,n))}i(kn,"createMcpTools");function Rn(t,e){return t.map(n=>{const s=e?`${e}_${n.name}`:n.name,r=Oe(n.inputSchema);return{name:s,description:n.description??"",schema:r}})}i(Rn,"createMcpToolDefinitions");function Mn(t,e,n){const s=n?`${n}_${t.name}`:t.name,r=Oe(t.inputSchema);return{name:s,description:t.description??"",schema:r,async execute(o){const a=await e.callTool({name:t.name,arguments:o});if("isError"in a&&a.isError)throw new Error($n(a.content));return On(a.content)}}}i(Mn,"createMcpTool");function On(t){return t.some(n=>n.type==="image")?t.filter(n=>n.type==="text"||n.type==="image").map(n=>{if(n.type==="text")return{type:"text",text:n.text};const s=n;return{type:"image",data:s.data,mimeType:s.mimeType}}):t.filter(n=>n.type==="text").map(n=>n.text).join(`
|
|
34
|
-
`)}i(On,"formatToolResult");function $n(t){return t.filter(e=>e.type==="text").map(e=>e.text).join(`
|
|
35
|
-
`)||"MCP tool execution error"}i($n,"formatErrorContent");class Cn{static{i(this,"MCP")}config;client;transport;cachedMcpTools;_connected=!1;constructor(e){this.config=e}get name(){return this.config.name??this.client?.getServerVersion()?.name}get connected(){return this._connected}async connect(e){if(this._connected)return;const n=e?.tracer?.startSpan("mcp:connect",{type:"internal"});this.client=new ze({name:"axle",version:"1.0.0"}),this.config.transport==="stdio"?this.transport=new Xe({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new Ze(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport),this._connected=!0,n?.end("ok")}catch(s){throw n?.end("error"),s}}async listTools(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return kn(s,n,e?.prefix)}async listToolDefinitions(e){const n=this.assertConnected(),s=await this.fetchTools(n,e?.tracer);return Rn(s,e?.prefix)}async refreshTools(){return this.assertConnected(),this.cachedMcpTools=void 0,this.listTools()}async close(e){this._connected&&(e?.tracer?.debug("mcp:close"),await this.client?.close(),this._connected=!1,this.client=void 0,this.transport=void 0,this.cachedMcpTools=void 0)}async fetchTools(e,n){if(this.cachedMcpTools)return this.cachedMcpTools;n?.debug("mcp:listTools");const s=await e.listTools();return this.cachedMcpTools=s.tools.map(r=>({name:r.name,description:r.description,inputSchema:r.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw new Error("MCP not connected. Call connect() first.");return this.client}}const $e={debug:0,info:1,warn:2,error:3};class Pn{static{i(this,"Tracer")}writers=[];_minLevel="info";get minLevel(){return this._minLevel}set minLevel(e){this._minLevel=e}addWriter(e){this.writers.includes(e)||this.writers.push(e)}removeWriter(e){const n=this.writers.indexOf(e);n!==-1&&this.writers.splice(n,1)}startSpan(e,n){const s={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.writers.forEach(r=>r.onSpanStart(s)),new Y(s,this)}async flush(){for(const e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(n=>n.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(n=>n.onSpanUpdate?.(e))}_notifyEvent(e,n){this.writers.forEach(s=>s.onEvent?.(e,n))}_notifySpanStart(e){this.writers.forEach(n=>n.onSpanStart(e))}_notifyLLMStreamStart(e){this.writers.forEach(n=>n.onLLMStreamStart?.(e))}_notifyLLMStreamChunk(e,n){this.writers.forEach(s=>s.onLLMStreamChunk?.(e,n))}_notifyLLMStreamEnd(e,n){this.writers.forEach(s=>s.onLLMStreamEnd?.(e,n))}_shouldLog(e){return $e[e]>=$e[this._minLevel]}}class Y{static{i(this,"Span")}data;tracer;ended=!1;llmStreamBuffer="";llmStreamActive=!1;constructor(e,n){this.data=e,this.tracer=n}startSpan(e,n){const s={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:e,type:n?.type,startTime:performance.now(),status:"ok",attributes:{},events:[]};return this.tracer._notifySpanStart(s),new Y(s,this.tracer)}end(e="ok"){this.ended||(this.ended=!0,this.data.endTime=performance.now(),this.data.status=e,this.tracer._notifySpanEnd(this.data))}addEvent(e,n,s){if(this.ended||!this.tracer._shouldLog(n))return;const r={name:e,timestamp:performance.now(),level:n,attributes:s};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,n){this.addEvent(e,"debug",n)}info(e,n){this.addEvent(e,"info",n)}warn(e,n){this.addEvent(e,"warn",n)}error(e,n){this.addEvent(e,"error",n)}setAttribute(e,n){this.ended||(this.data.attributes[e]=n,this.tracer._notifySpanUpdate(this.data))}setAttributes(e){this.ended||(Object.assign(this.data.attributes,e),this.tracer._notifySpanUpdate(this.data))}setResult(e){this.ended||(this.data.result=e,this.tracer._notifySpanUpdate(this.data))}startLLMStream(){this.ended||(this.llmStreamActive=!0,this.llmStreamBuffer="",this.tracer._notifyLLMStreamStart(this.data))}appendLLMStream(e){this.ended||!this.llmStreamActive||(this.llmStreamBuffer+=e,this.tracer._notifyLLMStreamChunk(this.data,e))}endLLMStream(e){if(this.ended||!this.llmStreamActive)return;this.llmStreamActive=!1;const n={...e,response:{...e.response,content:e.response.content??this.llmStreamBuffer}};this.data.result=n,this.tracer._notifyLLMStreamEnd(this.data,n)}}const Ce={debug:0,info:1,warn:2,error:3};let Pe=!1;function Ln(){Pe||(ae.use(Ye()),Pe=!0)}i(Ln,"ensureMarkedInit");class Nn{static{i(this,"SimpleWriter")}minLevel;showInternal;showTimestamp;showDuration;markdown;output;spans=new Map;visibleDepths=new Map;constructor(e={}){this.minLevel=e.minLevel??"info",this.showInternal=e.showInternal??!1,this.showTimestamp=e.showTimestamp??!0,this.showDuration=e.showDuration??!0,this.markdown=e.markdown??!1,this.output=e.output??console.log}shouldShowEvent(e){return Ce[e]>=Ce[this.minLevel]}isSpanVisible(e){return!(e.type==="internal"&&!this.showInternal)}findVisibleAncestor(e){let n=e.parentSpanId;for(;n;){const s=this.spans.get(n);if(!s)break;if(this.isSpanVisible(s))return s;n=s.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;const n=this.findVisibleAncestor(e);return n?(this.visibleDepths.get(n.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return"";const e=new Date,n=e.toTimeString().slice(0,8),s=e.getMilliseconds().toString().padStart(3,"0");return`[${n}.${s}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return"";const n=e.endTime-e.startTime;return n<1e3?` (${Math.round(n)}ms)`:` (${(n/1e3).toFixed(2)}s)`}formatIndent(e){return" ".repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return Ln(),ae.parse(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,s);const r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatSpanName(e);this.output(`${o}${r}START ${a}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s),o=this.formatTimestamp(),a=this.formatDuration(e),c=this.formatSpanName(e),d=e.status==="error"?" [ERROR]":"";this.output(`${o}${r}END ${c}${a}${d}`)}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,n){if(!this.shouldShowEvent(n.level))return;this.spans.set(e.spanId,e);let s;if(this.isSpanVisible(e))s=this.visibleDepths.get(e.spanId)??0;else{const u=this.findVisibleAncestor(e);u?s=this.visibleDepths.get(u.spanId)??0:s=0}const r=this.formatIndent(s+1),o=this.formatTimestamp(),a=n.level.toUpperCase().padEnd(5),c=this.markdown&&n.attributes?.markdown===!0,d=n.attributes?Object.entries(n.attributes).filter(([u])=>u!=="markdown"):[];let m=n.name;c&&(m=this.renderMarkdown(m));let p=`${o}${r}${a} ${m}`;if(d.length>0){const u=d.map(([l,f])=>`${l}=${JSON.stringify(f)}`).join(" ");p+=` ${u}`}this.output(p)}onLLMStreamStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const n=this.visibleDepths.get(e.spanId)??0,s=this.formatIndent(n+1),r=this.formatTimestamp();this.output(`${r}${s}INFO LLM streaming started`)}onLLMStreamChunk(e,n){}onLLMStreamEnd(e,n){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;const s=this.visibleDepths.get(e.spanId)??0,r=this.formatIndent(s+1),o=this.formatTimestamp(),a=[`model=${n.model}`];if(n.finishReason&&a.push(`finishReason=${n.finishReason}`),n.usage&&(n.usage.inputTokens!==void 0&&a.push(`inputTokens=${n.usage.inputTokens}`),n.usage.outputTokens!==void 0&&a.push(`outputTokens=${n.usage.outputTokens}`)),this.output(`${o}${r}INFO LLM complete ${a.join(" ")}`),this.shouldShowEvent("debug")&&n.response.content){const d=(typeof n.response.content=="string"?n.response.content:JSON.stringify(n.response.content,null,2)).split(`
|
|
36
|
-
`);for(const m of d)this.output(`${o}${r}DEBUG ${m}`)}}}export{I as A,ht as D,ce as H,ft as I,S as M,Nn as S,Pn as T,vt as a,x as b,tt as c,Kt as d,ue as e,ke as f,et as g,ot as h,Cn as i,At as j,ln as k,pn as l,Nt as m,fe as n,Jt as o,mt as p,on as q,de as r,pe as s,V as t,it as u,wn as v,bn as w,Tn as x,xn as y};
|