gemi 0.205.2 → 0.205.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +1 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/providers/fileRejection.d.ts +4 -0
- package/dist/ai/providers/fileRejection.d.ts.map +1 -1
- package/dist/ai/providers/request.d.ts.map +1 -1
- package/dist/ai/providers/staleReasoning.d.ts +25 -0
- package/dist/ai/providers/staleReasoning.d.ts.map +1 -0
- package/dist/ai/testing/index.js +1 -1
- package/dist/chunk-2e40rx0p.js +11 -0
- package/dist/{chunk-bb74k64k.js.map → chunk-2e40rx0p.js.map} +7 -6
- package/dist/{chunk-mepaafn3.js → chunk-bdrce9s8.js} +1 -1
- package/dist/{chunk-zfrwh9qm.js → chunk-bz84hrc3.js} +2 -2
- package/dist/{chunk-zfrwh9qm.js.map → chunk-bz84hrc3.js.map} +1 -1
- package/dist/{chunk-kj7z3kav.js → chunk-rbndzqg7.js} +1 -1
- package/dist/server/index.js +1 -1
- package/package.json +1 -1
- package/dist/chunk-bb74k64k.js +0 -11
- /package/dist/{chunk-mepaafn3.js.map → chunk-bdrce9s8.js.map} +0 -0
- /package/dist/{chunk-kj7z3kav.js.map → chunk-rbndzqg7.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as bQ,da as yQ,ea as IQ,fa as Y6,ga as V6,ha as z6,ia as b$,ja as D6,ka as H6,la as Y$,ma as P6,na as F6,oa as N6,pa as O6}from"../chunk-
|
|
2
|
+
import{ca as bQ,da as yQ,ea as IQ,fa as Y6,ga as V6,ha as z6,ia as b$,ja as D6,ka as H6,la as Y$,ma as P6,na as F6,oa as N6,pa as O6}from"../chunk-2e40rx0p.js";import{$c as s9,Ac as VZ,Bc as e$,Dc as JQ,Ec as XQ,Fc as ZQ,Gc as WQ,Hc as KQ,Ic as GQ,Jc as YQ,Kc as VQ,Lc as zQ,Mc as DQ,Nc as HQ,Oc as PQ,Qc as q$,Rc as g9,Sc as u9,Tc as c9,Uc as m9,Vc as p9,Wc as l9,Xc as i9,Yc as d9,Zc as n9,_c as o9,ad as GJ,bd as a9,cd as lZ,dd as t9,ed as iZ,fd as r9,gd as e9,hd as J6,ic as I$,id as SJ,jc as bZ,jd as eJ,kc as yZ,kd as $6,lc as w$,ld as Q6,md as dZ,nd as Z6,od as W6,pc as xQ,pd as K6,qc as AQ,qd as X6,rc as ZJ,rd as G6,sc as h9,sd as tJ,tc as f,uc as a$,vc as t$,xc as r$,yc as y,zc as YZ}from"../chunk-v1d7xya8.js";import{Fd as g,Gd as f$,Jd as vZ,Kd as hZ,Ld as gZ,Md as wJ,Nd as uZ,Od as yJ,Pd as cZ,Qd as mZ,Rd as vJ,Sd as pZ,Xd as G$,Yd as o,wd as hQ,xd as A,yd as k}from"../chunk-e0scxs81.js";import{ne as l$}from"../chunk-9m6mkaqb.js";import"../chunk-vebstesm.js";import{Aj as C$,Bj as IZ,Dj as wZ,Ej as fZ,Fj as qZ,Oi as j,mi as kZ,pi as jZ,vj as xZ}from"../chunk-7wzhdq1x.js";import{Gj as TZ,Ij as qJ,Jj as bJ}from"../chunk-aed0vv5g.js";import{Sj as h}from"../chunk-jy26hy7z.js";import{Uj as b9,Vj as y9,Wj as v9}from"../chunk-8ar7180x.js";import"../chunk-wdrmzjtq.js";import"../chunk-06w8hhnk.js";import"../chunk-24tj4dzx.js";import{Zk as d,_k as n,ml as _J}from"../chunk-xgc5tj8k.js";import"../chunk-etcds9w3.js";import"../chunk-65btke6p.js";import{dm as rQ}from"../chunk-vyaedzr8.js";import"../chunk-djnn8vvp.js";import"../chunk-0eq7am78.js";import{Am as cJ}from"../chunk-77dt2tap.js";import"../chunk-zf1eqgzt.js";import{existsSync as J8,readdirSync as U6,readFileSync as c$}from"fs";import{isAbsolute as $8,join as FJ,relative as Q8,sep as Z8}from"path";var m$="prompts.json",W8=/\{\{>\s*([\w./-]+)\s*\}\}/g,h$=/\{\{(\w+)\}\}/g,K8=/^[\w-]+(\/[\w-]+)*$/,g$={dir:"app/agents",shared:"prompts"},OJ={},gJ=new Map,NJ;function X8(){if(NJ===void 0){let J=FJ(cJ(),"dist","server",m$);NJ=J8(J)?JSON.parse(c$(J,"utf8")):null}return NJ??null}function G8(J){return J.replace(/\r?\n$/,"")}function u$(){return OJ.cache??Bun.env.NODE_ENV==="production"}function Y8(J,$){if(!K8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??OJ.dir??g$.dir,Z=$8(Q)?Q:FJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:FJ($.shared??OJ.shared??g$.shared,`${J}.md`);return FJ(Z,W)}function V8(J,$){let Q=Y8(J,$),Z=u$()?gJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=X8()?.[Q8(cJ(),Q).split(Z8).join("/")];if(X!==void 0)return X}let K;try{K=G8(c$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${m$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(u$())gJ.set(Q,K);return K}function uJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return V8(J,Q).replace(W8,(Z,W)=>uJ(W,[...$,J],Q))}class p${static configure(J){OJ={...J},gJ.clear(),NJ=void 0}static render(J,$={},Q={}){return uJ(J,[],Q).replace(h$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...uJ(J,[],$).matchAll(h$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class mJ extends l${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await y.sweep({limit:100})===100);}}var UJ=20,z8=300,D8=200;function d$(J,$){if($<=0||J.length===0)return null;let Q=(K,X)=>X.createdAt-K.createdAt||(K.id<X.id?1:-1);return["<jobs>","Background jobs that tools started in this conversation, running ones first. A running job's result replaces its tool result when it finishes. Do not start the same work again while a job for it is running.",...[...J.filter((K)=>!f(K.state)).sort(Q),...J.filter((K)=>f(K.state)).sort(Q)].slice(0,$).map((K)=>{let X=[`- ${K.id} (${K.toolName})`];if(K.state==="waiting")X.push(`waiting for ${(K.after??[]).join(", ")} since ${CJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${CJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${CJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${i$(K.error.message,D8)}`:"failed";X.push(`failed at ${CJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${i$(JSON.stringify(K.summary),z8)}`);if(K.orphaned)X.push("its tool call was lost when the turn that started it was cut short");return X.join("; ")}),"</jobs>"].join(`
|
|
3
3
|
`)}function CJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function i$(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var n$=["after_jobs","batch_key","queued","inbox","job_checkpoint"],o$=20;class pJ{table;sql;dialect;connection;later;constructor(J,$={}){let Q=$.table??"gemi_agent_jobs";if(!/^[A-Za-z_][A-Za-z0-9_]*$/.test(Q))throw Error(`The agent jobs table name "${Q}" is not a plain identifier. Use letters, digits and underscores.`);this.table=Q,this.sql=J.sql,this.dialect=J.dialect,this.connection=J.name}async createTable(){for(let J of H8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return _J(this.sql,()=>J(),{connection:this.connection})}async create(J){let $=J.after!==void 0||J.batch!==void 0||J.queued!==void 0;if($)await this.requireLaterColumns("A job with `after` or `batch`");let Q=this.q(),Z=this.clock(Q),W=J.state??"running";if($)await Q`
|
|
4
4
|
INSERT INTO ${this.name(Q)}
|
|
5
5
|
(id, thread_id, run_id, tool_call_id, tool_name, owner, job, summary, state,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"call.d.ts","sourceRoot":"","sources":["../../../ai/providers/call.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AASlD,OAAO,EAIL,KAAK,QAAQ,EACd,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,cAAc,EACpB,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;
|
|
1
|
+
{"version":3,"file":"call.d.ts","sourceRoot":"","sources":["../../../ai/providers/call.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,aAAa,EAAE,MAAM,kBAAkB,CAAC;AACtD,OAAO,KAAK,EAAE,cAAc,EAAE,MAAM,aAAa,CAAC;AASlD,OAAO,EAIL,KAAK,QAAQ,EACd,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,cAAc,EACpB,MAAM,QAAQ,CAAC;AAChB,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAIlD;;;;;;;;GAQG;AACH,MAAM,MAAM,iBAAiB,GAAG;IAC9B,YAAY,EAAE,MAAM,CAAC;IACrB,QAAQ,EAAE,MAAM,CAAC;IACjB;2DACuD;IACvD,OAAO,EAAE,MAAM,OAAO,CAAC,MAAM,CAAC,MAAM,EAAE,MAAM,CAAC,CAAC,CAAC;IAC/C,SAAS,EAAE,MAAM,CAAC;IAClB,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,sEAAsE;IACtE,mBAAmB,CAAC,EAAE,MAAM,CAAC;IAC7B,uEAAuE;IACvE,oBAAoB,CAAC,EAAE,MAAM,CAAC;IAC9B,UAAU,EAAE,MAAM,CAAC;IACnB,SAAS,CAAC,EAAE,SAAS,CAAC;IACtB;wDACoD;IACpD,KAAK,CAAC,EAAE,cAAc,CAAC,OAAO,CAAC,CAAC;IAChC,MAAM,CAAC,EAAE,MAAM,MAAM,CAAC;IACtB,GAAG,CAAC,EAAE,MAAM,MAAM,CAAC;CACpB,CAAC;AAEF;;;;;;;;;GASG;AACH,wBAAgB,iBAAiB,CAAC,MAAM,EAAE,cAAc,GAAG,iBAAiB,CAW3E;AAED;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA4CG;AACH,wBAAuB,eAAe,CAAC,IAAI,SAAS,MAAM,GAAG,gBAAgB,EAC3E,QAAQ,EAAE,iBAAiB,EAC3B,IAAI,EAAE,IAAI,EACV,MAAM,EAAE;IACN,MAAM,CAAC,EAAE,WAAW,CAAC;IACrB,gBAAgB,EAAE,OAAO,CAAC;IAC1B;;2EAEuE;IACvE,KAAK,CAAC,EAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CAAC;IAC9B;;;;OAIG;IACH,KAAK,CAAC,EAAE,CACN,MAAM,EAAE,aAAa,CAAC,MAAM,CAAC,EAC7B,OAAO,EAAE;QAAE,gBAAgB,EAAE,OAAO,CAAA;KAAE,KACnC,aAAa,CAAC,aAAa,CAAC,CAAC;CACnC,GACA,cAAc,CAAC,aAAa,CAAC,CA0N/B;AAED;;;;;;;;;;;;;;;;;GAiBG;AACH,MAAM,MAAM,aAAa,GAAG,WAAW,GAAG,YAAY,CAAC;AAEvD;;;;;GAKG;AACH,wBAAsB,UAAU,CAC9B,QAAQ,EAAE,iBAAiB,EAC3B,IAAI,EAAE,IAAI;AACV,gEAAgE;AAChE,OAAO,GAAE,aAAa,GAAG,IAAkB,GAC1C,OAAO,CAAC,MAAM,CAAC,CAyBjB"}
|
|
@@ -81,4 +81,8 @@ export declare function withoutFiles(body: ResponsesRequest, fileIds: Set<string
|
|
|
81
81
|
* and can hold anything.
|
|
82
82
|
*/
|
|
83
83
|
export declare function unreadableNote(name: string | undefined): string;
|
|
84
|
+
export declare function errorDetail(body: unknown): {
|
|
85
|
+
message?: string;
|
|
86
|
+
param?: string;
|
|
87
|
+
} | null;
|
|
84
88
|
//# sourceMappingURL=fileRejection.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"fileRejection.d.ts","sourceRoot":"","sources":["../../../ai/providers/fileRejection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,8EAA8E;AAC9E,MAAM,MAAM,QAAQ,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5D;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C,wEAAwE;AACxE,wBAAgB,SAAS,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CASzE;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE,OAAO,EACd,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAa,GACvC,MAAM,EAAE,CA4CV;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,gBAAgB,EACtB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EACpB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAa,GACvC,gBAAgB,CAgBlB;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAG/D"}
|
|
1
|
+
{"version":3,"file":"fileRejection.d.ts","sourceRoot":"","sources":["../../../ai/providers/fileRejection.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,UAAU,CAAC;AAE7C,OAAO,KAAK,EAAsB,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAEtE;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GAyCG;AAEH,8EAA8E;AAC9E,MAAM,MAAM,QAAQ,GAAG;IAAE,IAAI,CAAC,EAAE,MAAM,CAAC;IAAC,QAAQ,CAAC,EAAE,MAAM,CAAA;CAAE,CAAC;AAE5D;;;;;;GAMG;AACH,eAAO,MAAM,0BAA0B,IAAI,CAAC;AAE5C,wEAAwE;AACxE,wBAAgB,SAAS,CAAC,QAAQ,EAAE,YAAY,EAAE,GAAG,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAC,CASzE;AAED;;;;;GAKG;AACH,wBAAgB,eAAe,CAC7B,IAAI,EAAE,gBAAgB,EACtB,KAAK,EAAE,OAAO,EACd,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAa,GACvC,MAAM,EAAE,CA4CV;AAED;;;;;GAKG;AACH,wBAAgB,YAAY,CAC1B,IAAI,EAAE,gBAAgB,EACtB,OAAO,EAAE,GAAG,CAAC,MAAM,CAAC,EACpB,KAAK,GAAE,GAAG,CAAC,MAAM,EAAE,QAAQ,CAAa,GACvC,gBAAgB,CAgBlB;AAED;;;;;;;;GAQG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,MAAM,GAAG,SAAS,GAAG,MAAM,CAG/D;AAuBD,wBAAgB,WAAW,CAAC,IAAI,EAAE,OAAO,GAAG;IAAE,OAAO,CAAC,EAAE,MAAM,CAAC;IAAC,KAAK,CAAC,EAAE,MAAM,CAAA;CAAE,GAAG,IAAI,CAWtF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../../ai/providers/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,gBAAgB,EACjB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAoB,MAAM,UAAU,CAAC;AAEzF;;;;;;;GAOG;AAKH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACzD,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEpD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,kBAAkB,EAAE,CAAC;IAC5B,MAAM,EAAE,IAAI,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,aAAa,EAAE,CAAC;IACxB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,WAAW,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1D,IAAI,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IAC3C,SAAS,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACjD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,oBAAoB,EAC5B,GAAG,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,oBAAoB,CAAA;CAAE,GACzD,gBAAgB,CA8DlB;AAID;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,YAAY,EAAE,EACxB,YAAY,EAAE,oBAAoB,EAClC,KAAK,CAAC,EAAE,CAAC,gBAAgB,GAAG,qBAAqB,CAAC,EAAE,GACnD,kBAAkB,EAAE,
|
|
1
|
+
{"version":3,"file":"request.d.ts","sourceRoot":"","sources":["../../../ai/providers/request.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EACV,oBAAoB,EACpB,oBAAoB,EACpB,qBAAqB,EACrB,gBAAgB,EACjB,MAAM,kBAAkB,CAAC;AAG1B,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAoB,MAAM,UAAU,CAAC;AAEzF;;;;;;;GAOG;AAKH,MAAM,MAAM,kBAAkB,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AACzD,MAAM,MAAM,aAAa,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;AAEpD,MAAM,MAAM,gBAAgB,GAAG;IAC7B,KAAK,EAAE,MAAM,CAAC;IACd,KAAK,EAAE,kBAAkB,EAAE,CAAC;IAC5B,MAAM,EAAE,IAAI,CAAC;IACb,YAAY,CAAC,EAAE,MAAM,CAAC;IACtB,KAAK,CAAC,EAAE,aAAa,EAAE,CAAC;IACxB,mBAAmB,CAAC,EAAE,OAAO,CAAC;IAC9B,WAAW,CAAC,EAAE,MAAM,GAAG;QAAE,IAAI,EAAE,UAAU,CAAC;QAAC,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IAC1D,IAAI,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAA;KAAE,CAAC;IAC3C,SAAS,CAAC,EAAE;QAAE,MAAM,EAAE,MAAM,CAAC;QAAC,OAAO,CAAC,EAAE,MAAM,CAAA;KAAE,CAAC;IACjD,WAAW,CAAC,EAAE,MAAM,CAAC;IACrB,iBAAiB,CAAC,EAAE,MAAM,CAAC;IAC3B,gBAAgB,CAAC,EAAE,MAAM,CAAC;CAC3B,CAAC;AAEF,wBAAgB,qBAAqB,CACnC,MAAM,EAAE,oBAAoB,EAC5B,GAAG,EAAE;IAAE,KAAK,EAAE,MAAM,CAAC;IAAC,YAAY,EAAE,oBAAoB,CAAA;CAAE,GACzD,gBAAgB,CA8DlB;AAID;;;;;;;;;GASG;AACH,wBAAgB,gBAAgB,CAC9B,QAAQ,EAAE,YAAY,EAAE,EACxB,YAAY,EAAE,oBAAoB,EAClC,KAAK,CAAC,EAAE,CAAC,gBAAgB,GAAG,qBAAqB,CAAC,EAAE,GACnD,kBAAkB,EAAE,CAsItB;AAsED;;;;;;;;;GASG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,QAAQ,GAAG,MAAM,GAAG,SAAS,CAGjE;AAED;;;;;;;;;;;;;;;;;;;;;;GAsBG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,KAAK,EAAE,OAAO,GAAG,MAAM,CAQrE;AAiED,sEAAsE;AACtE,wBAAgB,WAAW,CAAC,IAAI,EAAE,QAAQ,GAAG,OAAO,CASnD;AAED;;;GAGG;AACH,wBAAgB,cAAc,CAAC,IAAI,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,GAAG,SAAS,GAAG,IAAI,CAiBrF;AAuGD;;;;;;;;;;;;;;;;;;;;;;;;;;;;;GA6BG;AACH,wBAAgB,gBAAgB,CAAC,IAAI,EAAE,cAAc,GAAG,MAAM,CAoC7D;AAuFD;;;;;;;;GAQG;AACH,wBAAgB,gBAAgB,CAC9B,KAAK,EAAE,CAAC,gBAAgB,GAAG,qBAAqB,CAAC,EAAE,GAAG,SAAS,EAC/D,YAAY,EAAE,oBAAoB,GACjC,aAAa,EAAE,CA2CjB"}
|
|
@@ -0,0 +1,25 @@
|
|
|
1
|
+
import type { ResponsesRequest } from "./request";
|
|
2
|
+
/**
|
|
3
|
+
* A replayed reasoning item the API no longer has, and the one retry it gets.
|
|
4
|
+
*
|
|
5
|
+
* Reasoning goes back to the Responses API by id (`request.ts`,
|
|
6
|
+
* `reasoningItem`), and the API looks the id up in what it stored. When the
|
|
7
|
+
* lookup fails the whole request is refused, `400 Item with id 'rs_…' not
|
|
8
|
+
* found.`, and because the id lives in the thread, so is every later turn.
|
|
9
|
+
* `toResponsesInput` already leaves out the reasoning of a message whose
|
|
10
|
+
* response never completed, which is the case seen in practice; this is the
|
|
11
|
+
* net under everything that rule does not know about (an item the vendor
|
|
12
|
+
* expired, a thread moved to another resource or deployment).
|
|
13
|
+
*
|
|
14
|
+
* The request is sent again once, with every reasoning item taken out rather
|
|
15
|
+
* than only the one named: Azure names a single id per refusal, and a thread
|
|
16
|
+
* with two stale items would otherwise spend its retry on the first and fail
|
|
17
|
+
* on the second. Reasoning is continuity and a cache hit, never content the
|
|
18
|
+
* answer depends on, and `request.ts` already sends a history without it
|
|
19
|
+
* whenever a part has no id, so the retried request is one the API accepts.
|
|
20
|
+
*
|
|
21
|
+
* Only for a refusal that names a reasoning item this request actually sent:
|
|
22
|
+
* any other 400 fails the call as before.
|
|
23
|
+
*/
|
|
24
|
+
export declare function withoutStaleReasoning(body: unknown, error: unknown): ResponsesRequest | null;
|
|
25
|
+
//# sourceMappingURL=staleReasoning.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"staleReasoning.d.ts","sourceRoot":"","sources":["../../../ai/providers/staleReasoning.ts"],"names":[],"mappings":"AAEA,OAAO,KAAK,EAAE,gBAAgB,EAAE,MAAM,WAAW,CAAC;AAElD;;;;;;;;;;;;;;;;;;;;;GAqBG;AACH,wBAAgB,qBAAqB,CAAC,IAAI,EAAE,OAAO,EAAE,KAAK,EAAE,OAAO,GAAG,gBAAgB,GAAG,IAAI,CAc5F"}
|
package/dist/ai/testing/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{la as g}from"../../chunk-
|
|
2
|
+
import{la as g}from"../../chunk-2e40rx0p.js";import"../../chunk-e0scxs81.js";import{Uj as v,Vj as m}from"../../chunk-8ar7180x.js";import"../../chunk-zf1eqgzt.js";import{createHash as s}from"crypto";import{createHash as S}from"crypto";import{existsSync as h,readdirSync as l,readFileSync as c,statSync as d}from"fs";import{join as q,relative as p,sep as i}from"path";var P="\u241F",F=6,n=/\{\{>\s*([^}\s]+)\s*\}\}/g,b=(D)=>D.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");function R(D){let $=D.filter((B)=>B.length>=F),z=D.filter((B)=>B.length<F);return(B)=>{let C=B;for(let G of $)if(C.includes(G))C=C.split(G).join(P);for(let G of z)C=C.replace(new RegExp(`${b(G)}\\s*${P}`,"g"),P).replace(new RegExp(`${P}\\s*${b(G)}`,"g"),P);return C.replace(new RegExp(`\\s*${P}[\\s${P}]*`,"g"),P)}}function y(D,$=[]){for(let z of l(D)){if(z==="node_modules")continue;let B=q(D,z);if(d(B).isDirectory())y(B,$);else if(z.endsWith(".md"))$.push(B)}return $}class L{data;root;options;constructor(D,$={}){this.data=D;this.options=$,this.root=$.root??process.cwd()}static blob(D){return S("sha1").update(`blob ${Buffer.byteLength(D)}\x00`).update(D).digest("hex")}static pieces(D){return D.split(/\{\{[^}]*\}\}/).map(($)=>$.trim()).filter(($)=>$.length>0)}static tool(D){return S("sha256").update(JSON.stringify({description:D.description,parameters:D.parameters})).digest("hex")}static prompts(D={}){let $=D.root??process.cwd(),z=new Map;for(let B of D.dirs??["app/agents"]){if(!h(q($,B)))continue;for(let C of y(q($,B)).sort())z.set(p($,C).split(i).join("/"),c(C,"utf8"))}return z}static of(D,$,z={}){let B=[...D].join(`
|
|
3
3
|
\x00
|
|
4
4
|
`),C={};for(let[Y,Q]of L.prompts(z))if(L.pieces(Q).filter((Z)=>Z.length>=12).sort((Z,K)=>K.length-Z.length).slice(0,3).some((Z)=>B.includes(Z)))C[Y]=L.blob(Q);let G=[...$.keys()].sort(),X=z.inputs?.(new Set(G));return new L({prompts:C,tools:Object.fromEntries(G.map((Y)=>[Y,[...$.get(Y)].sort()])),...X&&Object.keys(X).length>0?{inputs:a(X)}:{}},z)}same(D){let $=D instanceof L?D.data:D;return JSON.stringify(this.data)===JSON.stringify($)}changed(){let D=this.options.inputs?.(new Set(Object.keys(this.data.tools)))??{};return[...this.changedPrompts().map(([$])=>$),...Object.entries(this.data.inputs??{}).filter(([$,z])=>D[$]!==z).map(([$])=>`input ${$}`)]}cutters(){let D=L.prompts(this.options),$=this.changedPrompts(),z=new Map,B=new Map;for(let[C,G]of $){let X=this.readBlob(G);if(X===void 0)throw Error(`${C} changed since the recording, and the version it was recorded with (${G}) can't be read back from git`);if(z.set(C,X),D.has(C))B.set(C,D.get(C))}return{changed:$.map(([C])=>C),recorded:R(this.piecesWithPartials(z,(C)=>{let G=this.data.prompts[C];return G&&this.readBlob(G)||D.get(C)})),sent:R(this.piecesWithPartials(B,(C)=>D.get(C)))}}changedPrompts(){let D=L.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let B=D.get($);return B===void 0||L.blob(B)!==z})}readBlob(D){if(this.options.readBlob)return this.options.readBlob(D);let $=Bun.spawnSync(["git","cat-file","blob",D],{cwd:this.root});return $.exitCode===0?$.stdout.toString():void 0}piecesWithPartials(D,$){let z=this.options.dirs??["app/agents"],B=this.options.shared??"prompts",C=[...D];while(C.length>0){let[G,X]=C.pop(),Y=z.find((Q)=>G.startsWith(`${Q}/`));if(Y===void 0)continue;for(let[,Q]of X.matchAll(n)){let V=`${Y}/${Q.includes("/")?Q:`${B}/${Q}`}.md`,Z=D.has(V)?void 0:$(V);if(Z===void 0)continue;D.set(V,Z),C.push([V,Z])}}return[...D.values()].flatMap((G)=>L.pieces(G)).sort((G,X)=>X.length-G.length)}}function a(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class N extends Error{constructor(D){super(`${D} Record again.`);this.name="RecordingMismatchError"}}var o=/[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}/g;function T(D,$){if(typeof D==="string")return $(D);if(Array.isArray(D))return D.map((z)=>T(z,$));if(D&&typeof D==="object")return Object.fromEntries(Object.entries(D).map(([z,B])=>[z,T(B,$)]));return D}function f(D){return JSON.parse(JSON.stringify(D,function($,z){if($==="nested")return;if($==="output"&&this.type==="tool-result"&&"modelOutput"in this)return;return z}))}function u(){let D;return{promise:new Promise((z)=>D=z),resolve:D}}var r=(D)=>s("sha256").update(D).digest("hex"),E=(D)=>D.flatMap(($)=>("tools"in $)?$.tools:[$]);function x(D){return D.map(({role:$,content:z})=>({role:$,parts:(Array.isArray(z)?z:[]).flatMap((B)=>{if(B?.type==="tool-call")return[{call:B.name,input:B.input??B.args}];if(B?.type==="tool-result")return[{result:B.name,status:B.status}];if(B?.type==="file")return[{file:!0}];return[]})}))}class M extends g{live;model;capabilities;recordedAt;calls;recordedNested;children=new Map;parent;key;sent=[];uploads;uploadCount=0;read;shared;options;texts=new Set;toolHashes=new Map;toolLists=new Set;recorded;cuts;constructor(D,$,z,B){super();this.live=D;if(this.options={...z,match:z.match??"wording",ids:new RegExp(z.ids??o,"g"),waitMs:z.waitMs??60000},B){let{parent:C}=B;this.parent=C,this.key=B.key,this.model=C.model,this.capabilities=C.capabilities,this.recordedAt=C.recordedAt,this.calls=B.calls,this.recordedNested={},this.uploads=C.uploads,this.shared=C.shared;return}if(this.shared={ids:new Map,stale:new Set,staleCalls:0,started:0,moved:u()},this.uploads=new Map,D){this.model=D.model,this.capabilities=D.capabilities,this.recordedAt=new Date,this.calls=[],this.recordedNested={};return}if(!$||$.version!==1||!Array.isArray($.calls))throw Error("RecordingProvider.replay needs a recording made by RecordingProvider.");if(this.model=$.model,this.capabilities=$.capabilities,this.recordedAt=new Date($.recordedAt),this.calls=structuredClone($.calls),this.recordedNested=structuredClone($.nested??{}),$.fingerprints)this.recorded=new L($.fingerprints,z.fingerprints)}static record(D,$={}){return new M(D,void 0,$)}static replay(D,$={}){return new M(void 0,D,$)}get isRecording(){return this.live!==void 0}get stale(){return this.shared.stale}get staleCalls(){return this.shared.staleCalls}nested(D){if(this.parent)return this.parent.nested(D);let $=this.children.get(D);if(!$){let z=this.recordedNested[D];if(!this.live&&!z)throw new N(`The recording has no sub-run "${D}".`);$=new M(this.live,void 0,this.options,{parent:this,key:D,calls:z??[]}),this.children.set(D,$)}return $}recording(){if(this.parent)return this.parent.recording();if(!this.live)throw Error("Only a recording provider (`record`) has a recording to save.");return{version:1,model:this.model,capabilities:this.capabilities,recordedAt:this.recordedAt.toISOString(),calls:structuredClone(this.calls),...this.options.fingerprints?{fingerprints:this.fingerprints().data}:{},...this.children.size>0?{nested:Object.fromEntries([...this.children].map(([D,$])=>[D,structuredClone($.calls)]))}:{}}}fingerprints(){let D=this.parent??this;return L.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new L(D.fingerprints,$).changed():[]}replayedInFull(){let D=this.parent??this;return D.calls.length===0&&Object.entries(D.recordedNested).every(([$,z])=>(D.children.get($)?.calls??z).length===0)}async pin(D){if(this.live)return this.read=D,D;let $=this.calls[0]?.read;if($===void 0)return D;return await(this.parent??this).reach($,this.where()),$}async upload(D){let $=++this.uploadCount,z=this.key===void 0?`upload_${$}`:`upload_${this.key}_${$}`;if(this.live)this.uploads.set(z,await this.live.upload(D));return z}normalizeError(D){return this.live?this.live.normalizeError(D):super.normalizeError(D)}async*stream(D){let $=this.requestOf(D);if(this.live){yield*this.recordCall(D,$);return}yield*this.replayCall(D,$)}async*recordCall(D,$){let z=this.parent??this,B=z.shared.started++,C=this.read;this.read=void 0;let G=[],X=D.messages.map((Q)=>({...Q,content:Q.content.map((V)=>V.type==="file"&&V.fileId&&this.uploads.has(V.fileId)?{...V,fileId:this.uploads.get(V.fileId)}:V)}));for await(let Q of this.live.stream({...D,messages:X})){let V=G.at(-1);if(Q.type==="tool-call-discard"){let Z=new Set(Q.toolCallIds),K=G.filter((H)=>H.type!=="tool-call-delta"||!Z.has(H.toolCallId));G.splice(0,G.length,...K)}else if(Q.type==="retry");else if(V&&(Q.type==="text-delta"||Q.type==="output-delta")&&V.type===Q.type)V.delta+=Q.delta;else if(V?.type==="tool-call-delta"&&Q.type==="tool-call-delta"&&V.toolCallId===Q.toolCallId)V.argsDelta+=Q.argsDelta;else G.push({...Q});yield Q}let Y=this.options.position?await this.options.position():void 0;this.calls.push({request:$,events:G,at:B,...C!==void 0?{read:C}:{},...Y!==void 0?{ended:Y}:{}})}async*replayCall(D,$){let z=this.parent??this,B=this.where(),C=this.calls[0];if(this.options.ordered&&C?.at!==void 0)await z.turn(C.at,B);let G=this.calls.shift();if(!G)throw new N(`${B}: call ${this.sentCalls} was not recorded (the recording has no more calls).`);let{promptCacheKey:X,...Y}=G.request;if(!z.matches(JSON.stringify(Y),$))z.tolerate(B,{...G,request:Y},$,D.tools??[]);if(G.ended!==void 0)await z.reach(G.ended,B);let Q=z.shared.ids;for(let V of G.events)yield JSON.parse(JSON.stringify(V).replace(this.options.ids,(Z)=>Q.get(Z)??Z))}where(){return this.key===void 0?"the recording":`sub-run "${this.key}"`}sentCalls=0;requestOf(D){this.sentCalls++;let{signal:$,promptCacheKey:z,messages:B,tools:C,...G}=D,X=B.map(({role:K,content:H})=>({role:K,content:f(H)})),Y=this.sent.length>0&&this.sent.length<=X.length&&JSON.stringify(X.slice(0,this.sent.length))===JSON.stringify(this.sent)?this.sent.length:0;this.sent=X;let Q=C&&C.length>0?JSON.stringify(C):void 0,V=this.parent??this,Z=(K)=>{return V.texts.add(K),K};if(T([G,X.slice(Y)],Z),Q&&!V.toolLists.has(Q)){V.toolLists.add(Q);for(let K of E(C)){T(K,Z);let H=V.toolHashes.get(K.name)??new Set;H.add(L.tool(K)),V.toolHashes.set(K.name,H)}}return{...f(G),...Q?{tools:`sha256:${r(Q)}`,toolNames:E(C).map((K)=>K.name).sort()}:{},...Y>0?{after:Y}:{},messages:X.slice(Y)}}matches(D,$){let z=this.options.ids,B=JSON.stringify($),C=D.match(z)??[],G=B.match(z)??[];if(C.length!==G.length)return!1;let X=new Map(this.shared.ids);for(let[Y,Q]of C.entries()){let V=X.get(Q)??G[Y];if(V!==G[Y])return!1;X.set(Q,V)}if(D.replace(z,(Y)=>X.get(Y))!==B)return!1;for(let[Y,Q]of X)this.shared.ids.set(Y,Q);return!0}tolerate(D,$,z,B){let C=this.options.ids,G=this.options.match,X=$.request,Y=(j,J,I)=>{let A=JSON.stringify(j).replace(C,"<id>"),W=JSON.stringify(J).replace(C,"<id>"),_=0;while(_<A.length&&A[_]===W[_])_++;throw new N(`${D}: the request differs from the recorded one${I}. Recorded: \u2026${A.slice(Math.max(0,_-80),_+120)}\u2026 Sent: \u2026${W.slice(Math.max(0,_-80),_+120)}\u2026`)};if(G==="exact")Y(X,z,"");let{tools:Q,toolNames:V,...Z}=X,{tools:K,toolNames:H,...k}=z,w=[];if(!this.matches(JSON.stringify(Z),k))if(G==="wording"){if(!this.recorded)Y(Z,k,", and the recording has no fingerprints to tell a reworded prompt by");try{this.cuts??=this.recorded.cutters()}catch(I){throw new N(`${D}: ${I.message}.`)}let j=T(Z,this.cuts.recorded),J=T(k,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(j),J))Y(j,J,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");w.push(...this.cuts.changed.map((I)=>`${I} changed`))}else{if(!((X.after??0)===(z.after??0)&&this.matches(JSON.stringify(x(X.messages)),x(z.messages))))Y(Z,k," in the conversation itself");let{messages:J,...I}=Z,{messages:A,...W}=k;if(!this.matches(JSON.stringify(J),A))w.push("message text changed");let _=new Set([...Object.keys(I),...Object.keys(W)]);for(let U of[..._].sort()){let O=JSON.stringify(I[U]??null);if(!this.matches(O,W[U]??null))w.push(`${U} changed`)}}if(Q!==K){let j=E(B);for(let J of $.events){if(J.type!=="tool-call")continue;let I=j.find((O)=>O.name===J.name);if(!I)throw new N(`${D}: the recorded answer calls ${J.name}, which is not offered any more.`);let A=Object.fromEntries([...JSON.stringify(I.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,O])=>[O,!0])),W;try{W=JSON.parse(J.args||"{}")}catch{W=void 0}let _;try{_=m.fromJSONSchema(I.parameters,{unknownKeys:"error",formats:A})}catch(O){if(!(O instanceof v))throw O}let U=_?.safeParse(W);if(U&&U.ok===!1)throw new N(`${D}: the recorded call of ${J.name} does not fit its schema any more (${U.errors.join("; ")}).`)}if(this.recorded){let J=j.filter((I)=>!this.recorded.data.tools[I.name]?.includes(L.tool(I))).map((I)=>I.name).sort();w.push(J.length>0?`tools changed: ${J.join(", ")}`:"the tools offered changed")}else{let J=new Set(V??[]),I=new Set(H??[]),A=[...I].filter((_)=>!J.has(_)),W=[...J].filter((_)=>!I.has(_));w.push(A.length>0||W.length>0?`tools offered changed (${[...A.map((_)=>`+${_}`),...W.map((_)=>`-${_}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let j of w)this.shared.stale.add(j)}async turn(D,$){let z=this.shared;z.pending??=[...this.calls,...Object.values(this.recordedNested).flat()].map((B)=>B.at).filter((B)=>B!==void 0).sort((B,C)=>B-C);while(z.pending[0]!==void 0&&z.pending[0]<D){let B=z.moved.promise;if(!await Promise.race([B.then(()=>!0),new Promise((G)=>setTimeout(()=>G(!1),this.options.waitMs))]))throw new N(`${$}: call ${D} waits for call ${z.pending[0]}, which the replay does not make.`)}z.pending=z.pending.filter((B)=>B!==D),z.moved.resolve(),z.moved=u()}async reach(D,$){let z=this.options.position;if(!z)return;let B=await z(),C=0;while(B<D){await new Promise((X)=>setTimeout(X,25));let G=await z();if(C=G===B?C+25:0,B=G,C>=this.options.waitMs)throw new N(`${$}: a call waits for the app to reach ${D}; it stays at ${B}.`)}}}function t(D){let $=globalThis.Date,z=new $(D).getTime()-$.now();if(!Number.isFinite(z))throw Error(`pinClock: ${String(D)} is not a date.`);class B extends ${constructor(...C){if(C.length===0)super($.now()+z);else super(...C)}static now(){return $.now()+z}}return globalThis.Date=B,()=>{if(globalThis.Date===B)globalThis.Date=$}}export{t as pinClock,M as RecordingProvider,N as RecordingMismatchError,L as Fingerprints};
|
|
5
5
|
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
// @bun
|
|
2
|
+
import{Md as jQ,Sd as O,Td as l,Ud as dQ,Vd as lQ,Wd as iQ,Xd as I,Yd as M,wd as a,yd as r}from"./chunk-e0scxs81.js";import{Tj as wQ}from"./chunk-8ar7180x.js";var z5=500,SQ=20000;function L5(Q,$){if(!Q)return;let J=Q.trim();if(/^\d+(\.\d+)?$/.test(J))return Math.max(0,Number(J)*1000);let Z=Date.parse(J);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function d(Q,$){let J=Math.min(SQ,z5*2**Q);return Math.round(J*(0.5+$()*0.5))}function q5(Q){return Q===429||Q===408||Q===409||Q>=500}function D5(Q,$){return q5(Q)&&M($).retryable}function RQ(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function AQ(Q,$){return new Promise((J,Z)=>{let X=setTimeout(J,Q);$?.addEventListener("abort",()=>{clearTimeout(X),Z(RQ($))},{once:!0})})}async function JQ(Q,$,J=AQ){if(!$)return await J(Q);$.throwIfAborted();let Z;try{await Promise.race([J(Q,$),new Promise((X,Y)=>{Z=()=>Y(RQ($)),$.addEventListener("abort",Z,{once:!0})})])}finally{if(Z)$.removeEventListener("abort",Z)}}async function y(Q,$,J){let Z=J.fetchImpl??((V,W)=>fetch(V,W)),X=J.sleep??AQ,Y=J.random??Math.random,G=J.now??Date.now,F=Math.max(0,J.maxRetries),j=J.startedAt??G(),K=(V,W,H,U)=>{try{J.onRetry?.({attempt:W+1,maxRetries:F,error:M(H),...I(H),timedOut:U,delayMs:V,elapsedMs:G()-j})}catch{}return JQ(V,J.signal,X)},B;for(let V=0;V<=F;V++){J.signal?.throwIfAborted();let W=new AbortController,H=()=>W.abort(J.signal?.reason);J.signal?.addEventListener("abort",H,{once:!0});let U=!1,L=J.timeoutMs>0?setTimeout(()=>{U=!0,W.abort()},J.timeoutMs):void 0,P;try{P=await Z(Q,{...$,signal:W.signal})}catch(u){if(L!==void 0)clearTimeout(L);if(J.signal?.removeEventListener("abort",H),J.signal?.aborted)throw u;if(B=U?new l(J.timeoutMs):u,U&&J.retryTimeouts===!1)throw B;if(V===F)throw B;await K(d(V,Y),V,B,U);continue}if(L!==void 0)clearTimeout(L);if(P.ok)return P;J.signal?.removeEventListener("abort",H);let g=await C5(P),D=new O(P.status,g,P.headers.get("x-request-id")??P.headers.get("request-id")??void 0,L5(P.headers.get("retry-after"),G()));if(V===F||!D5(P.status,D))throw D;let _=D.retryAfter??(P.status===429?M(D).retryAfter:void 0);await K(_===void 0?d(V,Y):Math.min(_,SQ),V,D,!1),B=D}throw B??Error("Provider request failed with no response.")}async function C5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}function IQ(Q,$,J){let Z=$.idleMs>0?$.idleMs:0,X=$.maxMs>0?$.maxMs:0;if(!Q||!Z&&!X)return Q;let Y=X?performance.now()+X:1/0,G=Q.getReader();return new ReadableStream({async pull(F){let j,K,B=Math.max(0,Y-performance.now()),V=!Z||B<=Z,W=V?B:Z,H=new Promise((U,L)=>{j=setTimeout(()=>{K=V?J.max():J.idle(),L(K)},W)});try{let U=await Promise.race([G.read(),H]);if(U.done)F.close();else F.enqueue(U.value)}catch(U){let L=K??U;F.error(L),G.cancel(L).catch(()=>{})}finally{clearTimeout(j)}},cancel(F){return G.cancel(F)}},{highWaterMark:0})}var XQ=30000,TQ=10,EQ=7200,N5=600,P5="gpt-live-transcribe";function M5(Q){return Q.type==="transcription"}function x5(Q){if(Q.language!==void 0&&Q.languages!==void 0)throw TypeError("A transcription session takes `languages` or `language`, not both (gpt-live-transcribe reads `languages`).");for(let X of Q.keywords??[])if(/[<>\r\n]/.test(X))throw TypeError(`Transcription keywords must be one line without "<" or ">", got ${JSON.stringify(X)}.`);let $={model:Q.model??P5};if(Q.prompt!==void 0)$.prompt=Q.prompt;if(Q.keywords?.length)$.keywords=Q.keywords;if(Q.languages?.length)$.languages=Q.languages;if(Q.language!==void 0)$.language=Q.language;if(Q.delay!==void 0)$.delay=Q.delay;let J={transcription:$,turn_detection:Q.turnDetection?kQ(Q.turnDetection):null};if(Q.noiseReduction!==void 0)J.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Z={type:"transcription",audio:{input:J}};if(Q.logprobs)Z.include=["item.input_audio_transcription.logprobs"];return{...Z,...Q.vendor}}function _5(Q){if(!Q)return{type:"object",properties:{}};return wQ(Q)?Q.toJSONSchema():Q}function i(Q,$){if(M5(Q))return x5(Q);let J={type:"realtime"},Z=Q.model??$;if(Z)J.model=Z;if(Q.instructions!==void 0)J.instructions=Q.instructions;if(Q.outputModalities)J.output_modalities=Q.outputModalities;if(Q.maxOutputTokens!==void 0)J.max_output_tokens=Q.maxOutputTokens;if(Q.truncation!==void 0)J.truncation=Q.truncation;if(Q.tools)J.tools=Q.tools.map((G)=>({type:"function",name:G.name,...G.description?{description:G.description}:{},parameters:_5(G.parameters)}));if(Q.toolChoice!==void 0)J.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};let X={};if(Q.turnDetection!==void 0)X.turn_detection=Q.turnDetection&&kQ(Q.turnDetection);if(Q.transcription!==void 0)X.transcription=Q.transcription;if(Q.noiseReduction!==void 0)X.noise_reduction=Q.noiseReduction&&{type:Q.noiseReduction};let Y={};if(Q.voice!==void 0)Y.voice=Q.voice;if(Q.speed!==void 0)Y.speed=Q.speed;if(Object.keys(X).length||Object.keys(Y).length)J.audio={...Object.keys(X).length?{input:X}:{},...Object.keys(Y).length?{output:Y}:{}};return{...J,...Q.vendor}}function kQ(Q){let $={type:Q.type};if(Q.createResponse!==void 0)$.create_response=Q.createResponse;if(Q.interruptResponse!==void 0)$.interrupt_response=Q.interruptResponse;if(Q.type==="semantic_vad"){if(Q.eagerness!==void 0)$.eagerness=Q.eagerness}else{if(Q.threshold!==void 0)$.threshold=Q.threshold;if(Q.prefixPaddingMs!==void 0)$.prefix_padding_ms=Q.prefixPaddingMs;if(Q.silenceDurationMs!==void 0)$.silence_duration_ms=Q.silenceDurationMs;if(Q.idleTimeoutMs!==void 0)$.idle_timeout_ms=Q.idleTimeoutMs}return $}function YQ(Q){let $=Number(Q?.input_tokens??0),J=Number(Q?.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q?.total_tokens??$+J)},X=Q?.input_token_details??Q?.input_tokens_details,Y=Q?.output_token_details??Q?.output_tokens_details;if(typeof X?.cached_tokens==="number")Z.cachedInputTokens=X.cached_tokens;if(typeof X?.audio_tokens==="number")Z.audioInputTokens=X.audio_tokens;let G=X?.cached_tokens_details?.audio_tokens;if(typeof G==="number")Z.cachedAudioInputTokens=G;if(typeof X?.image_tokens==="number"&&X.image_tokens>0)Z.imageInputTokens=X.image_tokens;if(typeof Y?.audio_tokens==="number")Z.audioOutputTokens=Y.audio_tokens;return Z}class b extends Error{code;retryable;status;constructor(Q,$={}){super(Q.message,{cause:$.cause});if(this.name="RealtimeRequestError",this.code=Q.code,this.retryable=Q.retryable,$.status!==void 0)this.status=$.status}}var O5=60;class n{model;target;options;constructor(Q,$){this.target=Q,this.options=$,this.model=$.model}url(Q){return`${this.target.base}/realtime${Q}${this.target.query}`}sidebandUrl(Q){let $=this.target.base.replace(/^http(s?):/i,(Z,X)=>`ws${X}:`),J=this.target.query?`${this.target.query}&`:"?";return`${$}/realtime${J}call_id=${encodeURIComponent(Q)}`}async createCall(Q){let $=Q.flow??this.options.callFlow??"unified",J,Z;if($==="ephemeral")J={authorization:`Bearer ${(await this.clientSecret({session:Q.session,ttlSeconds:O5,signal:Q.signal})).value}`,"content-type":"application/sdp"},Z=Q.sdp;else{let j=new FormData;j.set("sdp",Q.sdp),j.set("session",JSON.stringify(i(Q.session??{},this.model))),J=await this.target.headers(),Z=j}if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=this.url("/calls"),Y=await this.request(Q.webrtcFilter?`${X}${X.includes("?")?"&":"?"}webrtcfilter=on`:X,{method:"POST",headers:J,body:Z},Q.signal),G=await Y.text(),F=R5(Y);if(!F)throw new b({code:"provider_error",message:"The provider started a realtime call but did not say which one (no Location).",retryable:!1});return{sdpAnswer:G,callId:F}}async clientSecret(Q={}){let $=Q.ttlSeconds??N5;if(!Number.isInteger($)||$<TQ||$>EQ)throw RangeError(`ttlSeconds must be a whole number from ${TQ} to ${EQ}, got ${$}.`);let J={...await this.target.headers(),"content-type":"application/json"};if(Q.safetyIdentifier)J["OpenAI-Safety-Identifier"]=Q.safetyIdentifier;let X=await(await this.request(this.url("/client_secrets"),{method:"POST",headers:J,body:JSON.stringify({expires_after:{anchor:"created_at",seconds:$},session:i(Q.session??{},this.model)})},Q.signal)).json();if(typeof X?.value!=="string")throw new b({code:"provider_error",message:"The provider answered a client secret request with no secret.",retryable:!1});return{value:X.value,expiresAt:Number(X.expires_at??0),session:X.session,callsUrl:this.url("/calls")}}async hangup(Q,$={}){try{await this.request(this.url(`/calls/${encodeURIComponent(Q)}/hangup`),{method:"POST",headers:await this.target.headers()},$.signal)}catch(J){if(S5(J,Q))return;throw J}}sideband(Q,$={}){return new ZQ({...$,callId:Q,url:this.sidebandUrl(Q),headers:this.target.headers,webSocket:$.webSocket??this.options.webSocket,hangup:()=>this.hangup(Q)})}async request(Q,$,J){try{return await y(Q,$,{maxRetries:this.target.maxRetries,timeoutMs:this.target.timeoutMs,retryTimeouts:!1,signal:J,fetchImpl:this.options.fetchImpl})}catch(Z){if(J?.aborted)throw Z;throw new b(M(Z),{cause:Z,...Z instanceof O?{status:Z.status}:{}})}}}function S5(Q,$){if(!(Q instanceof b)||Q.status!==404)return!1;let J=Q.cause instanceof O?Q.cause.body:void 0,Z=J?.error??J,X=String(Z?.code??"").toLowerCase(),Y=String(Z?.message??"").toLowerCase();if(X.includes("call"))return!0;if(Y.includes($.toLowerCase()))return!0;return/\bcall\b/.test(Y)&&/not (be )?found|does not exist|no longer|ended/.test(Y)}function R5(Q){let $=Q.headers.get("location");if(!$)return;let J=$.split("?")[0].replace(/\/+$/,""),Z=J.slice(J.lastIndexOf("/")+1);return Z?decodeURIComponent(Z):void 0}var A5={"response.audio_transcript.delta":"response.output_audio_transcript.delta","response.audio_transcript.done":"response.output_audio_transcript.done","response.text.delta":"response.output_text.delta","response.text.done":"response.output_text.done","response.audio.delta":"response.output_audio.delta","response.audio.done":"response.output_audio.done"};function I5(Q){if(typeof Q!=="string")return;let $;try{$=JSON.parse(Q)}catch{return}if(!$||typeof $!=="object"||typeof $.type!=="string")return;let J=A5[$.type];if(J)$.type=J;if($.type==="response.done"&&$.response?.usage)$.usage=YQ($.response.usage);if($.type==="conversation.item.input_audio_transcription.completed"&&$.usage)if($.usage.type==="duration"){let Z=Number($.usage.seconds);if(Number.isFinite(Z))$.transcriptionSeconds=Z}else $.transcriptionUsage=YQ($.usage);return $}var vQ=1,T5=500;function E5(Q,$){let J=globalThis.WebSocket;if(!J)throw Error("No global WebSocket: the realtime sideband needs Bun or Node 22+.");return new J(Q,{headers:$.headers})}class ZQ{callId;ready;closed;init;socket;finalEvent;outbox=[];subscribers=new Set;listeners=new Set;backlog=[];closing=!1;finished=!1;everOpened=!1;failures=0;resolveReady;rejectReady;resolveClosed;constructor(Q){this.init=Q,this.callId=Q.callId,this.ready=new Promise(($,J)=>{this.resolveReady=$,this.rejectReady=J}),this.ready.catch(()=>{}),this.closed=new Promise(($)=>this.resolveClosed=$),this.open()}send(Q){if(this.finished||this.closing)return;let $=JSON.stringify(Q);if(this.socket?.readyState===vQ)this.socket.send($);else this.outbox.push($)}updateSession(Q){this.send({type:"session.update",session:i(Q)})}addItem(Q){this.send({type:"conversation.item.create",item:Q})}addNote(Q){this.addItem({type:"message",role:"system",content:[{type:"input_text",text:Q}]})}functionOutput(Q,$){this.addItem({type:"function_call_output",call_id:Q,output:typeof $==="string"?$:JSON.stringify($)})}createResponse(Q={}){let $={};if(Q.instructions!==void 0)$.instructions=Q.instructions;if(Q.toolChoice!==void 0)$.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name};if(Q.outputModalities)$.output_modalities=Q.outputModalities;if(Q.conversation)$.conversation=Q.conversation;if(Q.metadata)$.metadata=Q.metadata;Object.assign($,Q.vendor),this.send(Object.keys($).length?{type:"response.create",response:$}:{type:"response.create"})}cancelResponse(Q){this.send(Q?{type:"response.cancel",response_id:Q}:{type:"response.cancel"})}on(Q){return this.listeners.add(Q),()=>this.listeners.delete(Q)}[Symbol.asyncIterator](){let Q={queue:this.backlog??[],done:this.finished};return this.backlog=void 0,this.subscribers.add(Q),{next:async()=>{for(;;){let J=Q.queue.shift();if(J)return{value:J,done:!1};if(Q.done)return this.subscribers.delete(Q),{value:void 0,done:!0};await new Promise((Z)=>Q.wake=Z),Q.wake=void 0}},return:async()=>{return Q.done=!0,Q.queue.length=0,this.subscribers.delete(Q),{value:void 0,done:!0}}}}close(Q=1000,$="closed"){if(this.finished||this.closing)return;if(this.closing=!0,this.socket&&this.socket.readyState<=vQ)this.socket.close(Q,$);else this.finish(Q,$,!0)}async hangup(){try{await this.init.hangup()}catch(Q){if(this.finalEvent&&!this.finalEvent.byClient&&this.finalEvent.code===1000)return;throw Q}this.close(1000,"hangup")}async open(){let Q;try{let J=await this.init.headers();if(this.closing)return this.finish(1000,"closed",!0);Q=(this.init.webSocket??E5)(this.init.url,{headers:J})}catch(J){return this.dropped(1006,J instanceof Error?J.message:String(J),!1)}this.socket=Q;let $=!1;Q.addEventListener("open",()=>{$=!0;let J=this.everOpened;this.everOpened=!0;let Z=this.failures;this.failures=0;for(let X of this.outbox.splice(0))Q.send(X);if(this.resolveReady(),J)this.emit({type:"sideband.reconnected",attempt:Z})}),Q.addEventListener("message",(J)=>{let Z=I5(J.data);if(Z)this.emit(Z)}),Q.addEventListener("close",(J)=>{if(this.socket!==Q)return;this.dropped(J.code??1006,J.reason??"",$)}),Q.addEventListener("error",()=>{})}dropped(Q,$,J){if(this.socket=void 0,this.closing)return this.finish(Q,$,!0);let Z=this.init.reconnect?.attempts??3;if(!((Q!==1000||!J)&&this.failures<Z))return this.finish(Q,$,!1);this.failures+=1;let Y=(this.init.reconnect?.delayMs??500)*2**(this.failures-1);setTimeout(()=>void this.open(),Y)}finish(Q,$,J){if(this.finished)return;this.finished=!0,this.outbox.length=0;let Z={type:"sideband.closed",code:Q,reason:$,byClient:J};this.finalEvent=Z,this.emit(Z);for(let X of this.subscribers)X.done=!0,X.wake?.();if(!this.everOpened)this.rejectReady(Error(`Realtime sideband did not open (${Q} ${$}).`));this.resolveClosed(Z)}emit(Q){if(this.backlog){if(this.backlog.push(Q),this.backlog.length>T5)this.backlog.shift()}for(let $ of this.subscribers){if($.done)continue;$.queue.push(Q),$.wake?.()}for(let $ of this.listeners)try{$(Q)}catch{}}}var hQ=3;function GQ(Q){let $=new Map;for(let J of Q)for(let Z of J.content??[]){if(Z.type!=="file"||!Z.fileId||$.has(Z.fileId))continue;$.set(Z.fileId,{name:Z.name,mimeType:Z.mimeType})}return $}function fQ(Q,$,J=new Map){if(!($ instanceof O))return[];if($.status!==400&&$.status!==404)return[];let Z=VQ($.body);if(!Z)return[];let X=w5(Q.input);if(X.length===0)return[];let Y=/^input\[(\d+)\]\.content\[(\d+)\]\.file_id$/.exec(Z.param??"");if(Y){let K=Q.input[Number(Y[1])],B=WQ(K)[Number(Y[2])],V=B&&typeof B.file_id==="string"?B.file_id:void 0;if(V)return[V]}let G=Z.message??"",F=bQ(X.map((K)=>K.fileId).filter((K)=>k5(G,K)));if(F.length>0)return F;let j=/Expected (image type|context stuffing file type) to be a supported format:.*but got \.([a-z0-9]+)\.?\s*$/is.exec(G);if(j){let K=j[1].toLowerCase()==="image type"?"input_image":"input_file",B=j[2].toLowerCase(),V=bQ(X.filter((H)=>H.type===K).map((H)=>H.fileId)),W=V.filter((H)=>(J.get(H)?.name??"").trim().toLowerCase().endsWith(`.${B}`));if(W.length===1)return W;if(W.length===0&&V.length===1)return V}return[]}function gQ(Q,$,J=new Map){return{...Q,input:Q.input.map((Z)=>{let X=WQ(Z);if(!X.some((Y)=>yQ(Y,$)))return Z;return{...Z,content:X.map((Y)=>yQ(Y,$)?{type:"input_text",text:h(J.get(String(Y.file_id))?.name)}:Y)}})}}function h(Q){return`[${Q?`attachment ${JSON.stringify(Q)}`:"an attachment"} could not be read by the provider and is not shown to you. Tell the user if it matters to the answer; uploading it again may help.]`}function yQ(Q,$){return typeof Q.file_id==="string"&&$.has(Q.file_id)}function WQ(Q){let $=Q?.content;return Array.isArray($)?$:[]}function w5(Q){let $=[];for(let J of Q)for(let Z of WQ(J))if(typeof Z.file_id==="string"&&Z.file_id)$.push({type:String(Z.type),fileId:Z.file_id});return $}function VQ(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;return{message:typeof J.message==="string"?J.message:void 0,param:typeof J.param==="string"?J.param:void 0}}function k5(Q,$){let J=$.replace(/[.*+?^${}()|[\]\\]/g,"\\$&");return new RegExp(`(^|[^A-Za-z0-9_-])${J}($|[^A-Za-z0-9_-])`).test(Q)}function bQ(Q){return[...new Set(Q)]}function uQ(Q,$){if(!($ instanceof O))return null;if($.status!==400&&$.status!==404)return null;let J=Q?.input;if(!Array.isArray(J))return null;let Z=VQ($.body)?.message??"",X=/Item with id '([^']+)' not found/i.exec(Z)?.[1];if(!X)return null;let Y=(G)=>G?.type==="reasoning";if(!J.some((G)=>Y(G)&&G.id===X))return null;return{...Q,input:J.filter((G)=>!Y(G))}}async function*HQ(Q){let $="",J="",Z=[],X,Y=()=>{if(Z.length===0&&!J)return null;let j={event:J,data:Z.join(`
|
|
3
|
+
`),id:X};return J="",Z=[],X=void 0,j.data?j:null},G=(j)=>{let K=j.endsWith("\r")?j.slice(0,-1):j;if(K==="")return Y();if(K.startsWith(":"))return null;let B=K.indexOf(":"),V=B===-1?K:K.slice(0,B),W=B===-1?"":K.slice(B+1);if(W.startsWith(" "))W=W.slice(1);if(V==="event")J=W;else if(V==="data")Z.push(W);else if(V==="id")X=W;return null};for await(let j of Q){$+=j;let K=$.indexOf(`
|
|
4
|
+
`);while(K!==-1){let B=$.slice(0,K);$=$.slice(K+1);let V=G(B);if(V)yield V;K=$.indexOf(`
|
|
5
|
+
`)}}if($.length>0){let j=G($);if(j)yield j}let F=Y();if(F)yield F}async function*cQ(Q,$={}){let J=new Map,Z=new Set,X,Y=!1,G,F=(j,K)=>({type:"finish",reason:j,usage:K,...G?{model:G}:{}});for await(let j of HQ(Q)){if(j.data==="[DONE]")break;let K;try{K=JSON.parse(j.data)}catch{continue}let B=typeof K.type==="string"?K.type:j.event,V=K.response?.model;if(typeof V==="string"&&V)G=V;switch(B){case"response.output_text.delta":{let W=String(K.delta??"");if(!W)break;yield $.structuredOutput?{type:"output-delta",delta:W}:{type:"text-delta",delta:W};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let W=String(K.delta??"");if(!W)break;yield{type:"reasoning-delta",delta:W,id:K.item_id};break}case"response.output_item.added":{let W=K.item;if(!W)break;if(W.type==="function_call"){let H=String(W.id??K.item_id??W.call_id??"");J.set(H,{callId:String(W.call_id??H),name:String(W.name??""),namespace:typeof W.namespace==="string"&&W.namespace?W.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let W=J.get(String(K.item_id??""));if(!W)break;let H=String(K.delta??"");if(!H)break;yield{type:"tool-call-delta",toolCallId:W.callId,name:W.name,argsDelta:H,...W.namespace?{namespace:W.namespace}:{}};break}case"response.function_call_arguments.done":{let W=String(K.item_id??""),H=J.get(W);if(!H)break;H.done=!0,yield{type:"tool-call",toolCallId:H.callId,name:H.name,args:String(K.arguments??""),...H.namespace?{namespace:H.namespace}:{}};break}case"response.output_item.done":{let W=K.item;if(!W)break;if(W.type==="function_call"){let H=String(W.id??K.item_id??W.call_id??""),U=J.get(H);if(U?.done)break;let L=(typeof W.namespace==="string"?W.namespace:"")||U?.namespace;if(yield{type:"tool-call",toolCallId:String(W.call_id??H),name:String(W.name??U?.name??""),args:String(W.arguments??""),...L?{namespace:L}:{}},U)U.done=!0;break}if(W.type==="tool_search_call"||W.type==="tool_search_output"){if(W.type==="tool_search_call"&&W.arguments!==void 0)X=W.arguments;let H=v5(W);if(H.loaded.length===0&&H.namespaces.length===0)break;let U=String(W.tool_search_call_id??W.id??"");if(Z.has(U))break;Z.add(U);let L=X;X=void 0,yield{type:"tool-search",...H,...L!==void 0&&L!==null?{arguments:L}:{}}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(K.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{Y=!0,yield F("stop",KQ(K.response?.usage));break}case"response.incomplete":{Y=!0;let W=KQ(K.response?.usage),H=K.response?.incomplete_details?.reason;if(H==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:y5(K.response?.content_filters),retryable:!1}},yield F("error",W);break}yield F(H==="max_output_tokens"?"length":"stop",W);break}case"response.failed":case"error":{Y=!0;let W=K.response?.error??K.error??K;yield{type:"error",error:b5(W)},yield F("error",KQ(K.response?.usage));break}}if(Y)return}if(!Y)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield F("error",x())}function v5(Q){let $=[],J=[];return mQ(Q.results??Q.tools??Q.loaded??Q.output,$,J,0),{loaded:BQ($),namespaces:BQ(J)}}function mQ(Q,$,J,Z){if(!Array.isArray(Q)||Z>4)return;for(let X of Q){if(typeof X==="string"){$.push(X);continue}if(!X||typeof X!=="object")continue;let Y=X,G=typeof Y.name==="string"?Y.name:typeof Y.tool_name==="string"?Y.tool_name:"",F=Y.tools??Y.functions;if(Array.isArray(F)){if(G)J.push(G);mQ(F,$,J,Z+1);continue}if(G)$.push(G)}}function BQ(Q){return Q.filter(($,J)=>Q.indexOf($)===J)}function y5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let J=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let X=Z,Y=X.content_filter_results;if(!Y||typeof Y!=="object")continue;for(let[G,F]of Object.entries(Y))if(F&&typeof F==="object"&&F.filtered===!0)J.push(`${G} (${String(X.source_type??"unknown")})`)}return J.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${BQ(J).join(", ")}.`}function b5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",J=String(Q?.code??"").toLowerCase();if(J==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(J==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(J.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function x(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function KQ(Q){if(!Q)return x();let $=Number(Q.input_tokens??0),J=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:J,totalTokens:Number(Q.total_tokens??$+J)},X=Q.output_tokens_details?.reasoning_tokens;if(typeof X==="number")Z.reasoningTokens=X;let Y=Q.input_tokens_details?.cached_tokens;if(typeof Y==="number")Z.cachedInputTokens=Y;return Z}async function*pQ(Q){if(!Q)return;let $=Q.getReader(),J=new TextDecoder;try{while(!0){let{done:X,value:Y}=await $.read();if(X)break;if(Y)yield J.decode(Y,{stream:!0})}let Z=J.decode();if(Z)yield Z}finally{$.releaseLock()}}function s(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,streamIdleTimeoutMs:Q.streamIdleTimeoutMs,streamMaxDurationMs:Q.streamMaxDurationMs,maxToolArgumentChars:Q.maxToolArgumentChars,maxRetries:Q.maxRetries}}async function*o(Q,$,J){let Z=J.parse??cQ,X=$,Y=new Set,G=0,F=!1,j=Math.max(0,Q.maxRetries),K=Q.random??Math.random,B,V=(D)=>{if(!B)return D;let _=r(r(x(),B),D.usage);return B=void 0,{...D,usage:_}},W=()=>V({type:"finish",reason:"aborted",usage:x()}),H=Q.streamIdleTimeoutMs??0,U=Q.streamMaxDurationMs??0,L=Q.maxToolArgumentChars??0,P=Q.now??Date.now,g=P();for(let D=0;;D++){let _=new AbortController,u=J.signal?AbortSignal.any([J.signal,_.signal]):_.signal,$Q;while($Q===void 0)try{let q=[],z=()=>{},C=y(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify(X)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:u,fetchImpl:Q.fetchImpl,sleep:Q.sleep,random:Q.random,now:Q.now,startedAt:g,onRetry:(A)=>{q.push({type:"retry",...A,phase:"request"}),z()}}),R=C.then(()=>!0,()=>!0);for(;;){let A=new Promise((p)=>z=()=>p(!1)),v=await Promise.race([R,A]);if(yield*q.splice(0),v)break}$Q=await C}catch(q){let z=X,C=J.files&&G<hQ?fQ(z,q,J.files).filter((v)=>!Y.has(v)):[];if(C.length>0){G++;let v=M(q).message;for(let p of C)Y.add(p),yield{type:"file-rejected",fileId:p,message:v,...I(q)};X=gQ(z,new Set(C),J.files);continue}let R=F?null:uQ(X,q);if(R){F=!0,X=R;continue}let A=M(q);if(A.code==="aborted"){yield W();return}yield{type:"error",error:A,...I(q)},yield V({type:"finish",reason:"error",usage:x()});return}let w=[],c=!1,m,OQ=!1,k=new Map;try{let q=IQ($Q.body,{idleMs:H,maxMs:U},{idle:()=>{let z=new dQ(H);return _.abort(z),z},max:()=>{let z=new lQ(U);return _.abort(z),z}});for await(let z of Z(pQ(q),{structuredOutput:J.structuredOutput})){if(z.type==="tool-call-delta"){let C=(k.get(z.toolCallId)??0)+z.argsDelta.length;if(k.set(z.toolCallId,C),L>0&&C>L){let R=new iQ(L,z.name);throw _.abort(R),R}yield z;continue}if(z.type==="tool-call")k.delete(z.toolCallId);if(c){yield z.type==="finish"?V(z):z;continue}if(a(z)){c=!0,yield*w.splice(0),yield z;continue}if(z.type==="error")m=z.error;w.push(z)}}catch(q){OQ=q instanceof l;let z=M(q);if(z.code==="aborted"||J.signal?.aborted){yield W();return}if(c){yield{type:"error",error:z},yield V({type:"finish",reason:"error",usage:x()});return}m=z,w.push({type:"error",error:z},{type:"finish",reason:"error",usage:x()})}if(c)return;if(m?.retryable&&D<j&&!J.signal?.aborted){let q={};for(let C of w){if(C.type==="finish")B=r(B??x(),C.usage);if(C.type==="error")q=I(C)}if(k.size>0)yield{type:"tool-call-discard",toolCallIds:[...k.keys()]};let z=d(D,K);yield{type:"retry",attempt:D+1,maxRetries:j,error:m,...q,phase:"stream",timedOut:OQ,delayMs:z,elapsedMs:P()-g};try{await JQ(z,J.signal,Q.sleep)}catch{yield W();return}continue}for(let q of w)yield q.type==="finish"?V(q):q;return}}async function t(Q,$,J="user_data"){let Z=new FormData;if(J)Z.set("purpose",J);Z.set("file",$);let Y=await(await y(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!Y?.id)throw Error("The provider accepted the upload but returned no file id.");return Y.id}function FQ(Q,$){let{capabilities:J}=$,Z={model:$.model,input:h5(Q.messages,J,Q.tools),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let X=i5(Q.tools,J);if(X.length>0){if(Z.tools=X,!J.parallelToolCalls)Z.parallel_tool_calls=!1;if(Q.toolChoice!==void 0)Z.tool_choice=typeof Q.toolChoice==="string"?Q.toolChoice:{type:"function",name:Q.toolChoice.name}}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&J.reasoning)Z.reasoning=Q.reasoning==="none"?{effort:"none"}:{effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;if(Q.promptCacheKey)Z.prompt_cache_key=Q.promptCacheKey;return Z}function h5(Q,$,J){let Z=[],X=new Map;if($.toolSearch){for(let Y of J??[])if(e(Y))X.set(Y.name,Y)}for(let Y of Q){let G=Y.role,F=!p5.has(Y.finishReason),j=[],K=()=>{if(j.length===0)return;Z.push({type:"message",role:G,content:j}),j=[]};for(let B of Y.content??[])switch(B.type){case"text":{if(!B.text)break;j.push(T(G,B.text));break}case"output":{if(B.partial)break;j.push(T(G,JSON.stringify(B.value)));break}case"file":{if(G==="assistant")break;let V=UQ(B);if(!$.fileInput){if(V)j.push(T(G,f(B,!1)));break}if(LQ(B,V),B.providerRejected){if(V)j.push(T(G,f(B,!1)));j.push(T(G,h(B.name)));break}if(V)j.push(T(G,f(B,!!B.fileId)));if(B.fileId)j.push(u5(B));break}case"reasoning":{if(K(),!F)break;let V=d5(B);if(V)Z.push(V);break}case"tool-call":{if(B.partial)break;if(K(),$.toolSearch&&Array.isArray(B.toolSearches))for(let W of B.toolSearches)Z.push(...l5(W,J??[]));let V={type:"function_call",call_id:B.toolCallId,name:String(B.name),arguments:JSON.stringify(B.input??{})};if(B.namespace&&X.has(B.namespace))V.namespace=B.namespace;Z.push(V);break}case"tool-result":{K(),Z.push({type:"function_call_output",call_id:B.toolCallId,output:qQ(B)});break}}K()}return g5(Z)}var f5="No result was recorded for this tool call. Assume it did not complete.";function g5(Q){let $=new Set,J=new Set,Z=[];for(let Y of Q){if(Y.type==="function_call"){let G=String(Y.call_id);if($.has(G))continue;$.add(G)}else if(Y.type==="function_call_output"){let G=String(Y.call_id);if(!$.has(G)||J.has(G))continue;J.add(G)}Z.push(Y)}if(J.size===$.size)return Z;let X=[];for(let Y of Z){if(X.push(Y),Y.type!=="function_call")continue;let G=String(Y.call_id);if(J.has(G))continue;J.add(G),X.push({type:"function_call_output",call_id:G,output:f5})}return X}function T(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function UQ(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(jQ)?$:void 0}function f(Q,$){let J=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)J.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)J.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let Z=`attachment ${J.join(" ")}`;return $?`[${Z}]`:`[${Z} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function u5(Q){return{type:zQ(Q)?"input_image":"input_file",file_id:Q.fileId}}function zQ(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return $?$.startsWith("image/")&&$!=="image/svg+xml":c5(Q.name)}function LQ(Q,$){if(Q.fileId?.startsWith(jQ))throw Error(`FilePart.fileId holds a gemi attachment id (${Q.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!Q.fileId&&!$)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.")}function c5(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&m5.has($[1])}var m5=new Set(["jpeg","jpg","png","gif","webp"]),p5=new Set(["error","aborted","interrupted"]);function d5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function qQ(Q){if(Q.status==="ok"){let $=Q.modelOutput!==void 0?Q.modelOutput:Q.output;return typeof $==="string"?$:JSON.stringify($??null)}if(Q.status==="running"){let $=Q.job?.summary===void 0?"":` Started with: ${JSON.stringify(Q.job.summary)}.`;return`Started background job ${Q.job?.id??"(unknown)"}. It is still running, so there is no result yet: this message will be replaced by the result when it finishes. Do not start it again.${$}`}if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function l5(Q,$){let J=new Set(nQ(Q?.loaded)),Z=nQ(Q?.namespaces),X=new Set(Z),Y=[];for(let F of $)if(e(F)){if(!X.has(F.name))continue;let j=F.tools.filter((K)=>J.size===0||J.has(K.name));if(j.length===0)continue;Y.push({type:"namespace",name:F.name,description:F.description,tools:j.map((K)=>E(K,!0))})}else if(F.deferred&&J.has(F.name))Y.push(E(F,!0));if(Y.length===0)return[];return[{type:"tool_search_call",call_id:null,execution:"server",status:"completed",arguments:Q.arguments&&typeof Q.arguments==="object"?Q.arguments:{paths:Z.length>0?Z:[...J]}},{type:"tool_search_output",call_id:null,execution:"server",status:"completed",tools:Y}]}function nQ(Q){return Array.isArray(Q)?Q.filter(($)=>typeof $==="string"):[]}function e(Q){return Array.isArray(Q.tools)}function i5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let X=[];for(let Y of Q)if(e(Y))for(let G of Y.tools)X.push(E(G,!1));else X.push(E(Y,!1));return X}let J=[],Z=!1;for(let X of Q)if(e(X)){let Y=X.tools.map((G)=>{if(G.deferred)Z=!0;return E(G,!0)});J.push({type:"namespace",name:X.name,description:X.description,tools:Y})}else{if(X.deferred)Z=!0;J.push(E(X,!0))}if(Z)J.push({type:"tool_search"});return J}function E(Q,$){let J={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)J.defer_loading=!0;return J}var n5=64000;function rQ(Q,$){let J={model:$.model,max_tokens:Q.maxOutputTokens??n5,messages:X6(Q.messages,$.capabilities),stream:!0},Z=Q.output,X=!!Z?.strict&&!$6(Z.schema),Y=Z&&!X?J6(Z.schema):void 0,G=[Q.systemPrompt,Y].filter(Boolean);if(G.length>0)J.system=[{type:"text",text:G.join(`
|
|
6
|
+
|
|
7
|
+
`)}];let F=$.capabilities.reasoning?Q.reasoning:void 0;if(F==="none"){if(/^claude-sonnet-5-5(?:-\d{8})?$/.test($.modelId))J.thinking={type:"between_tools"};J.output_config={effort:"low"}}else if(F)J.thinking={type:"adaptive",display:"summarized"},J.output_config={effort:a5(F,$.modelId)};else if($.capabilities.reasoning&&r5(J.messages))J.thinking={type:"adaptive"};if(J.thinking?.type==="adaptive"&&$.blockBinding)J.thinking.block_binding={prefix_mismatch_behavior:"drop_block"};if(Z&&X)J.output_config={...J.output_config,format:{type:"json_schema",schema:Q6(Z.schema)}};let j=U6(Q.tools);if(j.length>0){J.tools=j;let K=Z6(Q.toolChoice,$.forcedToolChoice);if(!$.capabilities.parallelToolCalls)K.disable_parallel_tool_use=!0;if(Q.toolChoice!==void 0||K.disable_parallel_tool_use)J.tool_choice=K}return s5(J)}function r5(Q){return Q.some(($)=>$.content.some((J)=>J.type==="thinking"||J.type==="redacted_thinking"))}var DQ="thinking-binding-controls-2026-08-01";function aQ(Q){if(/bound to a different conversation|Invalid `signature` in `thinking` block/i.test(Q))return"thinking";if(/schema is too complex/i.test(Q))return"schema";return}function sQ(Q){let $=[];for(let J of Q.messages){let Z=J.content.filter((Y)=>Y.type!=="thinking"&&Y.type!=="redacted_thinking");if(Z.length===0)continue;let X=$.at(-1);if(X?.role===J.role)X.content.push(...Z);else $.push({role:J.role,content:Z})}return{...Q,messages:$}}function a5(Q,$){if(Q==="none"||Q==="minimal")return"low";if(Q==="xhigh"&&/^claude-(?:opus|sonnet)-4-6(?:-|$)/.test($))return"high";return Q}function s5(Q){let $=(Z)=>{if(Z)Z.cache_control={type:"ephemeral"}};$(Q.tools?.at(-1)),$(Q.system?.at(-1));let J=Q.messages.at(-1)?.content??[];return $([...J].reverse().find((Z)=>Z.type!=="thinking"&&Z.type!=="redacted_thinking")),Q}var o5=new Set(["minimum","maximum","exclusiveMinimum","exclusiveMaximum","multipleOf","minLength","maxLength","maxItems","uniqueItems"]),t5=new Set(["date-time","time","date","duration","email","hostname","uri","ipv4","ipv6","uuid"]),e5=/\\[1-9]|\(\?<?[=!]|\\[bB]/,oQ=new Set(["properties","patternProperties","$defs","definitions"]);function Q6(Q){let $=(J)=>{if(Array.isArray(J))return J.map($);if(!S(J))return J;let Z={},X=[];for(let[Y,G]of Object.entries(J)){if(o5.has(Y)||Y==="minItems"&&typeof G==="number"&&G>1||Y==="format"&&typeof G==="string"&&!t5.has(G)||Y==="pattern"&&typeof G==="string"&&e5.test(G)){X.push(`${Y}: ${JSON.stringify(G)}`);continue}Z[Y]=oQ.has(Y)&&S(G)?Object.fromEntries(Object.entries(G).map(([j,K])=>[j,$(K)])):$(G)}if(X.length>0){let Y=`{${X.join(", ")}}`;Z.description=typeof Z.description==="string"?`${Z.description} ${Y}`:Y}if(Z.type==="object"||S(Z.properties))Z.additionalProperties=!1;return Z};return $(Q)}function $6(Q){let $=0,J=0,Z=(X)=>{if(Array.isArray(X))return X.forEach(Z);if(!S(X))return;if(Array.isArray(X.anyOf)||Array.isArray(X.type))J++;if(S(X.properties)){let Y=new Set(Array.isArray(X.required)?X.required:[]);$+=Object.keys(X.properties).filter((G)=>!Y.has(G)).length}for(let[Y,G]of Object.entries(X))if(oQ.has(Y)&&S(G))Object.values(G).forEach(Z);else Z(G)};return Z(Q),$>24||J>16}function J6(Q){return`Answer with only a JSON value (no prose, no code fence) that matches this JSON schema:
|
|
8
|
+
${JSON.stringify(Q)}`}function Z6(Q,$){if(Q==="none")return{type:"none"};if(Q==="required")return $?{type:"any"}:{type:"auto"};if(Q&&typeof Q==="object")return $?{type:"tool",name:Q.name}:{type:"auto"};return{type:"auto"}}function X6(Q,$){let J=[],Z=new Map;for(let B of Q){let V=B.role==="assistant"?"assistant":"user";J.push("step-end");for(let W of B.content??[])switch(W.type){case"text":{if(V==="assistant"?!!W.text:!!W.text?.trim())J.push({role:V,block:{type:"text",text:W.text}});break}case"output":{if(W.partial)break;let H=W.text??JSON.stringify(W.value);J.push({role:V,block:{type:"text",text:H}});break}case"file":{if(V==="assistant")break;for(let H of B6(W,$))J.push({role:V,block:H});break}case"reasoning":{let H=V==="assistant"?K6(W):void 0;if(H)J.push({role:V,block:H});break}case"tool-call":{if(W.partial)break;J.push({role:"assistant",block:{type:"tool_use",id:W.toolCallId,name:String(W.name),input:S(W.input)?W.input:{}}});break}case"tool-result":{if(J.push("step-end"),Z.has(W.toolCallId))break;Z.set(W.toolCallId,{type:"tool_result",tool_use_id:W.toolCallId,content:qQ(W),...W.status==="error"?{is_error:!0}:{}});break}}}let X=[],Y=(B,V)=>{let W=X[X.length-1];if(W&&W.role===B)W.content.push(V);else X.push({role:B,content:[V]})},G=new Set,F=[],j=!1,K=()=>{for(let B of F)Y("user",Z.get(B)??V6(B));F=[],j=!1};for(let B of J){if(B==="step-end"){j=!0;continue}let{role:V,block:W}=B;if(j||V==="user")K();if(W.type==="tool_use"){let H=String(W.id);if(G.has(H))continue;G.add(H),F.push(H)}Y(V,W)}if(K(),X[0]?.role==="assistant")X.unshift({role:"user",content:[{type:"text",text:Y6}]});if(X.at(-1)?.role==="assistant")X.push({role:"user",content:[{type:"text",text:G6}]});return X}var Y6="(The conversation continues from an earlier point.)",G6="Continue.",W6="No result was recorded for this tool call. Assume it did not complete.";function V6(Q){return{type:"tool_result",tool_use_id:Q,content:W6}}function K6(Q){let $=Q.providerMetadata?.anthropic;if(!S($))return;if($.type==="thinking"&&typeof $.signature==="string")return{type:"thinking",thinking:Q.text??"",signature:$.signature};if($.type==="redacted_thinking"&&typeof $.data==="string")return{type:"redacted_thinking",data:$.data};return}function B6(Q,$){let J=UQ(Q),Z=(Y)=>J?[{type:"text",text:f(Q,Y)}]:[];if(!$.fileInput)return Z(!1);if(LQ(Q,J),!Q.fileId)return Z(!1);let X=Q.providerRejected?void 0:j6(Q);if(!X)return[...Z(!1),{type:"text",text:h(Q.name)}];return[...Z(!0),{type:X,source:{type:"file",file_id:Q.fileId}}]}var H6=new Set(["image/jpeg","image/png","image/gif","image/webp"]);function j6(Q){let $=Q.mimeType?.trim().toLowerCase()??"";if(zQ(Q))return!$||H6.has($)?"image":void 0;if($)return $==="application/pdf"||$==="text/plain"?"document":void 0;return/\.(pdf|txt)$/i.test(Q.name??"")?"document":void 0}function S(Q){return!!Q&&typeof Q==="object"&&!Array.isArray(Q)}function F6(Q){return Array.isArray(Q.tools)}function U6(Q){let $=[];for(let J of Q??[])for(let Z of F6(J)?J.tools:[J])$.push({name:Z.name,description:Z.description,input_schema:Z.parameters,eager_input_streaming:!0});return $}async function*$5(Q,$={}){let J=new Map,Z=[],X,Y={},G,F,j=!1,K=(B)=>({type:"finish",reason:B,usage:C6(Y),...X?{model:X}:{}});for await(let B of HQ(Q)){let V;try{V=JSON.parse(B.data)}catch{continue}switch(typeof V.type==="string"?V.type:B.event){case"message_start":{let H=V.message??{};if(typeof H.model==="string"&&H.model)X=H.model;Y=Q5(Y,H.usage);break}case"content_block_start":{let H=Number(V.index),U=V.content_block??{},L={type:String(U.type??""),id:typeof U.id==="string"?U.id:void 0,name:typeof U.name==="string"?U.name:void 0,args:"",signature:typeof U.signature==="string"?U.signature:""};if(J.set(H,L),L.type==="redacted_thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"redacted_thinking",data:String(U.data??"")}}};if(L.type==="text"&&typeof U.text==="string"&&U.text)yield eQ(U.text,$);break}case"content_block_delta":{let H=J.get(Number(V.index)),U=V.delta??{};if(!H)break;if(U.type==="text_delta"){let L=String(U.text??"");if(L)yield eQ(L,$)}else if(U.type==="thinking_delta"){let L=String(U.thinking??"");if(L)yield{type:"reasoning-delta",delta:L}}else if(U.type==="signature_delta")H.signature+=String(U.signature??"");else if(U.type==="input_json_delta"&&H.type==="tool_use"){let L=String(U.partial_json??"");if(!L)break;H.args+=L,yield{type:"tool-call-delta",toolCallId:H.id??"",name:H.name??"",argsDelta:L}}break}case"content_block_stop":{let H=Number(V.index),U=J.get(H);if(J.delete(H),U?.type==="thinking")yield{type:"reasoning-delta",delta:"",providerMetadata:{anthropic:{type:"thinking",signature:U.signature}}};if(U?.type==="tool_use")if(U.args||="{}",z6(U.args))yield tQ(U);else Z.push(U);break}case"message_delta":{if(typeof V.delta?.stop_reason==="string")G=V.delta.stop_reason;if(V.delta?.stop_details)F=V.delta.stop_details;Y=Q5(Y,V.usage);break}case"message_stop":{if(j=!0,G==="refusal"){yield{type:"error",error:q6(F)},yield K("error");break}let H=L6(G);if(Z.length>0&&H==="length")yield{type:"tool-call-discard",toolCallIds:Z.map((U)=>U.id??"")};else for(let U of Z)yield tQ(U);yield K(H);break}case"error":{j=!0,yield{type:"error",error:D6(V.error??V)},yield K("error");break}}if(j)return}yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield K("error")}function tQ(Q){return{type:"tool-call",toolCallId:Q.id??"",name:Q.name??"",args:Q.args}}function z6(Q){try{return JSON.parse(Q),!0}catch{return!1}}function eQ(Q,$){return $.structuredOutput?{type:"output-delta",delta:Q}:{type:"text-delta",delta:Q}}function L6(Q){if(Q==="max_tokens"||Q==="model_context_window_exceeded")return"length";return"stop"}function q6(Q){let $=typeof Q?.explanation==="string"?Q.explanation:"",J=typeof Q?.category==="string"?` (${Q.category})`:"";return{code:"content_filtered",message:$||`The model declined to answer${J}.`,retryable:!1}}function D6(Q){let $=String(Q?.type??"").toLowerCase(),J=typeof Q?.message==="string"?Q.message:"The provider stream failed.";if($==="rate_limit_error")return{code:"rate_limited",message:J,retryable:!0};if($==="invalid_request_error"||$==="request_too_large")return{code:/prompt is too long|request_too_large/i.test(`${$} ${J}`)?"context_length_exceeded":"provider_error",message:J,retryable:!1};if($==="authentication_error"||$==="permission_error"||$==="billing_error"||$==="not_found_error")return{code:"provider_error",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!0}}function Q5(Q,$){if(!$||typeof $!=="object")return Q;let J={...Q};for(let X of["input_tokens","output_tokens","cache_creation_input_tokens","cache_read_input_tokens"])if(typeof $[X]==="number")J[X]=$[X];let Z=$.output_tokens_details?.thinking_tokens;if(typeof Z==="number")J.thinking_tokens=Z;return J}function C6(Q){if(!Q)return x();let{cache_read_input_tokens:$,cache_creation_input_tokens:J}=Q,Z=(Q.input_tokens??0)+($??0)+(J??0),X=Q.output_tokens??0,Y={inputTokens:Z,outputTokens:X,totalTokens:Z+X};if(typeof $==="number")Y.cachedInputTokens=$;if(typeof J==="number")Y.cacheWriteInputTokens=J;if(typeof Q.thinking_tokens==="number")Y.reasoningTokens=Q.thinking_tokens;return Y}function CQ(Q){let $=PQ(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let J=N6($);if(J?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:J.major>1,toolSearch:J5(J)};if(J?.kind==="gpt")return{reasoning:J.major>=5,structuredOutput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:J.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:J5(J)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function J5(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function NQ(Q){let $=PQ(Q),J=/^claude-(?:opus|sonnet|haiku)-4(?:-(\d{1,2}))?(?:-\d{8})?$/.exec($);return{reasoning:!(/^claude-(?:3|2|instant)/.test($)||!!J&&Number(J[1]??0)<=5),structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!1}}function Z5(Q){let $=PQ(Q);return/^claude-(?:3|2|instant)/.test($)||/^claude-(?:opus|sonnet|haiku)-4(?:-|$)/.test($)||/^claude-(?:opus|sonnet|fable|mythos)-5(?:-\d{8})?$/.test($)||/^claude-haiku-5-5(?:-\d{8})?$/.test($)}function PQ(Q){return Q.trim().toLowerCase()}function N6(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let J=/^o(\d+)(?:[-.]|$)/.exec(Q);if(J?.[1])return{kind:"o",major:Number(J[1]),minor:0};return null}function N(Q){return typeof process>"u"?void 0:process.env?.[Q]}var P6="preview";function X5(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function M6(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function MQ(Q,$={}){return{base:(Q.baseURL??N("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let Z=Q.apiKey??N("OPENAI_API_KEY");return{...Z?{authorization:`Bearer ${Z}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}function Y5(Q){let $=Q.baseURL??Q.endpoint??N("AZURE_OPENAI_ENDPOINT");if($)return X5($);let J=Q.resourceName??N("AZURE_OPENAI_RESOURCE_NAME")??N("AZURE_RESOURCE_NAME");return J?X5(`https://${J.trim()}.cognitiveservices.azure.com`):""}function xQ(Q,$={}){let J=Q.apiVersion??N("AZURE_OPENAI_API_VERSION")??P6;return{base:`${Y5(Q)}${M6(J)}`,query:`?api-version=${encodeURIComponent(J)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let Z=Q.apiKey??N("AZURE_OPENAI_API_KEY");return{...Z?{"api-key":Z}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,streamIdleTimeoutMs:Q.streamIdleTimeoutMs??120000,streamMaxDurationMs:Q.streamMaxDurationMs??300000,maxToolArgumentChars:Q.maxToolArgumentChars??0,maxRetries:Q.maxRetries??2}}var x6="2026-10-21";function G5(Q,$={}){let J=Q.baseURL??N("ANTHROPIC_BASE_URL")??"https://api.anthropic.com";return V5(J,Q,$,async()=>{let Z=Q.workspaceId??N("ANTHROPIC_WORKSPACE_ID"),X=Z?{"anthropic-workspace-id":Z}:{},Y=Q.apiKey??N("ANTHROPIC_API_KEY");if(Y)return{"x-api-key":Y,...X};let G=N("ANTHROPIC_AUTH_TOKEN");return G?{authorization:`Bearer ${G}`,...X}:X})}function W5(Q,$={}){let J=Q.resourceName??N("ANTHROPIC_FOUNDRY_RESOURCE"),Z=Q.baseURL??Q.endpoint??N("ANTHROPIC_FOUNDRY_BASE_URL")??(J?`https://${J.trim()}.services.ai.azure.com/anthropic`:"");if(!Z.trim())throw Error("AzureAnthropicProvider has no Foundry endpoint. Set `endpoint` (the deployment's Target URI without `/v1/messages`, e.g. `https://<resource>.services.ai.azure.com/anthropic`) or `resourceName`, or the ANTHROPIC_FOUNDRY_BASE_URL or ANTHROPIC_FOUNDRY_RESOURCE environment variable.");return V5(Z,Q,$,async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`};let X=Q.apiKey??N("ANTHROPIC_FOUNDRY_API_KEY");return X?{"api-key":X}:{}})}function V5(Q,$,J,Z){return{base:`${Q.trim().replace(/\/+$/,"").replace(/\/v1$/,"")}/v1`,query:"",headers:async()=>({...await Z(),"anthropic-version":x6,...$.headers}),timeoutMs:$.timeoutMs??J.timeoutMs??120000,streamIdleTimeoutMs:$.streamIdleTimeoutMs??120000,streamMaxDurationMs:$.streamMaxDurationMs??300000,maxToolArgumentChars:$.maxToolArgumentChars??0,maxRetries:$.maxRetries??2}}function K5(Q,$={}){return{...xQ(Q,$),base:`${Y5(Q)}/v1`,query:""}}class QQ{static models(){return[]}normalizeError(Q){return M(Q)}}var B5=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class H5 extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=CQ(Q),this.config=$}static model(Q,$){return new H5(Q,$)}static models(){return B5}stream(Q){let $=FQ(Q,{model:this.model,capabilities:this.capabilities});return o(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:GQ(Q.messages)})}upload(Q){return t(this.endpoint(),Q)}endpoint(){return s(MQ(this.config))}get realtime(){return new n(MQ(this.config,{timeoutMs:XQ}),{model:this.model})}}var _6=["claude-opus-5-5","claude-sonnet-5-5","claude-haiku-5-5","claude-fable-5-2","claude-fable-5-1","claude-opus-5","claude-sonnet-5","claude-fable-5","claude-opus-4-8","claude-sonnet-4-6","claude-haiku-4-5"];class _Q extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=NQ(Q),this.config=$}static model(Q,$){return new _Q(Q,$)}static models(){return _6}stream(Q){return this.send(Q)}async*send(Q){let $=Q,J=!1,Z=new Set;for(;;){let X=this.request($);if(J)X=sQ(X);let Y,G=!1;for await(let F of o(this.endpointFor(X),X,{signal:Q.signal,structuredOutput:Boolean(Q.output),parse:$5})){if(Y)continue;if(!G&&F.type==="error"&&F.status===400){let j=aQ(F.error.message);if(j&&!Z.has(j)){Z.add(j),Y=j;continue}}if(a(F))G=!0;yield F}if(!Y)return;if(Y==="thinking")J=!0;else if($.output)$={...$,output:{...$.output,strict:!1}}}}request(Q){return rQ(Q,{model:this.deployment(),modelId:this.model,capabilities:this.capabilities,forcedToolChoice:Z5(this.model),blockBinding:this.bindsThinking()})}endpointFor(Q){let $=this.endpoint();if(!(Q.thinking?.type==="adaptive"&&Q.thinking.block_binding))return $;return{...$,headers:async()=>{let Z=await $.headers(),X=Z["anthropic-beta"];return{...Z,"anthropic-beta":X?`${X},${DQ}`:DQ}}}}bindsThinking(){return!0}deployment(){return this.model}upload(Q){return t(this.endpoint(),Q,null)}endpoint(){return j5(G5(this.config))}}function j5(Q){return{...s(Q),responsesUrl:`${Q.base}/messages`}}class F5 extends _Q{constructor(Q,$={}){super(Q,$);this.capabilities={...NQ(Q),fileInput:!1}}static model(Q,$){return new F5(Q,$)}upload(Q){return Promise.reject(Error("AzureAnthropicProvider does not upload files: the Files API is not available on Azure-hosted Foundry deployments. The file is still stored by gemi and named to the model by its attachment id."))}deployment(){return this.config.deployment??this.model}bindsThinking(){return!1}endpoint(){return j5(W5(this.config))}}class U5 extends QQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=CQ(Q),this.config=$}static model(Q,$){return new U5(Q,$)}static models(){return B5}stream(Q){let $=FQ(Q,{model:this.deployment(),capabilities:this.capabilities});return o(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output),files:GQ(Q.messages)})}upload(Q){return t(this.endpoint(),Q,"assistants")}deployment(){return this.config.deployment??this.model}endpoint(){return s(xQ(this.config))}get realtime(){return new n(K5(this.config,{timeoutMs:XQ}),{model:this.deployment(),callFlow:"ephemeral"})}}
|
|
9
|
+
export{MQ as ca,xQ as da,y as ea,ZQ as fa,P5 as ga,YQ as ha,b as ia,n as ja,S5 as ka,QQ as la,H5 as ma,_Q as na,F5 as oa,U5 as pa};
|
|
10
|
+
|
|
11
|
+
//# debugId=DB3F0DE4EF0A1A8A64756E2164756E21
|