@fifthrevision/axle 0.17.0 → 0.19.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/README.md +125 -12
- package/dist/ProceduralMemory-CNxHj5B2.js +45 -0
- package/dist/accumulator-D2NgIGxp.d.ts +547 -0
- package/dist/accumulator-vmmD3pxt.js +1 -0
- package/dist/cli.js +5 -5
- package/dist/index.d.ts +128 -415
- package/dist/index.js +1 -1
- package/dist/models-Bp_jVWHN.js +1 -0
- package/dist/models-C7fdWvZ6.js +1 -0
- package/dist/{models-CI5k-LHn.d.ts → models-Whj6ZP3l.d.ts} +3 -1
- package/dist/providers/models.d.ts +1 -1
- package/dist/providers/models.js +1 -1
- package/dist/ui.d.ts +2 -0
- package/dist/ui.js +1 -0
- package/package.json +15 -11
- package/dist/ProceduralMemory-JWM3glv-.js +0 -45
- package/dist/models-CKz-RHh1.js +0 -1
- package/dist/models-DlE4tfcj.js +0 -1
package/README.md
CHANGED
|
@@ -3,6 +3,8 @@
|
|
|
3
3
|
Axle is a TypeScript library for building multi-turn LLM agents. It provides a
|
|
4
4
|
small, focused API for building agentic applications.
|
|
5
5
|
|
|
6
|
+
**Documentation:** https://axle.fifthrevision.com
|
|
7
|
+
|
|
6
8
|
## Quick Start
|
|
7
9
|
|
|
8
10
|
```typescript
|
|
@@ -330,7 +332,17 @@ const mcp = new MCP({
|
|
|
330
332
|
|
|
331
333
|
### Streaming
|
|
332
334
|
|
|
333
|
-
|
|
335
|
+
Axle has two event models, used at different levels:
|
|
336
|
+
|
|
337
|
+
- `Agent.on(...)` emits `TurnEvent` — a high-level turn view organized
|
|
338
|
+
around parts (text, thinking, action).
|
|
339
|
+
- `stream(...).on(...)` emits `StreamEvent` — a lower-level view that
|
|
340
|
+
surfaces every text/thinking/tool transition the provider produces.
|
|
341
|
+
|
|
342
|
+
`Agent` uses `stream()` internally and translates each `StreamEvent` into
|
|
343
|
+
one or more `TurnEvent`s.
|
|
344
|
+
|
|
345
|
+
#### Turn events
|
|
334
346
|
|
|
335
347
|
```typescript
|
|
336
348
|
const agent = new Agent({ provider, model });
|
|
@@ -340,11 +352,16 @@ agent.on((event) => {
|
|
|
340
352
|
case "text:delta":
|
|
341
353
|
process.stdout.write(event.delta);
|
|
342
354
|
break;
|
|
343
|
-
case "
|
|
344
|
-
|
|
355
|
+
case "part:start":
|
|
356
|
+
if (event.part.type === "action") {
|
|
357
|
+
console.log(`Tool: ${event.part.detail.name}`);
|
|
358
|
+
}
|
|
359
|
+
break;
|
|
360
|
+
case "action:complete":
|
|
361
|
+
console.log("Tool complete");
|
|
345
362
|
break;
|
|
346
|
-
case "
|
|
347
|
-
console.log(`
|
|
363
|
+
case "turn:end":
|
|
364
|
+
console.log(`Turn ${event.status} (in: ${event.usage.in})`);
|
|
348
365
|
break;
|
|
349
366
|
case "error":
|
|
350
367
|
console.error(event.error);
|
|
@@ -369,16 +386,112 @@ try {
|
|
|
369
386
|
}
|
|
370
387
|
```
|
|
371
388
|
|
|
372
|
-
|
|
373
|
-
`
|
|
374
|
-
`
|
|
375
|
-
`
|
|
376
|
-
`
|
|
377
|
-
|
|
378
|
-
|
|
389
|
+
`TurnEvent` types: `session:restore`, `turn:user`, `turn:start`, `turn:end`,
|
|
390
|
+
`part:start`, `part:end`, `text:delta`, `thinking:delta`, `action:args-delta`,
|
|
391
|
+
`action:running`, `action:progress`, `action:complete`, `action:error`,
|
|
392
|
+
`action:child-event`, `annotation:start`, `annotation:update`,
|
|
393
|
+
`annotation:end`, `error`.
|
|
394
|
+
|
|
395
|
+
`part:start` carries a `TurnPart`, discriminated by `part.type` (`"text"`,
|
|
396
|
+
`"thinking"`, `"file"`, `"action"`). Action parts further discriminate on
|
|
397
|
+
`part.kind` (`"tool" | "agent" | "provider-tool"`).
|
|
379
398
|
|
|
380
399
|
Callbacks are registered once and fire on every subsequent `send()`.
|
|
381
400
|
|
|
401
|
+
#### Turn accumulator
|
|
402
|
+
|
|
403
|
+
`Turn` objects are accumulated render state. They are the snapshot counterpart
|
|
404
|
+
to `TurnEvent` streams: text deltas are folded into text parts, tool call
|
|
405
|
+
lifecycles become stable action parts, and tool results are collapsed back into
|
|
406
|
+
the action part that produced them. `AxleMessage[]` remains the canonical model
|
|
407
|
+
conversation state; turns do not affect model input or tool routing.
|
|
408
|
+
|
|
409
|
+
Hosts that transport Axle events over SSE, WebSockets, or another mixed event
|
|
410
|
+
stream can use `TurnAccumulator` instead of reimplementing this reducer:
|
|
411
|
+
|
|
412
|
+
```typescript
|
|
413
|
+
import { TurnAccumulator, type Annotation } from "@fifthrevision/axle/ui";
|
|
414
|
+
|
|
415
|
+
type AppAnnotation =
|
|
416
|
+
| Annotation<{ image: string }, "sandbox">
|
|
417
|
+
| Annotation<{ score: number; passed: boolean }, "eval">;
|
|
418
|
+
|
|
419
|
+
type HostEvent = { type: "run:terminal"; status: string };
|
|
420
|
+
|
|
421
|
+
const accumulator = new TurnAccumulator<AppAnnotation, HostEvent>();
|
|
422
|
+
|
|
423
|
+
for await (const event of events) {
|
|
424
|
+
const { handled, state } = accumulator.apply(event);
|
|
425
|
+
|
|
426
|
+
if (!handled) {
|
|
427
|
+
// event is typed as HostEvent here
|
|
428
|
+
applyHostEvent(event);
|
|
429
|
+
}
|
|
430
|
+
|
|
431
|
+
render(state.turns);
|
|
432
|
+
}
|
|
433
|
+
```
|
|
434
|
+
|
|
435
|
+
Use `@fifthrevision/axle/ui` for browser-safe presentation primitives. It
|
|
436
|
+
exports turns, annotations, turn events, and `TurnAccumulator` without importing
|
|
437
|
+
providers, MCP, tools, or other server-side runtime code.
|
|
438
|
+
|
|
439
|
+
The accumulator accepts open event objects. Unknown host events, such as
|
|
440
|
+
`run:terminal` or `session:expired`, return `handled: false` and leave the
|
|
441
|
+
state unchanged. Session-level annotations are accumulated in
|
|
442
|
+
`state.sessionAnnotations`; turn and part annotations are embedded on their
|
|
443
|
+
targets. The accumulator is not idempotent; callers should deduplicate replayed
|
|
444
|
+
transport events before applying them.
|
|
445
|
+
|
|
446
|
+
#### Annotations
|
|
447
|
+
|
|
448
|
+
Annotations are embedded render metadata for sessions, turns, and parts. They
|
|
449
|
+
are useful for out-of-band UI such as sandbox startup, eval results, deployment
|
|
450
|
+
state, or any other consumer-owned status that should render alongside turns
|
|
451
|
+
without becoming model state.
|
|
452
|
+
|
|
453
|
+
```typescript
|
|
454
|
+
type EvalAnnotation = Annotation<{ score: number; passed: boolean }, "eval">;
|
|
455
|
+
|
|
456
|
+
const annotation: EvalAnnotation = {
|
|
457
|
+
id: crypto.randomUUID(),
|
|
458
|
+
kind: "eval",
|
|
459
|
+
label: "Plan adherence",
|
|
460
|
+
placement: "after",
|
|
461
|
+
status: "complete",
|
|
462
|
+
data: { score: 0.92, passed: true },
|
|
463
|
+
};
|
|
464
|
+
|
|
465
|
+
agentEventSink({
|
|
466
|
+
type: "annotation:end",
|
|
467
|
+
target: { type: "turn", turnId },
|
|
468
|
+
annotation,
|
|
469
|
+
});
|
|
470
|
+
```
|
|
471
|
+
|
|
472
|
+
Annotation `label` is required so generic renderers have a common UI surface.
|
|
473
|
+
`placement` defaults to `"after"`, and `annotation:end` defaults missing
|
|
474
|
+
`status` to `"complete"` in accumulated state. `annotation:update` and
|
|
475
|
+
`annotation:end` carry the full updated annotation object; Axle does not define
|
|
476
|
+
patch or merge semantics for annotation data.
|
|
477
|
+
|
|
478
|
+
#### stream() events
|
|
479
|
+
|
|
480
|
+
The low-level `stream()` primitive emits a different event shape — closer
|
|
481
|
+
to the raw provider stream, with separate `start`/`end` events for each
|
|
482
|
+
text and thinking block, and distinct events for tool request, execution,
|
|
483
|
+
and completion.
|
|
484
|
+
|
|
485
|
+
`StreamEvent` types: `text:start`, `text:delta`, `text:end`,
|
|
486
|
+
`thinking:start`, `thinking:delta`, `thinking:end`, `tool:request`,
|
|
487
|
+
`tool:exec-start`, `tool:exec-delta`, `tool:exec-complete`,
|
|
488
|
+
`provider-tool:start`, `provider-tool:complete`, `turn:complete`,
|
|
489
|
+
`tool-results:start`, `tool-results:complete`, `error`.
|
|
490
|
+
|
|
491
|
+
The `turn:complete` and `tool-results:complete` events carry complete
|
|
492
|
+
`AxleAssistantMessage` and `AxleToolCallMessage` objects for client-server
|
|
493
|
+
architectures that need authoritative message boundaries.
|
|
494
|
+
|
|
382
495
|
### Hosting / Sessions
|
|
383
496
|
|
|
384
497
|
Axle stops at the agent runtime boundary. If you need long-lived sessions,
|
|
@@ -0,0 +1,45 @@
|
|
|
1
|
+
import{t as e}from"./accumulator-vmmD3pxt.js";import{c as t}from"./models-C7fdWvZ6.js";import*as n from"zod";import r,{z as i}from"zod";import a,{access as o,mkdir as s,readFile as c,stat as l,writeFile as u}from"node:fs/promises";import d,{dirname as f,extname as p,resolve as m}from"node:path";import h from"@anthropic-ai/sdk";import"glob";import g from"mime";import{FinishReason as _,FunctionCallingConfigMode as v,GoogleGenAI as y}from"@google/genai";import b from"openai";import{spawn as x}from"node:child_process";import{Client as S}from"@modelcontextprotocol/sdk/client/index.js";import{StdioClientTransport as C}from"@modelcontextprotocol/sdk/client/stdio.js";import{StreamableHTTPClientTransport as w}from"@modelcontextprotocol/sdk/client/streamableHttp.js";import T from"chalk";import{marked as E}from"marked";import ee from"node:crypto";var D=class e extends Error{code;id;details;constructor(t,n){super(t,{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,e.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:O(this.cause)}:{}}}};function O(e){return e instanceof Error?{name:e.name,message:e.message,...e.stack?{stack:e.stack}:{},...`cause`in e&&e.cause?{cause:O(e.cause)}:{}}:e}var k=class e extends D{reason;messages;partial;usage;constructor(t=`Operation aborted`,n){super(t,{code:`ABORTED`,details:{reason:n?.reason,usage:n?.usage}}),this.name=`AbortError`,this.reason=n?.reason,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),reason:this.reason,...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}},A=class e extends k{turn;constructor(t=`Agent send aborted`,n){super(t,n),this.turn=n?.turn,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.turn?{turn:this.turn}:{}}}},j=class e extends D{toolName;messages;partial;usage;constructor(t=`Fatal tool error`,n){super(t,{code:`TOOL_FATAL_ERROR`,details:{toolName:n?.toolName,usage:n?.usage},cause:n?.cause}),this.toolName=n?.toolName,this.messages=n?.messages,this.partial=n?.partial,this.usage=n?.usage,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),...this.toolName?{toolName:this.toolName}:{},...this.messages?{messages:this.messages}:{},...this.partial?{partial:this.partial}:{},...this.usage?{usage:this.usage}:{}}}};function M(e){let t=V(e.system??``),n=R(e.tools),r=R(e.mcpTools),i=z(e.providerTools),a=e.messages.reduce((e,t)=>e+N(t),0),o=t+n+r+i+a;return{total:o,system:t,tools:n,mcpTools:r,providerTools:i,messages:a,...e.limit===void 0?{}:{limit:e.limit,free:Math.max(0,e.limit-o)}}}function N(e){switch(e.role){case`user`:return P(e.content);case`assistant`:return P(e.content);case`tool`:return e.content.reduce((e,t)=>e+I(t),0)}}function P(e){return typeof e==`string`?V(e):e.reduce((e,t)=>e+F(t),0)}function F(e){switch(e.type){case`text`:return V(e.text);case`thinking`:return V(e.summary??e.text);case`tool-call`:return V(e.name)+B(e.parameters);case`provider-tool`:return V(e.name)+B(e.input)+B(e.output);case`file`:return B(e.file)}}function I(e){return V(e.name)+L(e.content)}function L(e){return typeof e==`string`?V(e):e.reduce((e,t)=>t.type===`text`?e+V(t.text):e+B(t.file),0)}function R(e){let t=e?.map(te)??[];return t.length===0?0:B({tools:t})}function z(e){return!e||e.length===0?0:B({providerTools:e})}function te(e){try{return{name:e.name,description:e.description,parameters:r.toJSONSchema(e.schema)}}catch{return{name:e.name,description:e.description}}}function B(e){return e==null?0:V(JSON.stringify(e))}function V(e){return e?Math.ceil(e.length/3):0}function ne(e){let{text:t,files:n}=e,r=[];if(t&&r.push({type:`text`,text:t}),n)for(let e of n)r.push({type:`file`,file:e});return r}function H(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
2
|
+
|
|
3
|
+
`)}function re(e){return e.filter(e=>e.type===`tool-call`)}function U(e){if(e instanceof n.ZodString)return[`string`,`Your answer`];if(e instanceof n.ZodNumber)return[`number`,42];if(e instanceof n.ZodBoolean)return[`boolean`,!0];if(e instanceof n.ZodEnum){let t=e.options;return[t.map(ae).join(` | `),t[0]]}if(e instanceof n.ZodLiteral){let t=e.value;return[ae(t),t]}if(e instanceof n.ZodArray){let t=e.element;if(t instanceof n.ZodString)return[`string array`,[`answer 1`,`answer 2`,`third answer`]];if(t instanceof n.ZodNumber)return[`number array`,[42,59,3.14]];if(t instanceof n.ZodBoolean)return[`boolean array`,[!0,!1,!1]];if(t instanceof n.ZodObject){let[,e]=U(t);return[`object array`,[e,e]]}else if(t instanceof n.ZodEnum||t instanceof n.ZodLiteral){let[e,n]=U(t);return[`${e} array`,[n]]}return[`array`,[]]}if(e instanceof n.ZodObject){let t=e.shape,n={};for(let[e,r]of Object.entries(t)){let[,t]=U(r);n[e]=t}return[`JSON object`,n]}if(e instanceof n.ZodOptional){let[t,n]=U(e.unwrap());return[`${t} | undefined`,n]}throw Error(`Unsupported Zod schema: ${e.constructor.name}`)}function ie(e){if(e instanceof n.ZodObject)return Object.entries(e.shape).map(([e,t])=>{let[n]=U(t);return[e,n]});let[t]=U(e);return[[`response`,t]]}function ae(e){return typeof e==`string`?JSON.stringify(e):String(e)}function oe(e,t){if(!t)return e;let n=se(e);try{return t.parse(n)}catch(e){if(e&&typeof e==`object`&&`issues`in e){let t=e.issues.map(e=>`${e.path.join(`.`)}: ${e.message}`).join(`, `);throw Error(`Validation failed: ${t}`)}throw e}}function se(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*([\s\S]*?)\s*```$/i),r=n?n[1].trim():t;try{return JSON.parse(r)}catch(e){throw Error(`Cannot parse response as JSON: ${e.message}`)}}function ce(e){if(typeof e==`string`)return{message:{role:`user`,id:crypto.randomUUID(),content:[{type:`text`,text:e}]},parse:e=>le(e,void 0)};let t=e.render(),n=e.files,r=e.schema;return{message:{role:`user`,id:crypto.randomUUID(),content:ne({text:t,files:n})},parse:e=>le(e,r)}}function le(e,t){return e?oe(H(e.content),t):null}function W(){return{in:0,out:0}}function ue(e,t){t&&(e.in+=t.in??0,e.out+=t.out??0,fe(e,`cachedIn`,t.cachedIn),fe(e,`cacheWriteIn`,t.cacheWriteIn),fe(e,`reasoningOut`,t.reasoningOut))}function G(e,t){return{...e,...pe(`cachedIn`,t.cachedIn),...pe(`cacheWriteIn`,t.cacheWriteIn),...pe(`reasoningOut`,t.reasoningOut)}}function de(e){if(e)return{inputTokens:e.in,outputTokens:e.out,...e.cachedIn===void 0?{}:{cachedInputTokens:e.cachedIn},...e.cacheWriteIn===void 0?{}:{cacheWriteInputTokens:e.cacheWriteIn},...e.reasoningOut===void 0?{}:{reasoningOutputTokens:e.reasoningOut}}}function fe(e,t,n){n!==void 0&&(e[t]=(e[t]??0)+n)}function pe(e,t){return typeof t==`number`?{[e]:t}:{}}var me=class{tools=new Map;mcpTools=new Map;providerTools=new Map;constructor(e){e?.tools&&this.add(e.tools),e?.providerTools&&this.addProvider(e.providerTools)}add(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new D(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.tools.set(e.name,e)}}addMcp(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new D(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.mcpTools.set(e.name,e)}}addProvider(e){let t=Array.isArray(e)?e:[e];for(let e of t){if(this.has(e.name))throw new D(`Tool already registered: ${e.name}`,{code:`TOOL_REGISTRY_DUPLICATE`,details:{name:e.name}});this.providerTools.set(e.name,e)}}remove(e){let t=this.tools.delete(e),n=this.mcpTools.delete(e),r=this.providerTools.delete(e);return t||n||r}has(e){return this.tools.has(e)||this.mcpTools.has(e)||this.providerTools.has(e)}get(e){return this.tools.get(e)??this.mcpTools.get(e)}getProvider(e){return this.providerTools.get(e)}executable(){return[...this.tools.values(),...this.mcpTools.values()]}local(){return[...this.tools.values()]}mcp(){return[...this.mcpTools.values()]}provider(){return[...this.providerTools.values()]}get size(){return this.tools.size+this.mcpTools.size+this.providerTools.size}};function he(e,t){ue(e,t.usage)}function ge(e){return JSON.stringify({error:e})}function _e(e){let t=e.tools!==void 0||e.providerTools!==void 0;if(e.registry&&t)throw new D("Cannot specify both `registry` and `tools` / `providerTools`. Use one or the other.",{code:`TOOL_OPTIONS_CONFLICT`});return e.registry?e.registry:new me({tools:e.tools,providerTools:e.providerTools})}async function ve(e,t=async()=>null,n,r,i){let a=[],o=()=>{throw new k(`Operation aborted`,{reason:n.reason})};for(let s of e){n.aborted&&o();let e=i?.startSpan(s.name,{type:`tool`}),c={signal:n,tracer:e,registry:r,emit:()=>{}},l;try{l=await t(s.name,s.parameters,c),n.aborted&&(e?.end(`ok`),o())}catch(t){if(t instanceof j)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof k||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`exception`,message:t instanceof Error?t.message:String(t)}}}if(l==null){let t=r.get(s.name);if(t)try{let n=await t.execute(s.parameters,c);e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:n}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:n});continue}catch(t){if(t instanceof j)throw e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`fatal`,message:t.message}}),e?.end(`error`),t;(n.aborted||t instanceof k||t instanceof Error&&t.name===`AbortError`)&&(e?.end(`ok`),o()),l={type:`error`,error:{type:`execution`,message:t instanceof Error?t.message:String(t)}}}}if(l==null){let t=`Tool not found: ${s.name}`;e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:{type:`not-found`,message:t}}),e?.end(`error`),a.push({id:s.id,name:s.name,content:ge({type:`not-found`,message:t}),isError:!0});continue}l.type===`success`?(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.content}),e?.end(`ok`),a.push({id:s.id,name:s.name,content:l.content})):(e?.setResult({kind:`tool`,name:s.name,input:s.parameters,output:l.error}),e?.end(`error`),a.push({id:s.id,name:s.name,content:ge(l.error),isError:!0}))}return{results:a}}let ye=function(e){return e.Stop=`stop`,e.Length=`length`,e.FunctionCall=`function_call`,e.Error=`error`,e.Custom=`custom`,e.Cancelled=`cancelled`,e}({});function K(e,t){for(let n of e)n(t)}function be(e){return{type:`error`,error:{type:`not-found`,message:`Tool not found: ${e}`}}}function xe(e){return{name:e.name,description:e.description,schema:e.schema}}function Se(e){let t=[],n,r;if(`instruct`in e){let{instruct:t,messages:i,...a}=e,o=ce(t);r=o.parse,n={...a,messages:[...i??[],o.message]}}else n=e;let i=new AbortController,a=n.signal?AbortSignal.any([i.signal,n.signal]):i.signal,{promise:o,resolve:s,reject:c}=Promise.withResolvers();return Promise.resolve().then(()=>Ce(n,a,t).then(e=>{if(r&&e.ok){try{s({...e,response:r(e.final)})}catch(t){s({ok:!1,messages:e.messages,final:e.final,usage:e.usage,error:{kind:`parse`,error:t,message:t instanceof Error?t.message:String(t)}})}return}s(e)},c)),{on(e){t.push(e)},cancel(e){i.abort(e)},get final(){return o}}}async function Ce(e,t,n){let{provider:r,model:i,messages:a,system:o,onToolCall:s,maxIterations:c,tracer:l,fileResolver:u,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}=e,y=_e(e),b=[...a],x=[],S=W(),C=0,w=0,T=e=>{b.push(e),x.push(e)},E=e=>{e.ok||K(n,{type:`error`,error:e.error});let t=e.ok?e.final.content:null,r=e.ok?e.final.finishReason:void 0;return l?.setResult({kind:`llm`,model:i,request:{messages:a},response:{content:t??null},usage:de(e.usage),finishReason:r}),l?.end(e.ok?`ok`:`error`),e},ee=(e,n,r,i)=>{i();let a=e.length?{role:`assistant`,id:n,model:r,content:e,finishReason:`cancelled`}:void 0;throw a&&T(a),l?.end(`ok`),new k(`Stream aborted`,{reason:t.reason,messages:x,partial:a,usage:S})};for(;;){if(t.aborted&&ee([],``,``,()=>{}),c!==void 0&&w>=c)return E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${c})`}}},usage:S});w+=1;let e=l?.startSpan(`turn-${w}`,{type:`llm`}),a=y?.executable()??[],D=a.length>0?a.map(xe):void 0,O=y?.provider()??[],A=r.createStreamingRequest(i,{messages:b,system:o,tools:D,providerTools:O.length>0?O:void 0,runtime:{tracer:e,fileResolver:u},signal:t,reasoning:d,maxOutputTokens:f,temperature:p,topP:m,stop:h,toolChoice:g,parallelToolCalls:_,providerOptions:v}),M=[],N=``,P=``,F=null,I=W(),L=-1,R=null,z=``,te=new Map,B=-1,V=()=>{R!==null&&L>=0&&(K(n,{type:R===`text`?`text:end`:`thinking:end`,index:L,final:z}),R=null,z=``,L=-1)};for await(let r of A){switch(r.type){case`start`:N=r.id,P=r.data.model,K(n,{type:`turn:start`,id:N,model:P});break;case`text-start`:V(),M.push({type:`text`,text:``}),B=M.length-1,L=C++,R=`text`,z=``,K(n,{type:`text:start`,index:L});break;case`text-delta`:{let e=M[B];e.text+=r.data.text,z=e.text,K(n,{type:`text:delta`,index:L,delta:r.data.text,accumulated:z});break}case`text-complete`:V();break;case`thinking-start`:V(),M.push({type:`thinking`,text:``}),B=M.length-1,L=C++,R=`thinking`,z=``,K(n,{type:`thinking:start`,index:L});break;case`thinking-delta`:{let e=M[B];e.text+=r.data.text,z=e.text,K(n,{type:`thinking:delta`,index:L,delta:r.data.text,accumulated:z});break}case`thinking-summary-delta`:{let e=M[B];e.text+=r.data.text,z=e.text,K(n,{type:`thinking:delta`,index:L,delta:r.data.text,accumulated:z});break}case`thinking-complete`:V();break;case`tool-call-start`:{V();let e=C++;M.push({type:`tool-call`,id:r.data.id,name:r.data.name,parameters:{}}),B=M.length-1,te.set(r.data.id,e),K(n,{type:`tool:request`,index:e,id:r.data.id,name:r.data.name});break}case`tool-call-args-delta`:K(n,{type:`tool:args-delta`,index:te.get(r.data.id)??-1,id:r.data.id,name:r.data.name,delta:r.data.delta,accumulated:r.data.accumulated});break;case`tool-call-complete`:{let e=M[B];r.data.id&&(e.id=r.data.id),r.data.name&&(e.name=r.data.name),e.parameters=r.data.arguments,r.data.providerMetadata&&(e.providerMetadata=r.data.providerMetadata);break}case`provider-tool-start`:{V();let e=C++;M.push({type:`provider-tool`,id:r.data.id,name:r.data.name}),B=M.length-1,K(n,{type:`provider-tool:start`,index:e,id:r.data.id,name:r.data.name});break}case`provider-tool-complete`:{let e=M[B];r.data.output!=null&&(e.output=r.data.output),K(n,{type:`provider-tool:complete`,index:r.data.index,id:r.data.id,name:r.data.name,output:r.data.output});break}case`complete`:V(),F=r.data.finishReason,I=r.data.usage;break;case`error`:return V(),ue(S,r.data.usage),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:r.data.type,message:r.data.message}}},usage:S});default:console.warn(`[WARN] Unhandled chunk type. Should never happen`)}if(t.aborted)break}if(t.aborted&&(e?.end(`ok`),ee(M,N,P,V)),F===null)return V(),e?.end(`error`),E({ok:!1,messages:x,error:{kind:`model`,error:{type:`error`,error:{type:`IncompleteStream`,message:`Stream ended without a completion signal`}}},usage:S});ue(S,I);let ne={kind:`llm`,model:P,request:{messages:b},response:{content:M},usage:de(I),finishReason:F};e?.setResult(ne),e?.end();let H={role:`assistant`,id:N,model:P,content:M,finishReason:F};if(T(H),K(n,{type:`turn:complete`,message:H,usage:I}),F!==`function_call`)return E({ok:!0,response:H,messages:x,final:H,usage:S});let re=M.filter(e=>e.type===`tool-call`);if(re.length===0)return E({ok:!0,response:H,messages:x,final:H,usage:S});if(t.aborted)throw l?.end(`ok`),new k(`Stream aborted`,{reason:t.reason,messages:x,usage:S});let U=crypto.randomUUID();K(n,{type:`tool-results:start`,id:U});let ie=0,ae=async(e,t,r)=>{let i=re[ie++],a=te.get(i.id)??-1;K(n,{type:`tool:exec-start`,index:a,id:i.id,name:e,parameters:t});let o={...r,emit:t=>{K(n,{type:`tool:exec-delta`,index:a,id:i.id,name:e,chunk:t})}},c=y.get(e),l=(s?await s(e,t,o):c?{type:`success`,content:await c.execute(t,o)}:null)??be(e);return K(n,{type:`tool:exec-complete`,index:a,id:i.id,name:e,result:l}),l},oe;try{({results:oe}=await ve(re,ae,t,y,l))}catch(e){throw e instanceof j?(l?.end(`error`),new j(e.message,{toolName:e.toolName,messages:e.messages??x,partial:e.partial??H,usage:e.usage??S,cause:e.cause})):e instanceof k?(l?.end(`ok`),new k(`Stream aborted`,{reason:e.reason,messages:e.messages??x,partial:e.partial,usage:e.usage??S})):e}if(oe.length>0){let e={role:`tool`,id:U,content:oe};T(e),K(n,{type:`tool-results:complete`,message:e})}}}var we=class{rootPath;constructor(e){this.rootPath=e}async read(e){let t=d.join(this.rootPath,e);try{return await a.readFile(t,`utf-8`)}catch{return null}}async write(e,t){let n=d.join(this.rootPath,e);await a.mkdir(d.dirname(n),{recursive:!0}),await a.writeFile(n,t,`utf-8`)}};function q(e=new Date){return{start:e.toISOString()}}function J(e,t=new Date){let n=t.toISOString();return e?{...e,end:n}:{start:n,end:n}}var Te=class{currentTurnId=null;currentTurnTiming;currentTextPart=null;currentThinkingPart=null;toolIdMap=new Map;accumulatedUsage=W();createUserTurn(e){let t=e.id??crypto.randomUUID(),n=[],r=new Date,i=J(q(r),r),a=()=>({...i});if(typeof e.content==`string`)n.push({id:crypto.randomUUID(),type:`text`,text:e.content,timing:a()});else for(let t of e.content)t.type===`text`?n.push({id:crypto.randomUUID(),type:`text`,text:t.text,timing:a()}):t.type===`file`&&n.push({id:crypto.randomUUID(),type:`file`,file:t.file,timing:a()});return[{type:`turn:user`,turn:{id:t,owner:`user`,parts:n,status:`complete`,timing:i}}]}startAgentTurn(){let e=crypto.randomUUID();return this.currentTurnId=e,this.currentTurnTiming=q(),this.currentTextPart=null,this.currentThinkingPart=null,this.toolIdMap.clear(),this.accumulatedUsage=W(),{type:`turn:start`,turnId:e,timing:this.currentTurnTiming}}handleStreamEvent(e){let t=this.currentTurnId;if(!t)return[];let n=[];switch(e.type){case`turn:start`:break;case`text:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`text`,text:``,timing:q()};this.currentTextPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`text:delta`:this.currentTextPart&&n.push({type:`text:delta`,turnId:t,partId:this.currentTextPart.id,delta:e.delta});break;case`text:end`:if(this.currentTextPart){let e=J(this.currentTextPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:e}),this.currentTextPart=null}break;case`thinking:start`:{this.closeOpenParts(n);let e=crypto.randomUUID(),r={id:e,type:`thinking`,text:``,timing:q()};this.currentThinkingPart={id:e,timing:r.timing},n.push({type:`part:start`,turnId:t,part:r});break}case`thinking:delta`:this.currentThinkingPart&&n.push({type:`thinking:delta`,turnId:t,partId:this.currentThinkingPart.id,delta:e.delta});break;case`thinking:end`:if(this.currentThinkingPart){let e=J(this.currentThinkingPart.timing);n.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:e}),this.currentThinkingPart=null}break;case`tool:request`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),a={id:r,type:`action`,kind:`tool`,status:`pending`,timing:i,detail:{name:e.name,parameters:{}}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a});break}case`tool:args-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:args-delta`,turnId:t,partId:r.partId,delta:e.delta,accumulated:e.accumulated});break}case`tool:exec-start`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:running`,turnId:t,partId:r.partId,parameters:e.parameters});break}case`tool:exec-delta`:{let r=this.toolIdMap.get(e.id);r&&n.push({type:`action:progress`,turnId:t,partId:r.partId,chunk:e.chunk});break}case`tool:exec-complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,e.result.type===`success`?n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.result.content},timing:i}):n.push({type:`action:error`,turnId:t,partId:r.partId,error:e.result.error,timing:i})}break}case`provider-tool:start`:{this.closeOpenParts(n);let r=crypto.randomUUID(),i=q(),a={id:r,type:`action`,kind:`provider-tool`,status:`running`,timing:i,detail:{name:e.name}};this.toolIdMap.set(e.id,{partId:r,turnId:t,timing:i}),n.push({type:`part:start`,turnId:t,part:a}),n.push({type:`action:running`,turnId:t,partId:r});break}case`provider-tool:complete`:{let r=this.toolIdMap.get(e.id);if(r){let i=J(r.timing);r.timing=i,n.push({type:`action:complete`,turnId:t,partId:r.partId,result:{type:`success`,content:e.output},timing:i})}break}case`turn:complete`:this.closeOpenParts(n),ue(this.accumulatedUsage,e.usage);break;case`tool-results:start`:case`tool-results:complete`:break;case`error`:{let t=e.error,r=t.kind===`model`?t.error.error.message:t.kind===`tool`?`Tool error (${t.error.name}): ${t.error.message}`:`Parse error: ${t.message}`;n.push({type:`error`,error:{type:t.kind,message:r}});break}}return n}finalizeTurn(e=`complete`){let t=this.currentTurnId;if(!t)return[];let n=[];this.closeOpenParts(n);let r=J(this.currentTurnTiming);return n.push({type:`turn:end`,turnId:t,status:e,usage:{...this.accumulatedUsage},timing:r}),this.currentTurnId=null,this.currentTurnTiming=void 0,n}closeOpenParts(e){let t=this.currentTurnId;t&&(this.currentTextPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentTextPart.id,timing:J(this.currentTextPart.timing)}),null),this.currentThinkingPart&&=(e.push({type:`part:end`,turnId:t,partId:this.currentThinkingPart.id,timing:J(this.currentThinkingPart.timing)}),null))}};function Ee(e){return Array.isArray(e)?e:[e]}function De(e){return new Promise(t=>setTimeout(t,e))}function Oe(e){return e.then(()=>{},()=>{})}function ke(e,t,n){let r=new AbortController,i=n?AbortSignal.any([n,r.signal]):r.signal,a=e.then(()=>t(i));return{handle:{cancel:e=>r.abort(e),get final(){return a}},settled:Oe(a)}}var Ae=class{_turns=[];_log=[];constructor(e){e?.turns&&(this._turns=e.turns),e?.log&&(this._log=e.log)}get turns(){return[...this._turns]}get log(){return[...this._log]}addTurn(e){this._turns.push(e)}replaceTurns(e){this._turns=[...e]}appendToLog(e){Array.isArray(e)?this._log.push(...e):this._log.push(e)}latestTurn(){return this._turns[this._turns.length-1]}toString(){return JSON.stringify({turns:this._turns})}};function je(e,t){return{...e,...t,providerOptions:e?.providerOptions||t?.providerOptions?{...e?.providerOptions,...t?.providerOptions}:void 0}}var Me=class{provider;model;history;tracer;name;scope;store;fileResolver;requestOptions;registry;system;mcps=[];resolvedMcps=new WeakSet;memory;eventCallbacks=[];sendQueue=Promise.resolve();constructor(e){if(this.provider=e.provider,this.model=e.model,this.history=new Ae,this.tracer=e.tracer,this.system=e.system,this.name=e.name,this.scope=e.scope,this.store=new we(`.axle`),this.fileResolver=e.fileResolver,this.requestOptions={reasoning:e.reasoning,maxOutputTokens:e.maxOutputTokens,temperature:e.temperature,topP:e.topP,stop:e.stop,toolChoice:e.toolChoice,parallelToolCalls:e.parallelToolCalls,providerOptions:e.providerOptions},this.registry=new me({tools:e.tools,providerTools:e.providerTools}),e.mcps&&(this.mcps=[...e.mcps]),e.memory){if(!e.name)throw new D(`Agent requires a 'name' when memory is provided. The name is used to partition memory storage.`);this.memory=e.memory;let t=e.memory.tools?.();t&&this.registry.add(t)}}addMcp(e){this.mcps.push(e)}addMcps(e){this.mcps.push(...e)}hasTools(){return this.registry.size>0||this.mcps.length>0}on(e){this.eventCallbacks.push(e)}context(){return M({system:this.system,messages:this.history.log,tools:this.toToolDefinitions(this.registry.local()),providerTools:this.registry.provider(),mcpTools:this.toToolDefinitions(this.registry.mcp())})}send(e,t){let n=ce(e),r=je(this.requestOptions,t),{handle:i,settled:a}=ke(this.sendQueue,e=>this.run(n,e,t?.fileResolver,r),t?.signal);return this.sendQueue=a,i}async resolveMcpTools(e){for(let t of this.mcps){if(this.resolvedMcps.has(t))continue;let n=await t.listTools({prefix:t.name,tracer:this.tracer,signal:e});this.registry.addMcp(n),this.resolvedMcps.add(t)}}emitEvent(e){for(let t of this.eventCallbacks)t(e)}toToolDefinitions(e){return e.map(e=>({name:e.name,description:e.description,schema:e.schema}))}async run(t,n,r,i){let a=new Te,o=new e({turns:this.history.turns}),s,c=e=>{let t=o.apply(e);t.handled&&this.history.replaceTurns(t.state.turns),this.emitEvent(e)},l=()=>s?o.state.turns.find(e=>e.id===s):void 0,u=W();if(n.aborted)throw new A(`Agent send aborted`,{reason:n.reason,usage:u});try{await this.resolveMcpTools(n)}catch(e){throw n.aborted||e instanceof k||e instanceof Error&&e.name===`AbortError`?new A(`Agent send aborted`,{reason:e instanceof k?e.reason:n.reason,usage:u}):e}let d=this.system,f=[...this.history.log,t.message];if(this.memory){let e=await this.memory.recall({name:this.name,scope:this.scope,system:this.system,messages:f,store:this.store,tracer:this.tracer});e.systemSuffix&&(d=(d??``)+`
|
|
4
|
+
|
|
5
|
+
`+e.systemSuffix)}if(n.aborted)throw new A(`Agent send aborted`,{reason:n.reason,usage:u});this.history.appendToLog(t.message);for(let e of a.createUserTurn(t.message))c(e);let p=a.startAgentTurn();s=p.turnId,c(p);let{signal:m,...h}=i??{},g=Se({provider:this.provider,model:this.model,messages:f,system:d,registry:this.registry,tracer:this.tracer,fileResolver:r??this.fileResolver,...h,signal:n,onToolCall:async(e,t,n)=>{let r=this.registry.get(e);if(!r)return null;try{return{type:`success`,content:await r.execute(t,n)}}catch(e){if(e instanceof j)throw e;return{type:`error`,error:{type:`execution`,message:e instanceof Error?e.message:String(e)}}}}});g.on(e=>{let t=a.handleStreamEvent(e);for(let e of t)c(e)});let _;try{_=await g.final}catch(e){if(e instanceof j){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`error`);for(let e of t)c(e);throw new j(e.message,{toolName:e.toolName,messages:e.messages,partial:e.partial,usage:e.usage??u,cause:e.cause})}if(e instanceof k){e.messages&&e.messages.length>0&&this.history.appendToLog(e.messages);let t=a.finalizeTurn(`cancelled`);for(let e of t)c(e);throw new A(`Agent send aborted`,{reason:e.reason,messages:e.messages,partial:e.partial,turn:l(),usage:e.usage??u})}throw e}let v=_.ok?`complete`:`error`;_.messages.length>0&&this.history.appendToLog(_.messages);let y=a.finalizeTurn(v);for(let e of y)c(e);let b=_.usage??u,x=l();if(!_.ok)return{ok:!1,error:_.error,turn:x,usage:b};let S;try{S=t.parse(_.final)}catch(e){return{ok:!1,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)},turn:x,usage:b}}if(!x)throw new D(`Agent turn missing after send`);if(this.memory)try{await this.memory.record({name:this.name,scope:this.scope,system:this.system,messages:this.history.log,newMessages:_.messages,store:this.store,tracer:this.tracer})}catch(e){this.tracer?.warn(`memory record failed`,{error:e instanceof Error?e.message:String(e)})}return{ok:!0,response:S,turn:x,usage:b}}},Ne=class e extends D{missingVariables;constructor(t){super(Pe(t),{code:`INSTRUCT_VARIABLE_ERROR`,details:{missingVariables:t}}),this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}toJSON(){return{...super.toJSON(),missingVariables:this.missingVariables}}};function Pe(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var Fe=class e extends Error{missingVariables;constructor(t){super(Le(t)),this.name=`MissingVariablesError`,this.missingVariables=t,Object.setPrototypeOf(this,e.prototype)}};function Ie(e,t,n={}){let{placeholderStyle:r=`{{}}`,strict:i=!0}=n,a=r===`{{}}`?/\{\{(.*?)\}\}/g:/\{(.*?)\}/g,o=[];if(e=e.replace(a,(e,n)=>{if(n=n.trim(),Object.prototype.hasOwnProperty.call(t,n)){let e=t[n];return e==null?``:String(e)}return o.push(n),e}),o.length>0){let e=[...new Set(o)];if(i)throw new Fe(e)}return e}function Le(e){return`Missing variable${e.length>1?`s`:``}: ${e.join(`, `)}`}var Re=class e{prompt;inputs={};files=[];textReferences=[];vars;schema;constructor(e){this.prompt=e.prompt,this.schema=e.schema,this.vars=e.vars??`required`}clone(){let t=new e({prompt:this.prompt,schema:this.schema,vars:this.vars});return t.inputs={...this.inputs},t.files=[...this.files],t.textReferences=this.textReferences.map(e=>({...e})),t}withInputs(e){let t=this.clone();return t.inputs={...t.inputs,...e},t}withInput(e,t){return this.withInputs({[e]:t})}setInputs(e){this.inputs={...e}}addInput(e,t){this.inputs[e]=t}addFile(e,t){if(typeof e==`string`){this.textReferences.push({content:e,name:t?.name});return}if(e.kind===`text`&&e.source.type===`text`){this.textReferences.push({content:e.source.content,name:t?.name??e.name});return}this.files.push(t?.name?{...e,name:t.name}:e)}hasFiles(){return this.files.length>0}render(e={}){let t;try{t=Ie(this.prompt,this.inputs,{strict:(e.vars??this.vars)===`required`})}catch(e){throw e instanceof Fe?new Ne(e.missingVariables):e}if(this.textReferences.length>0)for(let[e,n]of this.textReferences.entries()){let r=n.name?`: ${n.name}`:``;t+=`\n\n## Reference ${e+1}${r}\n\n\`\`\`${n.content}'''`}if(!this.schema)return t;let n=`# Output Format Instructions
|
|
6
|
+
|
|
7
|
+
Return only valid JSON matching this schema. Do not wrap it in markdown. Do not include prose before or after the JSON.
|
|
8
|
+
`,[,r]=U(this.schema);for(let[e,t]of ie(this.schema))n+=`\n- ${e}: ${t}`;return n+=`\n\nExample:\n${JSON.stringify(r,null,2)}\n\n`,n+t}};function Y(e,t=`Operation aborted`){if(e?.aborted)throw new k(t,{reason:e.reason})}function X(e,t,n=`Operation aborted`){return t?t.aborted?Promise.reject(new k(n,{reason:t.reason})):new Promise((r,i)=>{let a=()=>{t.removeEventListener(`abort`,a),i(new k(n,{reason:t.reason}))};t.addEventListener(`abort`,a,{once:!0}),e.then(e=>{t.removeEventListener(`abort`,a),r(e)},e=>{t.removeEventListener(`abort`,a),i(e)})}):e}function ze(e,t,n=`[redacted]`){return Be(e,null,t,n)}function Be(e,t,n,r){if(typeof e!=`object`||!e)return typeof e==`string`&&t&&n.has(t)?r:e;if(Array.isArray(e))return e.map(e=>Be(e,t,n,r));let i={};for(let[t,a]of Object.entries(e))i[t]=Be(a,t,n,r);return i}const Ve=new Set([`data`,`file_data`,`file_url`,`image_url`,`url`,`uri`,`fileUri`]);function Z(e){return ze(e,Ve,`[redacted-file-value]`)}function He(e){if(e==null)return{type:`error`,error:{type:`Undetermined`,message:`Unknown error occurred`},usage:{in:0,out:0},raw:e};if(e instanceof Error)return{type:`error`,error:{type:e.name||`Error`,message:e.message||`Unexpected error`},usage:{in:0,out:0},raw:e};if(typeof e==`object`){let t=e,n=t?.error?.error?.type||t?.error?.type||t?.type||t?.code||t?.status||`Undetermined`,r=t?.error?.error?.message||t?.error?.message||t?.message||t?.error||`Unexpected error`;return{type:`error`,error:{type:String(n),message:String(r)},usage:{in:0,out:0},raw:e}}return{type:`error`,error:{type:`Undetermined`,message:String(e)},usage:{in:0,out:0},raw:e}}async function Ue(e,t){let{defaults:n,tag:r}=t,i=null,a=``;if(e)try{a=m(e),i=await c(a,{encoding:`utf-8`})}catch{throw Error(`${r} not found, see --help for details`)}else{for(let e of n.formats)try{a=m(n.name+`.`+e),i=await c(a,{encoding:`utf-8`});break}catch{continue}if(i===null)throw Error(`${r} not found, see --help for details`)}return{content:i,format:a.split(`.`).pop()??``,path:a}}const We=20*1024*1024;async function Q(e,t){if(t.signal?.aborted)throw new DOMException(`File resolution aborted`,`AbortError`);let{source:n}=e;if(n.type===`base64`)return Ge({type:`base64`,data:n.data},e,t);if(n.type===`text`)return Ge({type:`text`,content:n.content},e,t);if(n.type===`url`)return Ge({type:`url`,url:n.url},e,t);if(!t.resolver)throw Error(`No fileResolver configured for deferred file: ${e.name}`);return Ge(await t.resolver({file:e,ref:n.ref,provider:t.provider,model:t.model,accepted:t.accepted,signal:t.signal}),e,t)}function Ge(e,t,n){if(n.accepted.includes(e.type))return{...e,mimeType:e.mimeType??t.mimeType,name:e.name??t.name};throw Error(`File source '${e.type}' is not supported for ${n.provider} ${t.kind} file '${t.name}'. Accepted: ${n.accepted.join(`, `)}`)}const Ke=new Set([`application/json`,`application/xml`,`application/yaml`,`application/x-yaml`,`application/toml`]);function qe(e){return e.startsWith(`text/`)||Ke.has(e)}function Je(e){let t=g.getType(e);if(!t){let t=p(e).toLowerCase();throw Error(`Unsupported file type: ${t||`(no extension)`}`)}if(t.startsWith(`image/`))return{kind:`image`,mimeType:t};if(t===`application/pdf`)return{kind:`document`,mimeType:t};if(qe(t))return{kind:`text`,mimeType:t};{let n=p(e).toLowerCase();throw Error(`Unsupported file type: ${n} (${t})`)}}async function Ye(e,t){let n=m(e);try{await o(n)}catch{throw Error(`File not found: ${e}`)}let r=await l(n);if(r.size>We)throw Error(`File too large: ${r.size} bytes. Maximum allowed: ${We} bytes`);let i=n.split(`/`).pop()||``,a=Je(n);if((t||(a.kind===`text`?`utf-8`:`base64`))===`utf-8`){if(a.kind!==`text`)throw Error(`Cannot read ${a.kind} file as text: ${e}`);let t=await c(n,`utf-8`);return{kind:`text`,mimeType:a.mimeType,size:r.size,name:i,source:{type:`text`,content:t}}}else{if(a.kind===`text`)throw Error(`Cannot read text file as binary: ${e}`);let t=(await c(n)).toString(`base64`);return{kind:a.kind,mimeType:a.mimeType,size:r.size,name:i,source:{type:`base64`,data:t}}}}async function Xe(e,t={model:``}){return Promise.all(e.map(e=>Ze(e,t)))}async function Ze(e,t){if(e.role===`assistant`){let t=[];for(let n of e.content)n.type===`text`?t.push({type:`text`,text:n.text}):n.type===`thinking`?n.redacted?t.push({type:`redacted_thinking`,data:n.text}):n.signature&&t.push({type:`thinking`,thinking:n.text,signature:n.signature}):n.type===`tool-call`?t.push({type:`tool_use`,id:n.id,name:n.name,input:n.parameters}):n.type===`provider-tool`&&(t.push({type:`server_tool_use`,id:n.id,name:n.name,input:n.input??{}}),n.output!=null&&t.push({type:`web_search_tool_result`,tool_use_id:n.id,content:n.output}));return{role:`assistant`,content:t}}if(e.role===`tool`)return{role:`user`,content:await Promise.all(e.content.map(async e=>({type:`tool_result`,tool_use_id:e.id,content:typeof e.content==`string`?e.content:await ut(e.content,t),...e.isError?{is_error:!0}:{}})))};if(typeof e.content==`string`)return{role:`user`,content:e.content};{let n=[];for(let r of e.content)r.type===`text`?n.push({type:`text`,text:r.text}):r.type===`file`&&n.push(await Qe(r.file,t,`user-message`));return{role:`user`,content:n}}}async function Qe(e,t,n){if(e.kind===`image`)return{type:`image`,source:et(await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`Anthropic only supports PDF document files. Received ${e.mimeType}`);let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`document`,source:tt(r),title:r.name??e.name}}let r=await Q(e,{provider:`anthropic`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Anthropic text source: ${r.type}`);return n===`tool-result`?{type:`text`,text:r.content}:{type:`document`,source:{type:`text`,media_type:`text/plain`,data:r.content},title:r.name??e.name}}function $e(e){if(e===`image/jpeg`||e===`image/png`||e===`image/gif`||e===`image/webp`)return e;throw Error(`Anthropic does not support image MIME type: ${e}. Supported types: image/jpeg, image/png, image/gif, image/webp.`)}function et(e,t){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:$e(e.mimeType??t.mimeType),data:e.data};throw Error(`Unsupported Anthropic image source: ${e.type}`)}function tt(e){if(e.type===`url`)return{type:`url`,url:e.url};if(e.type===`base64`)return{type:`base64`,media_type:`application/pdf`,data:e.data};throw Error(`Unsupported Anthropic PDF source: ${e.type}`)}function nt(e){return e===!0?{thinking:{type:`enabled`,budget_tokens:8192}}:{}}function rt(e){return e.map(e=>{let t=r.toJSONSchema(e.schema);if(!lt(t))throw Error(`Schema for tool ${e.name} must be an object type`);return{name:e.name,description:e.description,input_schema:t}})}const it={web_search:`web_search_20250305`};function at(e){return(e??[]).map(e=>({type:it[e.name]??e.name,name:e.name,...e.config}))}function ot(e,t,n,r){if(e===void 0&&t!==!1)return{};let i=t===!1?{disable_parallel_tool_use:!0}:{};if(e===void 0||e===`auto`)return{tool_choice:{type:`auto`,...i}};if(e===`required`)return{tool_choice:{type:`any`,...i}};if(e===`none`)return{tool_choice:{type:`none`}};if(!(n?.some(t=>t.name===e.name)||r?.some(t=>t.name===e.name)))throw Error(`Tool choice references an unavailable tool: ${e.name}`);return{tool_choice:{type:`tool`,name:e.name,...i}}}function st(e){let t=[];for(let n of e)if(n.type===`text`)t.push({type:`text`,text:n.text});else if(n.type===`thinking`)t.push({type:`thinking`,text:n.text||``,redacted:!1});else if(n.type===`redacted_thinking`)t.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 Error(`Invalid tool call input for ${n.name}: expected object, got ${typeof n.input}`);t.push({type:`tool-call`,id:n.id,name:n.name,parameters:n.input})}return t}function ct(e){switch(e){case`max_tokens`:return`length`;case`end_turn`:return`stop`;case`stop_sequence`:return`stop`;case`tool_use`:return`function_call`;default:return`error`}}function lt(e){return e&&typeof e==`object`&&e.type===`object`}async function ut(e,t){return Promise.all(e.map(async e=>e.type===`text`?{type:`text`,text:e.text}:Qe(e.file,t,`tool-result`)))}async function dt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v;try{Y(g,`Generate aborted`);let e=await Xe(r,{model:n,fileResolver:s?.fileResolver,signal:g}),y={model:n,max_tokens:l??16e3,messages:e,...i&&{system:i},...f&&{stop_sequences:Ee(f)},...(a||o)&&{tools:[...a?rt(a):[],...at(o)]},...nt(c),...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...ot(p,m,a,o),...h};_?.debug(`Anthropic request`,{request:Z(y)});let b=await X(t.messages.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Y(g,`Generate aborted`),v=ft(b)}catch(e){Y(g,`Generate aborted`),v=He(e)}return _?.debug(`Anthropic response`,{result:v}),v}function ft(e){let t=ct(e.stop_reason);if(t===`error`)return{type:`error`,error:{type:`Uncaught error`,message:`Stop reason is not recognized or unhandled: ${e.stop_reason}`},usage:mt(e.usage),raw:e};if(t===`function_call`){let t=st(e.content);return{type:`success`,id:e.id,model:e.model,role:e.role,finishReason:`function_call`,content:t,text:H(t),usage:mt(e.usage),raw:e}}if(e.type==`message`){let n=st(e.content);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:t,content:n,text:H(n),usage:mt(e.usage),raw:e}}return{type:`error`,error:{type:`InvalidResponse`,message:`Unsupported completion type: ${e.type}`},usage:mt(e.usage),raw:e}}function pt(e){return e.input_tokens+(e.cache_creation_input_tokens??0)+(e.cache_read_input_tokens??0)}function mt(e){return G({in:pt(e),out:e.output_tokens},{cachedIn:e.cache_read_input_tokens??void 0,cacheWriteIn:e.cache_creation_input_tokens??void 0})}function ht(){let e=new Map,t=new Map,n=0,r=0,i=0,a=0,o=new Map;function s(s){let c=[];switch(s.type){case`message_start`:n=(s.message.usage?.input_tokens??0)+(s.message.usage?.cache_creation_input_tokens??0)+(s.message.usage?.cache_read_input_tokens??0),a=s.message.usage?.cache_creation_input_tokens??0,i=s.message.usage?.cache_read_input_tokens??0,c.push({type:`start`,id:s.message.id,data:{model:s.message.model,timestamp:Date.now()}});break;case`message_delta`:s.usage&&(r=s.usage.output_tokens??r,s.usage.input_tokens!=null&&(n=s.usage.input_tokens+(s.usage.cache_creation_input_tokens??a)+(s.usage.cache_read_input_tokens??i)),a=s.usage.cache_creation_input_tokens??a,i=s.usage.cache_read_input_tokens??i),s.delta.stop_reason&&c.push({type:`complete`,data:{finishReason:ct(s.delta.stop_reason),usage:G({in:n,out:r},{cachedIn:i,cacheWriteIn:a})}});case`message_stop`:break;case`content_block_start`:if(s.content_block.type===`text`)e.set(s.index,`text`),c.push({type:`text-start`,data:{index:s.index}});else if(s.content_block.type===`tool_use`){e.set(s.index,`tool`);let t=s.content_block;o.set(s.index,{id:t.id,name:t.name,argumentsBuffer:``}),c.push({type:`tool-call-start`,data:{index:s.index,id:t.id,name:t.name}})}else if(s.content_block.type===`thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!1}});else if(s.content_block.type===`redacted_thinking`)e.set(s.index,`thinking`),c.push({type:`thinking-start`,data:{index:s.index,redacted:!0}});else if(s.content_block.type===`server_tool_use`){e.set(s.index,`provider-tool`);let n=s.content_block;t.set(n.id,{index:s.index,name:n.name}),c.push({type:`provider-tool-start`,data:{index:s.index,id:n.id,name:n.name}})}else if(s.content_block.type===`web_search_tool_result`){let e=s.content_block,n=t.get(e.tool_use_id);n&&(c.push({type:`provider-tool-complete`,data:{index:n.index,id:e.tool_use_id,name:n.name,output:e.content}}),t.delete(e.tool_use_id))}break;case`content_block_delta`:if(s.delta.type===`text_delta`)c.push({type:`text-delta`,data:{text:s.delta.text,index:s.index}});else if(s.delta.type===`input_json_delta`){let e=o.get(s.index);e&&(e.argumentsBuffer+=s.delta.partial_json,c.push({type:`tool-call-args-delta`,data:{index:s.index,id:e.id,name:e.name,delta:s.delta.partial_json,accumulated:e.argumentsBuffer}}))}else s.delta.type===`thinking_delta`?c.push({type:`thinking-delta`,data:{text:s.delta.thinking,index:s.index}}):s.delta.type===`signature_delta`||s.delta.type;break;case`content_block_stop`:{let t=e.get(s.index);if(t===`text`)c.push({type:`text-complete`,data:{index:s.index}});else if(t===`thinking`)c.push({type:`thinking-complete`,data:{index:s.index}});else if(t!==`provider-tool`&&t===`tool`){let e=o.get(s.index);if(e){try{let t=e.argumentsBuffer?JSON.parse(e.argumentsBuffer):{};c.push({type:`tool-call-complete`,data:{index:s.index,id:e.id,name:e.name,arguments:t}})}catch(t){throw Error(`Failed to parse tool call arguments for ${e.name}: ${t instanceof Error?t.message:String(t)}\nRaw buffer: ${e.argumentsBuffer}`)}o.delete(s.index)}}e.delete(s.index);break}}return c}return{handleEvent:s}}async function*gt(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer,v=[...a?rt(a):[],...at(o)],y=ht();try{let e=await Xe(r,{model:n,fileResolver:s?.fileResolver,signal:c}),b={model:n,max_tokens:u??_t(n),messages:e,...i&&{system:i},...p&&{stop_sequences:Ee(p)},...v.length>0&&{tools:v},...nt(l),...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...ot(m,h,a,o),...g};_?.debug(`Anthropic streaming request`,{request:Z(b)});let x=await t.messages.create({...b,stream:!0},{signal:c});for await(let e of x){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function _t(e){return e in t?t[e]:e.includes(`opus`)?e.match(/opus-4-[6-9]|opus-[5-9]/)?128e3:64e3:e.includes(`sonnet`)||e.includes(`haiku`)?e.match(/claude-3-[0-5]-/)?8192:64e3:16384}function vt(e){let t=new h({apiKey:e});return{name:`anthropic`,async createGenerationRequest(e,n){return await dt({client:t,model:e,...n})},createStreamingRequest(e,n){return gt({client:t,model:e,...n})}}}async function yt(e,t,n={model:``}){let r=(await Promise.all(e.map(e=>Tt(e,n)))).flat(1);return t?[{role:`system`,content:t},...r]:r}function bt(e){return e===!0?{reasoning_effort:`high`}:e===!1?{reasoning_effort:`none`}:{}}function xt(e){return G({in:e?.prompt_tokens||0,out:e?.completion_tokens||0},{cachedIn:e?.prompt_tokens_details?.cached_tokens??e?.input_tokens_details?.cached_tokens,cacheWriteIn:e?.prompt_tokens_details?.cache_write_tokens??e?.prompt_tokens_details?.cache_creation_tokens??e?.input_tokens_details?.cache_write_tokens??e?.input_tokens_details?.cache_creation_tokens,reasoningOut:e?.completion_tokens_details?.reasoning_tokens??e?.output_tokens_details?.reasoning_tokens})}function St(e){if(e&&e.length>0)return e.map(e=>({type:`function`,function:{name:e.name,description:e.description,parameters:r.toJSONSchema(e.schema)}}))}function Ct(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,function:{name:e.name}}};throw n?.some(t=>t.name===e.name)?Error(`ChatCompletions does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function wt(e){switch(e){case`stop`:return`stop`;case`length`:return`length`;case`tool_calls`:case`function_call`:return`function_call`;case`content_filter`:return`error`;default:return`stop`}}async function Tt(e,t){switch(e.role){case`tool`:return Et(e,t);case`assistant`:return Dt(e);default:return Ot(e,t)}}async function Et(e,t){return Promise.all(e.content.map(async e=>({role:`tool`,content:typeof e.content==`string`?e.content:await At(e.content,t),tool_call_id:e.id})))}function Dt(e){let t=e.content.filter(e=>e.type===`tool-call`),n=e.content.filter(e=>e.type===`text`),r=t.length>0?t.map(e=>({type:`function`,id:e.id,function:{name:e.name,arguments:JSON.stringify(e.parameters)}})):void 0;return{role:`assistant`,content:n.map(e=>e.text).join(``),...r&&{tool_calls:r}}}async function Ot(e,t){if(typeof e.content==`string`)return{role:`user`,content:e.content};let n=(await Promise.all(e.content.map(e=>kt(e,t)))).filter(e=>e!==null);return n.every(e=>e.type===`text`)?{role:`user`,content:n.map(e=>e.text).join(``)}:{role:`user`,content:n}}async function kt(e,t){return e.type===`text`?{type:`text`,text:e.text}:e.type===`file`?jt(e.file,t,`user-message`):null}async function At(e,t){let n=[];for(let r of e){if(r.type===`text`){n.push(r.text);continue}if(r.file.kind===`text`){let e=await Q(r.file,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:`tool-result`,resolver:t.fileResolver,signal:t.signal});if(e.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${e.type}`);n.push(Pt(r.file,e.content,e.name,e.mimeType));continue}throw Error(`ChatCompletions tool results do not support file parts other than text`)}return n.join(`
|
|
9
|
+
`)}async function jt(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported ChatCompletions text source: ${r.type}`);return{type:`text`,text:Pt(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`ChatCompletions document file inputs currently support PDF only. Received ${e.mimeType}`);let r=await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return{type:`file`,file:{filename:r.name??e.name,file_data:Nt(r,e)}}}return{type:`image_url`,image_url:{url:Mt(await Q(e,{provider:`chatcompletions`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}}}function Mt(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions image source: ${e.type}`)}function Nt(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported ChatCompletions file source: ${e.type}`)}function Pt(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}async function Ft(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,apiKey:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}=e,v=s?.tracer,y;try{Y(_,`Generate aborted`);let e=await yt(r,i,{model:n,fileResolver:s?.fileResolver,signal:_}),b=St(a);o&&o.length>0&&v?.warn(`providerTools not supported by ChatCompletions provider`);let x={model:n,messages:e,...b&&{tools:b},...bt(l),...u===void 0?{}:{max_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...p===void 0?{}:{stop:p},...Ct(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};v?.debug(`ChatCompletions request`,{request:Z(x)});let S={"Content-Type":`application/json`};c&&(S.Authorization=`Bearer ${c}`);let C=await X(fetch(`${t}/chat/completions`,{method:`POST`,headers:S,body:JSON.stringify(x),signal:_}),_,`Generate aborted`);if(!C.ok){let e=await C.text().catch(()=>``);throw Error(`HTTP error! status: ${C.status}${e?` - ${e}`:``}`)}let w=await X(C.json(),_,`Generate aborted`);Y(_,`Generate aborted`),y=It(w)}catch(e){Y(_,`Generate aborted`),v?.error(`Error fetching ChatCompletions response`,{error:e instanceof Error?e.message:String(e)}),y=He(e)}return v?.debug(`ChatCompletions response`,{result:y}),y}function It(e){let t=e.choices?.[0];if(!t)return{type:`error`,error:{type:`ChatCompletionsError`,message:`No choices in response`},usage:{in:0,out:0},raw:e};let n=[],r=t.message.reasoning_content??t.message.reasoning;if(r&&n.push({type:`thinking`,text:r}),t.message.content&&n.push({type:`text`,text:t.message.content}),t.message.tool_calls)for(let e of t.message.tool_calls){let t;try{t=JSON.parse(e.function.arguments)}catch(t){throw Error(`Invalid tool call arguments for ${e.function.name}: ${t instanceof Error?t.message:String(t)}`)}if(typeof t!=`object`||!t||Array.isArray(t))throw Error(`Invalid tool call arguments for ${e.function.name}: expected object, got ${typeof t}`);n.push({type:`tool-call`,id:e.id,name:e.function.name,parameters:t})}let i=n.some(e=>e.type===`tool-call`)?wt(`tool_calls`):wt(t.finish_reason);return{type:`success`,id:e.id,model:e.model,role:`assistant`,finishReason:i,content:n,text:H(n),usage:xt(e.usage),raw:e}}function Lt(){let e=new Map,t=0,n=-1,r=``,i=``,a=null,o,s;function c(e){n<0||(a===`text`?e.push({type:`text-complete`,data:{index:n}}):a===`thinking`&&e.push({type:`thinking-complete`,data:{index:n}}),a=null,n=-1)}function l(l){let u=[];l.usage&&(s=xt(l.usage));let d=l.choices?.[0];if(!d)return u;r||(r=l.id,i=l.model,u.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}}));let f=d.delta,p=f.reasoning_content??f.reasoning;if(p&&(a!==`thinking`&&(c(u),n=t++,a=`thinking`,u.push({type:`thinking-start`,data:{index:n}})),u.push({type:`thinking-delta`,data:{index:n,text:p}})),f.content&&(a!==`text`&&(c(u),n=t++,a=`text`,u.push({type:`text-start`,data:{index:n}})),u.push({type:`text-delta`,data:{text:f.content,index:n}})),f.tool_calls){c(u);for(let n of f.tool_calls){let r=n.index;if(!e.has(r)){let i=t++,a=n.id||`tool-${i}`;e.set(r,{id:a,name:n.function?.name||``,argumentsBuffer:``,partIdx:i}),u.push({type:`tool-call-start`,data:{index:i,id:a,name:n.function?.name||``}})}let i=e.get(r);n.id&&(i.id=n.id),n.function?.name&&(i.name=n.function.name),n.function?.arguments&&(i.argumentsBuffer+=n.function.arguments,u.push({type:`tool-call-args-delta`,data:{index:i.partIdx,id:i.id,name:i.name,delta:n.function.arguments,accumulated:i.argumentsBuffer}}))}}if(d.finish_reason){c(u);for(let[,t]of e)try{let e=t.argumentsBuffer?JSON.parse(t.argumentsBuffer):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.id,name:t.name,arguments:e}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw buffer: ${t.argumentsBuffer}`)}o=wt(d.finish_reason)}return u}function u(){return o===void 0?[]:[{type:`complete`,data:{finishReason:o,usage:s??{in:0,out:0}}}]}return{handleChunk:l,finalize:u}}async function*Rt(e){let{baseUrl:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,apiKey:l,reasoning:u,maxOutputTokens:d,temperature:f,topP:p,stop:m,toolChoice:h,parallelToolCalls:g,providerOptions:_}=e,v=s?.tracer;o&&o.length>0&&v?.warn(`providerTools not supported by ChatCompletions provider`);let y=Lt();try{let e=await yt(r,i,{model:n,fileResolver:s?.fileResolver,signal:c}),b=St(a),x={model:n,messages:e,stream:!0,stream_options:{include_usage:!0},...b&&{tools:b},...bt(u),...d===void 0?{}:{max_tokens:d},...f===void 0?{}:{temperature:f},...p===void 0?{}:{top_p:p},...m===void 0?{}:{stop:m},...Ct(h,a,o),...g===void 0?{}:{parallel_tool_calls:g},..._};v?.debug(`ChatCompletions streaming request`,{request:Z(x)});let S={"Content-Type":`application/json`};l&&(S.Authorization=`Bearer ${l}`);let C=await fetch(`${t}/chat/completions`,{method:`POST`,headers:S,body:JSON.stringify(x),signal:c});if(!C.ok){let e=await C.text().catch(()=>``);throw Error(`HTTP error! status: ${C.status}${e?` - ${e}`:``}`)}if(!C.body)throw Error(`Response body is null`);let w=C.body.getReader(),T=new TextDecoder,E=``;for(;;){let{done:e,value:t}=await w.read();if(e)break;E+=T.decode(t,{stream:!0});let n=E.split(`
|
|
10
|
+
`);E=n.pop()||``;for(let e of n){let t=e.trim();if(!t||t.startsWith(`:`)||!t.startsWith(`data: `))continue;let n=t.slice(6);if(n!==`[DONE]`)try{let e=JSON.parse(n),t=y.handleChunk(e);for(let e of t)yield e}catch(e){v?.error(`Error parsing ChatCompletions stream chunk`,{error:e instanceof Error?e.message:String(e),line:t})}}}for(let e of y.finalize())yield e}catch(e){if(c?.aborted)return;v?.error(`Error in ChatCompletions streaming request`,{error:e instanceof Error?e.message:String(e)}),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function zt(e,t){return{name:`ChatCompletions`,async createGenerationRequest(n,r){return await Ft({baseUrl:e,model:n,apiKey:t,...r})},createStreamingRequest(n,r){return Rt({baseUrl:e,model:n,apiKey:t,...r})}}}function Bt(e,t,n){let i={};return t&&(i.systemInstruction=t),e&&e.length>0&&(i.tools=e.map(e=>({functionDeclarations:[{name:e.name,description:e.description,parametersJsonSchema:r.toJSONSchema(e.schema)}]}))),n&&Object.assign(i,n),i}const Vt={web_search:`googleSearch`,code_execution:`codeExecution`};function Ht(e,t){if(!(!t||t.length===0)){e.tools||=[];for(let n of t){let t=Vt[n.name]??n.name;e.tools.push({[t]:n.config??{}})}}}function Ut(e,t,n,r){if(t===!1)throw Error(`Gemini does not support disabling parallel tool calls`);if(e===void 0)return{};if(e===`auto`)return{toolConfig:{functionCallingConfig:{mode:v.AUTO}}};if(e===`none`)return{toolConfig:{functionCallingConfig:{mode:v.NONE}}};if(e===`required`){if(!n||n.length===0)throw Error(`Gemini requires function tools for required tool choice`);return{toolConfig:{functionCallingConfig:{mode:v.ANY}}}}if(n?.some(t=>t.name===e.name))return{toolConfig:{functionCallingConfig:{mode:v.ANY,allowedFunctionNames:[e.name]}}};throw r?.some(t=>t.name===e.name)?Error(`Gemini does not support provider tool choice: ${e.name}`):Error(`Tool choice references an unavailable tool: ${e.name}`)}function Wt(e){return e===!0?{thinkingConfig:{thinkingBudget:8192,includeThoughts:!0}}:e===!1?{thinkingConfig:{thinkingBudget:0}}:{}}async function Gt(e,t={model:``}){return(await Promise.all(e.map(e=>Kt(e,t)))).filter(e=>e!==void 0)}async function Kt(e,t){switch(e.role){case`tool`:return qt(e,t);case`assistant`:return Jt(e);case`user`:return Yt(e,t)}}async function qt(e,t){return{role:`user`,parts:(await Promise.all(e.content.map(async e=>{let n=typeof e.content==`string`?e.content:e.content.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
11
|
+
`),r={functionResponse:{id:e.id??void 0,name:e.name,response:{output:n}}};return typeof e.content==`string`?[r]:[r,...await Promise.all(e.content.filter(e=>e.type===`file`).map(e=>Zt(e.file,t,`tool-result`)))]}))).flat(1)}}function Jt(e){let t=[],n=e.content.filter(e=>e.type===`text`);if(n.length>0){let e=n.map(e=>e.text).join(``);e&&t.push({text:e})}let r=e.content.filter(e=>e.type===`tool-call`);return r.length>0&&t.push(...r.map(e=>{let t={functionCall:{id:e.id??void 0,name:e.name,args:e.parameters}};return e.providerMetadata?.thoughtSignature&&(t.thoughtSignature=e.providerMetadata.thoughtSignature),t})),{role:`model`,parts:t}}async function Yt(e,t){return typeof e.content==`string`?{role:`user`,parts:[{text:e.content}]}:{role:`user`,parts:(await Promise.all(e.content.map(e=>Xt(e,t)))).filter(e=>e!==null)}}async function Xt(e,t){return e.type===`text`?{text:e.text}:e.type===`file`?Zt(e.file,t,`user-message`):null}async function Zt(e,t,n){if(e.kind===`text`){let r=await Q(e,{provider:`gemini`,model:t.model,accepted:[`text`],purpose:n,resolver:t.fileResolver,signal:t.signal});if(r.type!==`text`)throw Error(`Unsupported Gemini text source: ${r.type}`);return{text:$t(e,r.content,r.name,r.mimeType)}}if(e.kind===`document`&&e.mimeType!==`application/pdf`)throw Error(`Gemini document file support is limited to PDFs. Received ${e.mimeType}`);return Qt(await Q(e,{provider:`gemini`,model:t.model,accepted:[`gemini-file-uri`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}function Qt(e,t){if(e.type===`base64`)return{inlineData:{mimeType:e.mimeType??t.mimeType,data:e.data}};if(e.type===`url`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.url}};if(e.type===`gemini-file-uri`)return{fileData:{mimeType:e.mimeType??t.mimeType,fileUri:e.uri}};throw Error(`Unsupported Gemini file source: ${e.type}`)}function $t(e,t,n,r){return`File: ${n??e.name}\nMIME type: ${r??e.mimeType}\n\n${t}`}function en(e){switch(e){case _.STOP:return[!0,`stop`];case _.MAX_TOKENS:return[!0,`length`];case _.FINISH_REASON_UNSPECIFIED:case _.SAFETY:case _.RECITATION:case _.LANGUAGE:case _.OTHER:case _.BLOCKLIST:case _.PROHIBITED_CONTENT:case _.SPII:case _.MALFORMED_FUNCTION_CALL:case _.IMAGE_SAFETY:return[!1,`error`]}return[!1,`error`]}async function tn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v={...Wt(c),...l===void 0?{}:{maxOutputTokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{topP:d},...f===void 0?{}:{stopSequences:Array.isArray(f)?f:[f]},...Ut(p,m,a,o),...h},y;try{Y(g,`Generate aborted`);let e=await Gt(r,{model:n,fileResolver:s?.fileResolver,signal:g}),c=Bt(a,i,v);p!==`none`&&Ht(c,o);let l={contents:e,config:c};_?.debug(`Gemini request`,{request:Z(l)});let u=await X(t.models.generateContent({model:n,...l}),g,`Generate aborted`);Y(g,`Generate aborted`),y=nn(u,{tracer:_})}catch(e){Y(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),y=He(e)}return _?.debug(`Gemini response`,{result:y}),y}function nn(e,t){let{tracer:n}=t,r=e.usageMetadata?.promptTokenCount??0,i=G({in:r,out:(e.usageMetadata?.totalTokenCount??r)-r},{cachedIn:e.usageMetadata?.cachedContentTokenCount,reasoningOut:e.usageMetadata?.thoughtsTokenCount});if(!e)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};if(e.promptFeedback&&e.promptFeedback.blockReason)return{type:`error`,error:{type:`Blocked`,message:`Response blocked by Google AI: ${e.promptFeedback.blockReason}, ${e.promptFeedback.blockReasonMessage}`},usage:i,raw:e};if(!e.candidates||e.candidates.length===0)return{type:`error`,error:{type:`InvalidResponse`,message:`Invalid or empty response from Google AI`},usage:{in:0,out:0},raw:e};e.candidates.length>1&&n?.warn(`We received ${e.candidates.length} response candidates`);let a=e.candidates[0],o=a.content?.parts||[],s=o.map(e=>e.text).filter(e=>e!==void 0).join(``),[c,l]=en(a.finishReason);if(c){let t=[];s&&t.push({type:`text`,text:s});let n=o.filter(e=>e.functionCall),r=n.length>0?n.map(e=>({call:e.functionCall,thoughtSignature:e.thoughtSignature})):(e.functionCalls??[]).map(e=>({call:e,thoughtSignature:void 0}));if(r.length>0)for(let{call:e,thoughtSignature:n}of r)if(e.args==null)t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:{},...n?{providerMetadata:{thoughtSignature:n}}:{}});else if(typeof e.args!=`object`||Array.isArray(e.args))throw Error(`Invalid tool call arguments for ${e.name}: expected object, got ${typeof e.args}`);else t.push({type:`tool-call`,id:e.id??``,name:e.name??``,parameters:e.args,...n?{providerMetadata:{thoughtSignature:n}}:{}});return{type:`success`,id:e.responseId??``,model:e.modelVersion??``,role:`assistant`,finishReason:r.length>0?`function_call`:l,content:t,text:H(t),usage:i,raw:e}}else return{type:`error`,error:{type:`Undetermined`,message:`Unexpected stop reason: ${l}`},usage:i,raw:e}}function rn(){let e=0,t=-1,n=!1,r=``,i=``,a=0,o=0,s=0,c=0,l=null;function u(e){t<0||(l===`text`?e.push({type:`text-complete`,data:{index:t}}):l===`thinking`&&e.push({type:`thinking-complete`,data:{index:t}}),l=null,t=-1)}function d(d){let f=[];r||(r=d.responseId||`gemini-${Date.now()}`,i=d.modelVersion||`gemini`,f.push({type:`start`,id:r,data:{model:i,timestamp:Date.now()}})),d.usageMetadata&&(a=d.usageMetadata.promptTokenCount||0,o=(d.usageMetadata.totalTokenCount||0)-a,s=d.usageMetadata.cachedContentTokenCount||0,c=d.usageMetadata.thoughtsTokenCount||0);let p=d.candidates?.[0];if(!p)return f;let m=p.content?.parts||[];for(let r of m){let i=`thought`in r&&r.thought===!0,a=Object.keys(r),o=a.length===1&&`text`in r&&!r.text;if(!(`thoughtSignature`in r&&!r.text&&!r.functionCall||a.length===2&&`text`in r&&`thoughtSignature`in r&&!r.text||o)&&(i&&r.text?(l!==`thinking`&&(u(f),t=e++,l=`thinking`,f.push({type:`thinking-start`,data:{index:t}})),f.push({type:`thinking-delta`,data:{index:t,text:r.text}})):r.text&&!i?(l!==`text`&&(u(f),t=e++,l=`text`,f.push({type:`text-start`,data:{index:t}})),f.push({type:`text-delta`,data:{text:r.text,index:t}})):r.functionCall||console.log(`[gemini] unhandled part type: ${JSON.stringify(Object.keys(r))}`),r.functionCall)){u(f),n=!0;let t=e++,i=r.functionCall.id||`tool-${t}`,a=r.functionCall.name??``;f.push({type:`tool-call-start`,data:{index:t,id:i,name:a}});let o=r.functionCall.args??{},s=JSON.stringify(o);f.push({type:`tool-call-args-delta`,data:{index:t,id:i,name:a,delta:s,accumulated:s}});let c={index:t,id:i,name:a,arguments:o},l=r;l.thoughtSignature&&(c.providerMetadata={thoughtSignature:l.thoughtSignature}),f.push({type:`tool-call-complete`,data:c})}}if(p.finishReason&&p.finishReason!==_.FINISH_REASON_UNSPECIFIED){u(f);let[e,t]=en(p.finishReason),r=n?`function_call`:t;!e&&!n?f.push({type:`error`,data:{type:`FinishReasonError`,message:`Unexpected finish reason: ${p.finishReason}`,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c}),raw:d}}):f.push({type:`complete`,data:{finishReason:r,usage:G({in:a,out:o},{cachedIn:s,reasoningOut:c})}})}return f}return{handleChunk:d}}async function*an(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer,v=Bt(a,i,{...Wt(l),...u===void 0?{}:{maxOutputTokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{topP:f},...p===void 0?{}:{stopSequences:Array.isArray(p)?p:[p]},...Ut(m,h,a,o),...g});m!==`none`&&Ht(v,o);let y=rn();try{let e={contents:await Gt(r,{model:n,fileResolver:s?.fileResolver,signal:c}),config:v};_?.debug(`Gemini streaming request`,{request:Z(e)});let i=await t.models.generateContentStream({model:n,...e});for await(let e of i){let t=y.handleChunk(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function on(e){let t=new y({apiKey:e});return{name:`Gemini`,async createGenerationRequest(e,n){return await tn({client:t,model:e,...n})},createStreamingRequest(e,n){return an({client:t,model:e,...n})}}}async function sn(e){let{provider:t,model:n,messages:r,system:i,tools:a,providerTools:o,tracer:s,fileResolver:c,...l}=e;return t.createGenerationRequest(n,{messages:r,system:i,tools:a,providerTools:o,runtime:{tracer:s,fileResolver:c},...l})}async function cn(e){if(`instruct`in e){let{instruct:t,messages:n,...r}=e,i=ce(t),a=await ln({...r,messages:[...n??[],i.message]});if(!a.ok)return a;try{return{...a,response:i.parse(a.final)}}catch(e){return{ok:!1,messages:a.messages,final:a.final,usage:a.usage,error:{kind:`parse`,error:e,message:e instanceof Error?e.message:String(e)}}}}return ln(e)}async function ln(e){let{provider:t,model:n,messages:r,system:i,onToolCall:a,maxIterations:o,tracer:s,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_=new AbortController().signal}=e,v=_e(e),y=[...r],b=[],x=W(),S=0,C,w=e=>{y.push(e),b.push(e)},T=e=>(s?.setResult({kind:`llm`,model:n,request:{messages:r},response:{content:e.ok?e.final.content:null},usage:de(e.usage),finishReason:e.ok?e.final.finishReason:void 0}),s?.end(e.ok?`ok`:`error`),e),E=(e,t)=>{if(!e||t.type===`error`){e?.end(`error`);return}e.setResult({kind:`llm`,model:t.model??n,request:{messages:y},response:{content:t.content},usage:de(t.usage),finishReason:t.finishReason}),e.end()};try{for(;;){if(Y(_,`Generate aborted`),o!==void 0&&S>=o)return T({ok:!1,messages:b,error:{kind:`model`,error:{type:`error`,error:{type:`MaxIterations`,message:`Exceeded max iterations (${o})`}}},usage:x});S+=1;let e=s?.startSpan(`turn-${S}`,{type:`llm`}),r=v.executable(),ee=r.length>0?r.map(e=>({name:e.name,description:e.description,schema:e.schema})):void 0,D=v.provider(),O;try{O=await sn({provider:t,model:n,messages:y,system:i,tools:ee,providerTools:D.length>0?D:void 0,tracer:e,fileResolver:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g,signal:_}),Y(_,`Generate aborted`)}catch(t){throw t instanceof Error&&t.name===`AbortError`&&e?.end(`ok`),t}if(he(x,O),E(e,O),O.type===`error`)return T({ok:!1,messages:b,error:{kind:`model`,error:O},usage:x});let k={role:`assistant`,id:O.id,model:O.model,content:O.content,finishReason:O.finishReason};if(w(k),C=k,O.finishReason!==`function_call`)return T({ok:!0,response:C,messages:b,final:C,usage:x});let A=re(O.content);if(A.length===0)return T({ok:!0,response:C,messages:b,final:C,usage:x});let{results:j}=await ve(A,a,_,v,s);Y(_,`Generate aborted`),j.length>0&&w({role:`tool`,id:crypto.randomUUID(),content:j})}}catch(e){throw e instanceof j?(s?.end(`error`),new j(e.message,{toolName:e.toolName,messages:e.messages??b,partial:e.partial??C,usage:e.usage??x,cause:e.cause})):e instanceof k?(s?.end(`ok`),new k(`Generate aborted`,{reason:e.reason,messages:e.messages??b,partial:e.partial,usage:e.usage??x})):e instanceof Error&&e.name===`AbortError`?(s?.end(`ok`),new k(`Generate aborted`,{reason:_.reason,messages:b,usage:x})):e}}function un(e){if(e&&e.length>0)return e.map(e=>({type:`function`,strict:!0,name:e.name,description:e.description,parameters:r.toJSONSchema(e.schema)}))}const dn={web_search:`web_search_preview`,code_execution:`code_interpreter`};function fn(e){return e?.map(e=>({type:dn[e.name]??e.name,...e.config}))}function pn(e,t,n){if(e===void 0)return{};if(e===`auto`||e===`none`||e===`required`)return{tool_choice:e};if(t?.some(t=>t.name===e.name))return{tool_choice:{type:`function`,name:e.name}};let r=n?.find(t=>t.name===e.name);if(r)return{tool_choice:{type:dn[r.name]??r.name}};throw Error(`Tool choice references an unavailable tool: ${e.name}`)}function mn(e){return e===!0?{reasoning:{effort:`high`}}:e===!1?{reasoning:{effort:`none`}}:{}}async function hn(e,t={model:``}){return(await Promise.all(e.map(e=>gn(e,t)))).flat(1)}async function gn(e,t){switch(e.role){case`tool`:return _n(e,t);case`assistant`:return vn(e);default:return yn(e,t)}}async function _n(e,t){return Promise.all(e.content.map(async e=>({type:`function_call_output`,call_id:e.id,output:typeof e.content==`string`?e.content:await Promise.all(e.content.map(e=>e.type===`text`?Promise.resolve({type:`input_text`,text:e.text}):xn(e.file,t,`tool-result`)))})))}function vn(e){let t=[],n=H(e.content);n&&t.push({role:e.role,content:n});let r=e.content.filter(e=>e.type===`tool-call`);for(let e of r)t.push({type:`function_call`,call_id:e.id,name:e.name,arguments:JSON.stringify(e.parameters)});let i=e.content.filter(e=>e.type===`provider-tool`);for(let e of i)e.output!=null&&t.push(e.output);return t}async function yn(e,t){if(typeof e.content==`string`)return{role:e.role,content:e.content};{let n=(await Promise.all(e.content.map(e=>bn(e,t)))).filter(e=>e!==null);return{role:e.role,content:n}}}async function bn(e,t){return e.type===`text`?{type:`input_text`,text:e.text}:e.type===`file`?xn(e.file,t,`user-message`):(e.type,null)}async function xn(e,t,n){if(e.kind===`image`)return{type:`input_image`,image_url:Sn(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e),detail:`auto`};if(e.kind===`document`){if(e.mimeType!==`application/pdf`)throw Error(`OpenAI file inputs currently support PDF documents. Received ${e.mimeType}`);return Cn(await Q(e,{provider:`openai`,model:t.model,accepted:[`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal}),e)}let r=await Q(e,{provider:`openai`,model:t.model,accepted:[`text`,`url`,`base64`],purpose:n,resolver:t.fileResolver,signal:t.signal});return r.type===`text`?{type:`input_text`,text:r.content}:Cn(r,e)}function Sn(e,t){if(e.type===`url`)return e.url;if(e.type===`base64`)return`data:${e.mimeType??t.mimeType};base64,${e.data}`;throw Error(`Unsupported OpenAI image source: ${e.type}`)}function Cn(e,t){if(e.type===`url`)return{type:`input_file`,filename:e.name??t.name,file_url:e.url};if(e.type===`base64`)return{type:`input_file`,filename:e.name??t.name,file_data:`data:${e.mimeType??t.mimeType};base64,${e.data}`};throw Error(`Unsupported OpenAI file source: ${e.type}`)}async function wn(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,reasoning:c,maxOutputTokens:l,temperature:u,topP:d,stop:f,toolChoice:p,parallelToolCalls:m,providerOptions:h,signal:g}=e,_=s?.tracer,v;try{if(Y(g,`Generate aborted`),f!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let e=[...un(a)??[],...fn(o)??[]],y={model:n,input:await hn(r,{model:n,fileResolver:s?.fileResolver,signal:g}),...i&&{instructions:i},...e.length>0?{tools:e}:{},...mn(c),...l===void 0?{}:{max_output_tokens:l},...u===void 0?{}:{temperature:u},...d===void 0?{}:{top_p:d},...pn(p,a,o),...m===void 0?{}:{parallel_tool_calls:m},...h};_?.debug(`OpenAI ResponsesAPI request`,{request:Z(y)});let b=await X(t.responses.create(y,...g?[{signal:g}]:[]),g,`Generate aborted`);Y(g,`Generate aborted`),v=Tn(b)}catch(e){Y(g,`Generate aborted`),_?.error(e instanceof Error?e.message:String(e)),v=He(e)}return _?.debug(`OpenAI ResponsesAPI response`,{result:v}),v}function Tn(e){if(e.error)return{type:`error`,error:{type:e.error.code||`undetermined`,message:e.error.message||`Response generation failed`},usage:En(e.usage),raw:e};let t=e.output?.filter(e=>e.type===`reasoning`)?.map(e=>e),n=[];if(t&&t.length>0)for(let e of t){let t=e.summary?.[0]?.text||e.content?.[0]?.text||``;(t||e.encrypted_content)&&n.push({type:`thinking`,text:t,...e.encrypted_content&&{encrypted:e.encrypted_content}})}e.output_text&&n.push({type:`text`,text:e.output_text});let r=e.output?.filter(e=>e.type===`function_call`);if(r&&r.length>0)for(let e of r){let t=e;try{n.push({type:`tool-call`,id:t.call_id||t.id||``,name:t.name||``,parameters:t.arguments?JSON.parse(t.arguments):{}})}catch(e){throw Error(`Failed to parse tool call arguments for ${t.name}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${t.arguments}`)}}return{type:`success`,id:e.id,model:e.model||``,role:`assistant`,finishReason:e.incomplete_details?`error`:r&&r.length>0?`function_call`:`stop`,content:n,text:H(n),usage:En(e.usage),raw:e}}function En(e){return G({in:e?.input_tokens??0,out:e?.output_tokens??0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}function Dn(){let e=``,t=``,n=0,r=-1,i=!1,a=new Map,o=new Map,s=new Set([`web_search_call`,`file_search_call`,`code_interpreter_call`]),c=new Map;function l(l){let u=[];switch(l.type){case`response.created`:e=l.response.id||`openai-${Date.now()}`,t=l.response.model,u.push({type:`start`,id:e,data:{model:t,timestamp:Date.now()}});break;case`response.output_text.delta`:r===-1&&(r=n++,u.push({type:`text-start`,data:{index:r}})),u.push({type:`text-delta`,data:{text:l.delta,index:r}});break;case`response.output_text.done`:r>=0&&(u.push({type:`text-complete`,data:{index:r}}),r=-1);break;case`response.function_call_arguments.delta`:{let e=l.item_id;if(!c.has(e)){let t=a.get(e),r=t?.name||``,i=t?.callId||e,o=n++;c.set(e,{id:e,callId:i,name:r,argumentsBuffer:``,partIdx:o}),u.push({type:`tool-call-start`,data:{index:o,id:i,name:r}})}let t=c.get(e);t.argumentsBuffer+=l.delta,u.push({type:`tool-call-args-delta`,data:{index:t.partIdx,id:t.callId,name:t.name,delta:l.delta,accumulated:t.argumentsBuffer}});break}case`response.function_call_arguments.done`:{i=!0;let e=l.item_id,t=c.get(e),n=l.name||t?.name||``;if(t){try{let e=l.arguments?JSON.parse(l.arguments):{};u.push({type:`tool-call-complete`,data:{index:t.partIdx,id:t.callId,name:n,arguments:e}})}catch(e){throw Error(`Failed to parse function call arguments for ${n}: ${e instanceof Error?e.message:String(e)}\nRaw value: ${l.arguments}`)}c.delete(e)}break}case`response.completed`:{let e=l.response.usage;u.push({type:`complete`,data:{finishReason:l.response.incomplete_details?`error`:i?`function_call`:`stop`,usage:G({in:e?.input_tokens||0,out:e?.output_tokens||0},{cachedIn:e?.input_tokens_details?.cached_tokens,reasoningOut:e?.output_tokens_details?.reasoning_tokens})}});break}case`response.failed`:u.push({type:`error`,data:{type:`RESPONSES_API_ERROR`,message:`Response failed: ${l.response.status}`,raw:l}});break;case`response.output_item.added`:if(l.item?.type===`reasoning`)r=n++,u.push({type:`thinking-start`,data:{index:r}});else if(l.item?.type===`function_call`){let e=l.item,t=e.id||e.call_id;t&&a.set(t,{name:e.name||``,callId:e.call_id||t})}else if(l.item&&s.has(l.item.type)){let e=l.item,t=n++;o.set(e.id,t),u.push({type:`provider-tool-start`,data:{index:t,id:e.id,name:e.type}})}break;case`response.output_item.done`:if(l.item?.type===`reasoning`&&r>=0)u.push({type:`thinking-complete`,data:{index:r}}),r=-1;else if(l.item&&s.has(l.item.type)){let e=l.item,t=o.get(e.id);t!==void 0&&(u.push({type:`provider-tool-complete`,data:{index:t,id:e.id,name:e.type,output:l.item}}),o.delete(e.id))}break;case`response.reasoning_text.delta`:l.delta&&u.push({type:`thinking-delta`,data:{index:r,text:l.delta}});break;case`response.reasoning_summary_text.delta`:l.delta&&u.push({type:`thinking-summary-delta`,data:{index:r,text:l.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: ${l.type}`)}return u}return{handleEvent:l}}async function*On(e){let{client:t,model:n,messages:r,system:i,tools:a,providerTools:o,runtime:s,signal:c,reasoning:l,maxOutputTokens:u,temperature:d,topP:f,stop:p,toolChoice:m,parallelToolCalls:h,providerOptions:g}=e,_=s?.tracer;if(p!==void 0)throw Error(`OpenAI Responses does not support normalized stop sequences`);let v=[...un(a)??[],...fn(o)??[]],y=Dn();try{let e={model:n,input:await hn(r,{model:n,fileResolver:s?.fileResolver,signal:c}),...i&&{instructions:i},stream:!0,...v.length>0?{tools:v}:{},...mn(l),...u===void 0?{}:{max_output_tokens:u},...d===void 0?{}:{temperature:d},...f===void 0?{}:{top_p:f},...pn(m,a,o),...h===void 0?{}:{parallel_tool_calls:h},...g};_?.debug(`OpenAI ResponsesAPI streaming request`,{request:Z(e)});let p=t.responses.stream(e,...c?[{signal:c}]:[]);for await(let e of p){let t=y.handleEvent(e);for(let e of t)yield e}}catch(e){if(c?.aborted)return;_?.error(e instanceof Error?e.message:String(e)),yield{type:`error`,data:{type:`STREAMING_ERROR`,message:e instanceof Error?e.message:String(e),raw:e}}}}function kn(e){let t=new b({apiKey:e});return{name:`OpenAI`,async createGenerationRequest(e,n){return await wn({client:t,model:e,...n})},createStreamingRequest(e,n){return On({client:t,model:e,...n})}}}const An=n.object({searchTerm:n.string().describe(`The search term to query`)}),jn=new class{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){let{rateLimit:t}=e;this.apiKey=e[`api-key`],this.throttle=t?1100/t:void 0}async execute(e,t){let{searchTerm:n}=e;if(this.throttle){for(;Date.now()-this.lastExecTime<this.throttle;)await X(De(this.throttle-(Date.now()-this.lastExecTime)),t.signal);this.lastExecTime=Date.now()}try{Y(t.signal);let e=this.apiKey,r=new URL(`https://api.search.brave.com/res/v1/web/search`);r.searchParams.append(`q`,n),r.searchParams.append(`format`,`json`);let i=await fetch(r.toString(),{method:`GET`,signal:t.signal,headers:{Accept:`application/json`,"X-Subscription-Token":e??``}});if(!i.ok)throw Error(`[Brave] HTTP error ${i.status}: ${i.statusText}`);let a=await i.json();return JSON.stringify(a)}catch(e){throw t.signal.aborted||e instanceof Error&&e.name===`AbortError`?e:e instanceof Error?Error(`[Brave] Error fetching search results: ${e.message}`):e}}},Mn={name:`calculator`,description:`Performs basic arithmetic operations`,schema:i.object({operation:i.enum([`add`,`subtract`,`multiply`,`divide`]).describe(`The operation to perform (add, subtract, multiply, divide)`),a:i.number().describe(`First operand`),b:i.number().describe(`Second operand`)}),execute:async({operation:e,a:t,b:n})=>{switch(e){case`add`:return`${t} + ${n} = ${t+n}`;case`subtract`:return`${t} - ${n} = ${t-n}`;case`multiply`:return`${t} * ${n} = ${t*n}`;case`divide`:if(n===0)throw Error(`Cannot divide by zero`);return`${t} / ${n} = ${t/n}`;default:throw Error(`Unknown operation: ${e}`)}}};async function Nn(e,t={}){let n=t.timeout??3e4,r=t.maxBuffer??1048576;return new Promise((i,a)=>{let o=x(e,[],{shell:!0,cwd:t.cwd}),s=``,c=``,l=!1,u=!1,d=!1,f=setTimeout(()=>{l=!0,o.kill(`SIGTERM`)},n),p=()=>{u=!0,o.kill(`SIGTERM`)};t.signal?.addEventListener(`abort`,p);let m=()=>{clearTimeout(f),t.signal?.removeEventListener(`abort`,p)};o.stdout?.setEncoding(`utf-8`),o.stderr?.setEncoding(`utf-8`),o.stdout?.on(`data`,e=>{if(s+=e,s.length+c.length>r){d=!0,o.kill(`SIGTERM`);return}t.onChunk?.(e)}),o.stderr?.on(`data`,e=>{if(c+=e,s.length+c.length>r){d=!0,o.kill(`SIGTERM`);return}t.onChunk?.(e)}),o.on(`error`,e=>{m(),a(e)}),o.on(`close`,e=>{if(m(),l){let e=Error(`Command timed out after ${n}ms`);e.stdout=s,e.stderr=c,a(e);return}if(u){let e=Error(`Command aborted`);e.stdout=s,e.stderr=c,a(e);return}if(d){let e=Error(`Command output exceeded maxBuffer (${r} bytes)`);e.stdout=s,e.stderr=c,a(e);return}if(e!==0){let t=Error(`Command failed with exit code ${e}`);t.stdout=s,t.stderr=c,t.code=e??-1,a(t);return}i({stdout:s,stderr:c})})})}function Pn(e){if(e instanceof Error){let t=e,n=`Error executing command: ${e.message}`;return t.stdout&&(n+=`\n[stdout]: ${t.stdout}`),t.stderr&&(n+=`\n[stderr]: ${t.stderr}`),n}return`Error executing command: ${String(e)}`}function Fn(e,t){return t&&t.trim()?`${e}\n[stderr]: ${t}`:e}const In=n.object({command:n.string().describe(`The shell command to execute`)}),Ln=new class{name=`exec`;description=`Execute a shell command and return the output.`;schema=In;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,t){let{command:n}=e;try{let e=await Nn(n,{timeout:this.timeout,maxBuffer:this.maxBuffer,cwd:this.cwd,signal:t.signal,onChunk:e=>t.emit(e)});return Fn(e.stdout,e.stderr)}catch(e){return Pn(e)}}},Rn={name:`patch-file`,description:`Patch a file by replacing an exact string match within a specified line range`,schema:i.object({path:i.string().describe(`The file path to patch`),old_string:i.string().describe(`The exact text to find and replace`),new_string:i.string().describe(`The replacement text`),start_line:i.number().int().positive().describe(`1-indexed start line of the region to match within`),end_line:i.number().int().positive().describe(`1-indexed end line (inclusive) of the region to match within`)}),summarize:({path:e,start_line:t,end_line:n})=>`${e}:${t}:${n}`,execute:async({path:e,old_string:t,new_string:n,start_line:r,end_line:i})=>{if(i<r)throw Error(`end_line (${i}) must be >= start_line (${r})`);let a;try{a=await c(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}let o=a.split(`
|
|
12
|
+
`);if(r>o.length)throw Error(`start_line (${r}) exceeds file length (${o.length} lines)`);if(i>o.length)throw Error(`end_line (${i}) exceeds file length (${o.length} lines)`);let s=o.slice(r-1,i).join(`
|
|
13
|
+
`),l=s.indexOf(t);if(l===-1)throw Error(`old_string not found within lines ${r}-${i} of "${e}"`);if(s.indexOf(t,l+1)!==-1)throw Error(`old_string matches multiple times within lines ${r}-${i} of "${e}"`);let d=s.replace(t,n),f=[...o.slice(0,r-1),...d.split(`
|
|
14
|
+
`),...o.slice(i)].join(`
|
|
15
|
+
`);try{await u(e,f,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}return`Successfully patched "${e}" (lines ${r}-${i})`}},zn={name:`read-file`,description:`Read the contents of a file from disk`,schema:i.object({path:i.string().describe(`The file path to read from`)}),summarize:({path:e})=>e,execute:async({path:e})=>{try{return await c(e,`utf-8`)}catch(t){throw t instanceof Error?Error(`Failed to read file "${e}": ${t.message}`):t}}},Bn={name:`write-file`,description:`Write content to a file on disk, creating directories if needed`,schema:i.object({path:i.string().describe(`The file path to write to`),content:i.string().describe(`The content to write to the file`)}),summarize:({path:e})=>e,execute:async({path:e,content:t})=>{try{return await s(f(e),{recursive:!0}),await u(e,t,`utf-8`),`Successfully wrote ${t.length} characters to "${e}"`}catch(t){throw t instanceof Error?Error(`Failed to write file "${e}": ${t.message}`):t}}};function Vn(e){try{let t=r.fromJSONSchema(e);return t instanceof r.ZodObject?t.strict():r.object({}).passthrough()}catch{return r.object({}).passthrough()}}function Hn(e,t,n){return e.map(e=>Wn(e,t,n))}function Un(e,t){return e.map(e=>{let n=t?`${t}_${e.name}`:e.name,r=Vn(e.inputSchema);return{name:n,description:e.description??``,schema:r}})}function Wn(e,t,n){let r=n?`${n}_${e.name}`:e.name,i=Vn(e.inputSchema);return{name:r,description:e.description??``,schema:i,async execute(n,i){let a;try{a=await t.callTool({name:e.name,arguments:n},void 0,{signal:i.signal})}catch(t){throw i.signal.aborted||t instanceof Error&&t.name===`AbortError`?t:new j(`MCP tool call failed: ${e.name}`,{toolName:r,cause:t})}if(`isError`in a&&a.isError)throw Error(Kn(a.content));return Gn(a.content)}}}function Gn(e){return e.some(e=>e.type===`image`)?e.filter(e=>e.type===`text`||e.type===`image`).map(e=>{if(e.type===`text`)return{type:`text`,text:e.text};let t=e;return{type:`file`,file:{kind:`image`,mimeType:t.mimeType,name:`mcp-image`,source:{type:`base64`,data:t.data}}}}):e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
16
|
+
`)}function Kn(e){return e.filter(e=>e.type===`text`).map(e=>e.text).join(`
|
|
17
|
+
`)||`MCP tool execution error`}var qn=class{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;let t=e?.tracer?.startSpan(`mcp:connect`,{type:`internal`});this.client=new S({name:`axle`,version:`1.0.0`}),this.config.transport===`stdio`?this.transport=new C({command:this.config.command,args:this.config.args,env:this.config.env}):this.transport=new w(new URL(this.config.url),{requestInit:this.config.headers?{headers:this.config.headers}:void 0});try{await this.client.connect(this.transport,{signal:e?.signal}),this._connected=!0,t?.end(`ok`)}catch(e){throw t?.end(`error`),e}}async listTools(e){let t=this.assertConnected();return Hn(await this.fetchTools(t,e?.tracer,e?.signal),t,e?.prefix)}async listToolDefinitions(e){let t=this.assertConnected();return Un(await this.fetchTools(t,e?.tracer,e?.signal),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,t,n){if(this.cachedMcpTools)return this.cachedMcpTools;t?.debug(`mcp:listTools`);let r=await e.listTools(void 0,{signal:n});return this.cachedMcpTools=r.tools.map(e=>({name:e.name,description:e.description,inputSchema:e.inputSchema})),this.cachedMcpTools}assertConnected(){if(!this._connected||!this.client)throw Error(`MCP not connected. Call connect() first.`);return this.client}};const Jn={debug:0,info:1,warn:2,error:3};var Yn=class{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){let t=this.writers.indexOf(e);t!==-1&&this.writers.splice(t,1)}startSpan(e,t){let n={traceId:crypto.randomUUID(),spanId:crypto.randomUUID(),name:e,type:t?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.writers.forEach(e=>e.onSpanStart(n)),new Xn(n,this)}async flush(){for(let e of this.writers)e.flush&&await e.flush()}_notifySpanEnd(e){this.writers.forEach(t=>t.onSpanEnd(e))}_notifySpanUpdate(e){this.writers.forEach(t=>t.onSpanUpdate?.(e))}_notifyEvent(e,t){this.writers.forEach(n=>n.onEvent?.(e,t))}_notifySpanStart(e){this.writers.forEach(t=>t.onSpanStart(e))}_shouldLog(e){return Jn[e]>=Jn[this._minLevel]}},Xn=class e{data;tracer;ended=!1;constructor(e,t){this.data=e,this.tracer=t}startSpan(t,n){let r={traceId:this.data.traceId,spanId:crypto.randomUUID(),parentSpanId:this.data.spanId,name:t,type:n?.type,startTime:performance.now(),status:`ok`,attributes:{},events:[]};return this.tracer._notifySpanStart(r),new e(r,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,t,n){if(this.ended||!this.tracer._shouldLog(t))return;let r={name:e,timestamp:performance.now(),level:t,attributes:n};this.data.events.push(r),this.tracer._notifyEvent(this.data,r)}debug(e,t){this.addEvent(e,`debug`,t)}info(e,t){this.addEvent(e,`info`,t)}warn(e,t){this.addEvent(e,`warn`,t)}error(e,t){this.addEvent(e,`error`,t)}setAttribute(e,t){this.ended||(this.data.attributes[e]=t,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))}};const Zn={debug:0,info:1,warn:2,error:3};var Qn=class{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 Zn[e]>=Zn[this.minLevel]}isSpanVisible(e){return!(e.type===`internal`&&!this.showInternal)}findVisibleAncestor(e){let t=e.parentSpanId;for(;t;){let e=this.spans.get(t);if(!e)break;if(this.isSpanVisible(e))return e;t=e.parentSpanId}return null}calculateVisibleDepth(e){if(!this.isSpanVisible(e))return-1;let t=this.findVisibleAncestor(e);return t?(this.visibleDepths.get(t.spanId)??0)+1:0}formatTimestamp(){if(!this.showTimestamp)return``;let e=new Date;return`[${e.toTimeString().slice(0,8)}.${e.getMilliseconds().toString().padStart(3,`0`)}] `}formatDuration(e){if(!this.showDuration||!e.endTime)return``;let t=e.endTime-e.startTime;return t<1e3?` (${Math.round(t)}ms)`:` (${(t/1e3).toFixed(2)}s)`}formatIndent(e){return` `.repeat(e)}formatSpanName(e){return e.type?`[${e.type}] ${e.name}`:e.name}renderMarkdown(e){return $n(e).trimEnd()}onSpanStart(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.calculateVisibleDepth(e);this.visibleDepths.set(e.spanId,t);let n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatSpanName(e);this.output(`${r}${n}START ${i}`)}onSpanEnd(e){if(this.spans.set(e.spanId,e),!this.isSpanVisible(e))return;let t=this.visibleDepths.get(e.spanId)??0,n=this.formatIndent(t),r=this.formatTimestamp(),i=this.formatDuration(e),a=this.formatSpanName(e),o=e.status===`error`?` [ERROR]`:``;if(this.output(`${r}${n}END ${a}${i}${o}`),e.result?.kind===`llm`){let t=e.result,i=[`model=${t.model}`];if(t.finishReason&&i.push(`finishReason=${t.finishReason}`),t.usage&&(t.usage.inputTokens!==void 0&&i.push(`inputTokens=${t.usage.inputTokens}`),t.usage.outputTokens!==void 0&&i.push(`outputTokens=${t.usage.outputTokens}`),t.usage.cachedInputTokens!==void 0&&i.push(`cachedInputTokens=${t.usage.cachedInputTokens}`),t.usage.cacheWriteInputTokens!==void 0&&i.push(`cacheWriteInputTokens=${t.usage.cacheWriteInputTokens}`),t.usage.reasoningOutputTokens!==void 0&&i.push(`reasoningOutputTokens=${t.usage.reasoningOutputTokens}`)),this.output(`${r}${n} INFO LLM complete ${i.join(` `)}`),this.shouldShowEvent(`debug`)&&t.response.content){let e=(typeof t.response.content==`string`?t.response.content:JSON.stringify(t.response.content,null,2)).split(`
|
|
18
|
+
`);for(let t of e)this.output(`${r}${n} DEBUG ${t}`)}}}onSpanUpdate(e){this.spans.set(e.spanId,e)}onEvent(e,t){if(!this.shouldShowEvent(t.level))return;this.spans.set(e.spanId,e);let n;if(this.isSpanVisible(e))n=this.visibleDepths.get(e.spanId)??0;else{let t=this.findVisibleAncestor(e);n=t?this.visibleDepths.get(t.spanId)??0:0}let r=this.formatIndent(n+1),i=this.formatTimestamp(),a=t.level.toUpperCase().padEnd(5),o=this.markdown&&t.attributes?.markdown===!0,s=t.attributes?Object.entries(t.attributes).filter(([e])=>e!==`markdown`):[],c=t.name;o&&(c=this.renderMarkdown(c));let l=`${i}${r}${a} ${c}`;if(s.length>0){let e=s.map(([e,t])=>`${e}=${JSON.stringify(t)}`).join(` `);l+=` ${e}`}this.output(l)}};function $n(e){return er(E.lexer(e))}function er(e=[]){return e.map(e=>tr(e)).filter(e=>e.length>0).join(`
|
|
19
|
+
`)}function tr(e){switch(e.type){case`space`:return``;case`heading`:return T.bold($(e.tokens));case`paragraph`:return $(e.tokens);case`blockquote`:return sr(er(e.tokens),`> `);case`code`:return(e.lang?T.dim(`${e.lang}\n`):``)+T.yellow(e.text);case`list`:return rr(e)?ar(e):e.raw;case`hr`:return T.dim(`-`.repeat(40));case`table`:return ir(e)?or(e):e.raw;case`html`:return e.text;case`text`:return e.tokens?$(e.tokens):lr(e.text);default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function $(e=[]){return e.map(e=>nr(e)).join(``)}function nr(e){switch(e.type){case`text`:case`escape`:return lr(e.text);case`strong`:return T.bold($(e.tokens));case`em`:return T.italic($(e.tokens));case`codespan`:return T.yellow(e.text);case`del`:return T.strikethrough($(e.tokens));case`link`:{let t=$(e.tokens);return e.href&&e.href!==e.text?`${T.blue.underline(t)} ${T.dim(`(${e.href})`)}`:T.blue.underline(t)}case`image`:return e.text?`${e.text} (${e.href})`:e.href;case`br`:return`
|
|
20
|
+
`;case`html`:return e.text;default:return`tokens`in e&&e.tokens?$(e.tokens):e.raw}}function rr(e){return e.type===`list`&&`items`in e&&Array.isArray(e.items)}function ir(e){return e.type===`table`&&`header`in e&&`rows`in e}function ar(e){return e.items.map((t,n)=>{let r=e.ordered?`${Number(e.start||1)+n}. `:`- `,i=t.task?`[${t.checked?`x`:` `}] `:``,a=er(t.tokens).trimEnd();return r+i+cr(a,r.length+i.length)}).join(`
|
|
21
|
+
`)}function or(e){let t=e.header.map(e=>$(e.tokens)).join(` | `),n=e.rows.map(e=>e.map(e=>$(e.tokens)).join(` | `));return[T.bold(t),...n].join(`
|
|
22
|
+
`)}function sr(e,t){return e.split(`
|
|
23
|
+
`).map(e=>t+e).join(`
|
|
24
|
+
`)}function cr(e,t){let[n=``,...r]=e.split(`
|
|
25
|
+
`);if(r.length===0)return n;let i=` `.repeat(t);return[n,...r.map(e=>i+e)].join(`
|
|
26
|
+
`)}function lr(e){return e.replace(/"/g,`"`).replace(/'/g,`'`).replace(/</g,`<`).replace(/>/g,`>`).replace(/&/g,`&`)}var ur=class{provider;model;enableTools;lastStore;lastName;lastScope;constructor(e){this.provider=e.provider,this.model=e.model,this.enableTools=e.enableTools??!1}async recall(e){let t=e.tracer?.startSpan(`memory.recall`,{type:`internal`});this.lastStore=e.store,this.lastName=e.name,this.lastScope=e.scope;let n=await this.loadStore(e.store,e.name,e.scope);if(n.instructions.length===0)return t?.info(`no stored instructions`),t?.end(),{};t?.info(`loaded instructions`,{count:n.instructions.length});let r=n.instructions.map((e,t)=>`${t+1}. ${e}`).join(`
|
|
27
|
+
`);return t?.end(),{systemSuffix:`## Learned Instructions\n\n${r}`}}async record(e){if(!e.newMessages||e.newMessages.length===0)return;let t=e.tracer?.startSpan(`memory.record`,{type:`internal`}),n=this.formatMessages(e.newMessages);if(!n.trim()){t?.info(`no text content to extract from`),t?.end();return}let r=t?.startSpan(`memory.extract`,{type:`llm`}),i=await cn({provider:this.provider,model:this.model,messages:[{role:`user`,content:n}],system:`You are a memory extraction system. Your job is to extract learnings from a conversation that should be remembered for future runs.
|
|
28
|
+
|
|
29
|
+
Only extract:
|
|
30
|
+
- Explicit user corrections (e.g., "No, always use bullet points")
|
|
31
|
+
- Stated preferences (e.g., "I prefer concise summaries")
|
|
32
|
+
- Patterns that clearly emerged from user feedback
|
|
33
|
+
|
|
34
|
+
Do NOT extract:
|
|
35
|
+
- General knowledge or facts from the conversation content
|
|
36
|
+
- Inferences or speculation about what the user might want
|
|
37
|
+
- Task-specific details that won't apply to future runs
|
|
38
|
+
|
|
39
|
+
Respond with a JSON array of instruction strings. Each instruction should be a clear, actionable directive.
|
|
40
|
+
If there are no learnings to extract, respond with an empty array: []
|
|
41
|
+
|
|
42
|
+
Example response:
|
|
43
|
+
["Always use bullet points for lists", "Keep summaries under 3 sentences"]`,tracer:r});if(!i.ok){t?.warn(`extraction failed`,{error:i.error}),t?.end();return}let a=H(i.final.content);if(!a){t?.end();return}let o=this.parseInstructions(a);if(o.length===0){t?.info(`no instructions extracted`),t?.end();return}let s=await this.loadStore(e.store,e.name,e.scope);s.instructions.push(...o),await this.saveStore(e.store,e.name,e.scope,s),t?.info(`saved instructions`,{count:o.length}),t?.end()}tools(){if(!this.enableTools)return[];let e=this;return[{name:`add_instruction`,description:`Save a learned instruction for future runs. Use this when the user explicitly asks you to remember something.`,schema:i.object({instruction:i.string().describe(`The instruction to remember`)}),async execute(t){if(!e.lastStore)return`Error: memory not initialized (no recall has been called yet)`;let n=await e.loadStore(e.lastStore,e.lastName,e.lastScope);return n.instructions.push(t.instruction),await e.saveStore(e.lastStore,e.lastName,e.lastScope,n),`Instruction saved: "${t.instruction}"`}}]}formatMessages(e){let t=[];for(let n of e)if(n.role===`user`){let e=typeof n.content==`string`?n.content:H(n.content);e&&t.push(`User: ${e}`)}else if(n.role===`assistant`){let e=H(n.content);e&&t.push(`Assistant: ${e}`)}return t.join(`
|
|
44
|
+
|
|
45
|
+
`)}parseInstructions(e){let t=e.trim(),n=t.match(/^```(?:json)?\s*\n?([\s\S]*?)\n?\s*```$/);n&&(t=n[1].trim());try{let e=JSON.parse(t);if(Array.isArray(e)&&e.every(e=>typeof e==`string`))return e}catch{}return[]}getStorePath(e,t){let n=e??`default`,r=n;if(t&&Object.keys(t).length>0){let e=Object.entries(t).sort(([e],[t])=>e.localeCompare(t)).map(([e,t])=>`${e}=${t}`).join(`&`);r=`${n}-${ee.createHash(`sha256`).update(e).digest(`hex`).slice(0,8)}`}return`memory/procedural/${r}.json`}async loadStore(e,t,n){let r=this.getStorePath(t,n),i=await e.read(r);if(i)try{let e=JSON.parse(i);if(e&&Array.isArray(e.instructions))return{instructions:e.instructions}}catch{}return{instructions:[]}}async saveStore(e,t,n,r){if(!r)return;let i=this.getStorePath(t,n);await e.write(i,JSON.stringify(r,null,2))}};export{W as A,ke as C,ye as D,Se as E,k as F,D as I,M,j as N,me as O,A as P,Ae as S,we as T,Ye as _,Bn as a,Ne as b,Ln as c,kn as d,cn as f,vt as g,zt as h,qn as i,oe as j,ue as k,Mn as l,on as m,Qn as n,zn as o,sn as p,Yn as r,Rn as s,ur as t,jn as u,Ue as v,Te as w,Me as x,Re as y};
|