gemi 0.224.0 → 0.225.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/dist/ai/index.js +1 -1
- package/dist/ai/providers/call.d.ts.map +1 -1
- package/dist/ai/testing/index.js +1 -1
- package/dist/bin/http-client/model.d.ts +1 -1
- package/dist/bin/http-client/model.d.ts.map +1 -1
- package/dist/bin/http-client/patch.d.ts +11 -0
- package/dist/bin/http-client/patch.d.ts.map +1 -0
- package/dist/bin/http-client/render.d.ts +3 -3
- package/dist/bin/http-client/render.d.ts.map +1 -1
- package/dist/{chunk-qnag7887.js → chunk-8pz8yzax.js} +2 -2
- package/dist/{chunk-qnag7887.js.map → chunk-8pz8yzax.js.map} +3 -3
- package/dist/{chunk-ftq3tapd.js → chunk-dgy6pf2h.js} +1 -1
- package/dist/{chunk-9yascc81.js → chunk-dpmvvwts.js} +3 -3
- package/dist/{chunk-9yascc81.js.map → chunk-dpmvvwts.js.map} +3 -3
- package/dist/{chunk-39kzdd32.js → chunk-jychsmhf.js} +2 -2
- package/dist/{chunk-39kzdd32.js.map → chunk-jychsmhf.js.map} +1 -1
- package/dist/{chunk-qgfwa4jm.js → chunk-knfvx96p.js} +1 -1
- package/dist/{chunk-3k4p9agd.js → chunk-mdg8g8h2.js} +22 -22
- package/dist/{chunk-3k4p9agd.js.map → chunk-mdg8g8h2.js.map} +8 -7
- package/dist/{chunk-n2epez2r.js → chunk-rdfatx17.js} +1 -1
- package/dist/chunks/{RealtimeClient-CuTFz0v1.js → RealtimeClient-C5Zh3fD6.js} +2 -2
- package/dist/chunks/{RealtimeClient-CuTFz0v1.js.map → RealtimeClient-C5Zh3fD6.js.map} +1 -1
- package/dist/chunks/{ThemeProvider-BO3sQkWl.js → ThemeProvider-bbbE-N3t.js} +5 -3
- package/dist/chunks/ThemeProvider-bbbE-N3t.js.map +1 -0
- package/dist/chunks/{fetchFileRequest-CrKd0rD5.js → fetchFileRequest-JXhnEi-R.js} +2 -2
- package/dist/chunks/{fetchFileRequest-CrKd0rD5.js.map → fetchFileRequest-JXhnEi-R.js.map} +1 -1
- package/dist/chunks/{live-BCCfTb28.js → live-CApTRvmK.js} +3 -3
- package/dist/chunks/{live-BCCfTb28.js.map → live-CApTRvmK.js.map} +1 -1
- package/dist/chunks/{mutationExtras-cPXZS6Hf.js → mutationExtras-C2qSSZ2Q.js} +34 -3
- package/dist/chunks/mutationExtras-C2qSSZ2Q.js.map +1 -0
- package/dist/chunks/{subscriptionStream-CRrAISl8.js → subscriptionStream-DQLW7dTW.js} +2 -2
- package/dist/chunks/{subscriptionStream-CRrAISl8.js.map → subscriptionStream-DQLW7dTW.js.map} +1 -1
- package/dist/client/QueryManagerContext.d.ts +2 -0
- package/dist/client/QueryManagerContext.d.ts.map +1 -1
- package/dist/client/index.d.ts +2 -1
- package/dist/client/index.d.ts.map +1 -1
- package/dist/client/index.js +63 -8
- package/dist/client/index.js.map +1 -1
- package/dist/client/islands.d.ts.map +1 -1
- package/dist/client/mutationExtras.d.ts +1 -1
- package/dist/client/mutationExtras.d.ts.map +1 -1
- package/dist/client/queryUpdates.d.ts +8 -0
- package/dist/client/queryUpdates.d.ts.map +1 -1
- package/dist/client/useInvalidate.d.ts +13 -0
- package/dist/client/useInvalidate.d.ts.map +1 -0
- package/dist/client/useMutation.d.ts +17 -0
- package/dist/client/useMutation.d.ts.map +1 -1
- package/dist/facades/Prefetch.d.ts +22 -0
- package/dist/facades/Prefetch.d.ts.map +1 -1
- package/dist/facades/index.js +1 -1
- package/dist/http/index.js +1 -1
- package/dist/i18n/index.js +1 -1
- package/dist/kernel/index.js +1 -1
- package/dist/server/index.js +1 -1
- package/dist/services/index.js +1 -1
- package/dist/services/router/ServerQueryStore.d.ts +8 -0
- package/dist/services/router/ServerQueryStore.d.ts.map +1 -1
- package/dist/testing/index.js +2 -2
- package/dist/utils/invalidation.d.ts +16 -0
- package/dist/utils/invalidation.d.ts.map +1 -0
- package/package.json +1 -1
- package/dist/chunks/ThemeProvider-BO3sQkWl.js.map +0 -1
- package/dist/chunks/mutationExtras-cPXZS6Hf.js.map +0 -1
- /package/dist/{chunk-ftq3tapd.js.map → chunk-dgy6pf2h.js.map} +0 -0
- /package/dist/{chunk-qgfwa4jm.js.map → chunk-knfvx96p.js.map} +0 -0
- /package/dist/{chunk-n2epez2r.js.map → chunk-rdfatx17.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,ka as A6,la as P$,ma as R6,na as E6,oa as k6,pa as T6}from"../chunk-
|
|
2
|
+
import{ca as uQ,da as lQ,ea as iQ,fa as _6,ga as B6,ha as S6,ia as m$,ja as M6,ka as A6,la as P$,ma as R6,na as E6,oa as k6,pa as T6}from"../chunk-dpmvvwts.js";import{$c as X6,Ac as CZ,Bc as YQ,Dc as VQ,Ec as FQ,Fc as HQ,Gc as PQ,Hc as NQ,Ic as OQ,Jc as UQ,Kc as CQ,Lc as LQ,Mc as _Q,Nc as BQ,Oc as SQ,Qc as c$,Rc as a9,Sc as t9,Tc as r9,Uc as e9,Vc as J6,Wc as $6,Xc as Q6,Yc as Z6,Zc as W6,_c as K6,ad as DJ,bd as G6,cd as eZ,dd as Y6,ed as J8,fd as V6,gd as z6,hd as D6,ic as h$,id as kJ,jc as lZ,jd as K$,kc as iZ,kd as H6,lc as g$,ld as P6,md as $8,nd as N6,od as F6,pc as gQ,pd as O6,qc as fQ,qd as U6,rc as GJ,rd as C6,sc as s9,sd as L6,tc as b,td as Z$,uc as KQ,vc as XQ,xc as GQ,yc as g,zc as UZ}from"../chunk-8pz8yzax.js";import{Gd as m,Hd as u$,Kd as dZ,Ld as nZ,Md as oZ,Nd as qJ,Od as sZ,Pd as mJ,Qd as vJ,Rd as w$,Sd as aZ,Td as tZ,Ud as pJ,Vd as rZ,_d as t,ae as a,xd as nQ,yd as A,zd as T}from"../chunk-kp7wcpx7.js";import{re as e$}from"../chunk-7xe5vd4w.js";import"../chunk-p1ern8r4.js";import{Ni as I,li as qZ,oi as hZ,uj as gZ,zj as S$}from"../chunk-zcmz311y.js";import{Aj as vZ,Cj as uJ,Dj as cJ}from"../chunk-h1wmpa03.js";import{Mj as c}from"../chunk-t586p2g2.js";import{Oj as d9,Pj as n9,Qj as o9}from"../chunk-qs2xvc8g.js";import"../chunk-anc5v266.js";import{Xk as uZ,Yk as cZ,Zk as mZ,_k as pZ}from"../chunk-tac25cnj.js";import"../chunk-0k2r6bep.js";import{el as o,fl as s,ul as AJ}from"../chunk-0av1gyns.js";import"../chunk-zmt5kdpb.js";import"../chunk-yj7pbbnm.js";import{lm as GZ}from"../chunk-37209psn.js";import"../chunk-fqhkkpq3.js";import"../chunk-6r7956dh.js";import{Im as nJ}from"../chunk-5mrtgr7q.js";import"../chunk-3dkv4989.js";import{existsSync as z8,readdirSync as x6,readFileSync as a$}from"fs";import{isAbsolute as D8,join as CJ,relative as H8,sep as P8}from"path";var t$="prompts.json",N8=/\{\{>\s*([\w./-]+)\s*\}\}/g,n$=/\{\{(\w+)\}\}/g,F8=/^[\w-]+(\/[\w-]+)*$/,o$={dir:"app/agents",shared:"prompts"},_J={},iJ=new Map,LJ;function O8(){if(LJ===void 0){let J=CJ(nJ(),"dist","server",t$);LJ=z8(J)?JSON.parse(a$(J,"utf8")):null}return LJ??null}function U8(J){return J.replace(/\r?\n$/,"")}function s$(){return _J.cache??Bun.env.NODE_ENV==="production"}function C8(J,$){if(!F8.test(J))throw Error(`"${J}" is not a prompt name. Use letters, digits, "-" and "_", with "/" between folders.`);let Q=$.dir??_J.dir??o$.dir,Z=D8(Q)?Q:CJ(process.cwd(),Q),W=J.includes("/")?`${J}.md`:CJ($.shared??_J.shared??o$.shared,`${J}.md`);return CJ(Z,W)}function L8(J,$){let Q=C8(J,$),Z=s$()?iJ.get(Q):void 0;if(Z!==void 0)return Z;let W=Bun.env.NODE_ENV==="production";if(W){let X=O8()?.[H8(nJ(),Q).split(P8).join("/")];if(X!==void 0)return X}let K;try{K=U8(a$(Q,"utf8"))}catch(X){if(X.code==="ENOENT"){let G=W?` or in dist/server/${t$}`:"";throw Error(`The prompt "${J}" does not exist (looked for ${Q}${G}).`)}throw X}if(s$())iJ.set(Q,K);return K}function dJ(J,$,Q){if($.includes(J))throw Error(`The prompt "${J}" includes itself: ${[...$,J].join(" > ")}.`);return L8(J,Q).replace(N8,(Z,W)=>dJ(W,[...$,J],Q))}class r${static configure(J){_J={...J},iJ.clear(),LJ=void 0}static render(J,$={},Q={}){return dJ(J,[],Q).replace(n$,(Z,W)=>{if(!Object.hasOwn($,W))throw Error(`The prompt "${J}" has no value for {{${W}}}.`);return String($[W])})}static placeholders(J,$={}){let Q=[...dJ(J,[],$).matchAll(n$)].map((Z)=>Z[1]);return[...new Set(Q)]}}class oJ extends e${name="AgentJobDeadlineSweep";cron="* * * * *";async callback(){while(await g.sweep({limit:100})===100);}}var SJ=20,_8=300,B8=200;function $Q(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)=>!b(K.state)).sort(Q),...J.filter((K)=>b(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 ${BJ(K.createdAt)}`);else if(K.state==="running")X.push(`running since ${BJ(K.createdAt)}`);else if(K.state==="ok")X.push(`finished at ${BJ(K.settledAt??K.updatedAt)}`);else{let G=K.error?`${K.error.code}: ${JQ(K.error.message,B8)}`:"failed";X.push(`failed at ${BJ(K.settledAt??K.updatedAt)} (${G})`)}if(K.summary!==void 0)X.push(`summary: ${JQ(JSON.stringify(K.summary),_8)}`);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 BJ(J){return new Date(J).toISOString().replace(/\.\d{3}Z$/,"Z")}function JQ(J,$){return J.length<=$?J:`${J.slice(0,$-1)}\u2026`}var QQ=["after_jobs","batch_key","queued","inbox","job_checkpoint"],ZQ=20;class sJ{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 S8(this.dialect,this.table))await this.sql.unsafe(J)}async transaction(J){if(this.connection===void 0||this.joinable())return J();return AJ(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;AAUlD,OAAO,EAIL,KAAK,QAAQ,EACd,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,cAAc,EAGnB,KAAK,mBAAmB,EACzB,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,kCAAkC;IAClC,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,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,CAY3E;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,4DAA4D;IAC5D,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;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,
|
|
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;AAUlD,OAAO,EAIL,KAAK,QAAQ,EACd,MAAM,iBAAiB,CAAC;AAGzB,OAAO,EAKL,KAAK,SAAS,EACd,KAAK,cAAc,EAGnB,KAAK,mBAAmB,EACzB,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,kCAAkC;IAClC,KAAK,CAAC,EAAE,mBAAmB,CAAC;IAC5B,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,CAY3E;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,4DAA4D;IAC5D,yBAAyB,CAAC,EAAE,OAAO,CAAC;IACpC;;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,CAiQ/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;AAED;;;;;;;;GAQG;AACH,wBAAsB,UAAU,CAAC,QAAQ,EAAE,iBAAiB,EAAE,MAAM,EAAE,MAAM,GAAG,OAAO,CAAC,IAAI,CAAC,CAqB3F"}
|
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-dpmvvwts.js";import"../../chunk-kp7wcpx7.js";import{Oj as v,Pj as m}from"../../chunk-qs2xvc8g.js";import"../../chunk-3dkv4989.js";import{createHash as s}from"crypto";import{createHash as S}from"crypto";import{existsSync as h,readdirSync as c,readFileSync as l,statSync as p}from"fs";import{join as q,relative as d,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 c(D)){if(z==="node_modules")continue;let B=q(D,z);if(p(B).isDirectory())y(B,$);else if(z.endsWith(".md"))$.push(B)}return $}class W{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(d($,C).split(i).join("/"),l(C,"utf8"))}return z}static of(D,$,z={}){let B=[...D].join(`
|
|
3
3
|
\x00
|
|
4
4
|
`),C={};for(let[Y,Q]of W.prompts(z))if(W.pieces(Q).filter((Z)=>Z.length>=12).sort((Z,L)=>L.length-Z.length).slice(0,3).some((Z)=>B.includes(Z)))C[Y]=W.blob(Q);let G=[...$.keys()].sort(),X=z.inputs?.(new Set(G));return new W({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 W?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=W.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=W.prompts(this.options);return Object.entries(this.data.prompts).filter(([$,z])=>{let B=D.get($);return B===void 0||W.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)=>W.pieces(G)).sort((G,X)=>X.length-G.length)}}function a(D){return Object.fromEntries(Object.entries(D).sort(([$],[z])=>$.localeCompare(z)))}class H 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 W($.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 H(`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 W.of(D.texts,D.toolHashes,this.options.fingerprints)}static changedSince(D,$={}){return D.fingerprints?new W(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}async deleteFile(D){let $=this.uploads.get(D);if(this.live&&$!==void 0){if(!this.live.deleteFile)throw Error(`${this.live.constructor.name} cannot delete provider files: it does not implement deleteFile().`);await this.live.deleteFile($),this.uploads.delete(D)}}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),L=G.filter((I)=>I.type!=="tool-call-delta"||!Z.has(I.toolCallId));G.splice(0,G.length,...L)}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 H(`${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:L,content:I})=>({role:L,content:f(I)})),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=(L)=>{return V.texts.add(L),L};if(T([G,X.slice(Y)],Z),Q&&!V.toolLists.has(Q)){V.toolLists.add(Q);for(let L of E(C)){T(L,Z);let I=V.toolHashes.get(L.name)??new Set;I.add(W.tool(L)),V.toolHashes.set(L.name,I)}}return{...f(G),...Q?{tools:`sha256:${r(Q)}`,toolNames:E(C).map((L)=>L.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=(A,K,J)=>{let N=JSON.stringify(A).replace(C,"<id>"),j=JSON.stringify(K).replace(C,"<id>"),_=0;while(_<N.length&&N[_]===j[_])_++;throw new H(`${D}: the request differs from the recorded one${J}. Recorded: \u2026${N.slice(Math.max(0,_-80),_+120)}\u2026 Sent: \u2026${j.slice(Math.max(0,_-80),_+120)}\u2026`)};if(G==="exact")Y(X,z,"");let{tools:Q,toolNames:V,...Z}=X,{tools:L,toolNames:I,...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(J){throw new H(`${D}: ${J.message}.`)}let A=T(Z,this.cuts.recorded),K=T(k,this.cuts.sent);if(this.cuts.changed.length===0||!this.matches(JSON.stringify(A),K))Y(A,K,this.cuts.changed.length>0?", beyond the wording of the prompts changed since":"");w.push(...this.cuts.changed.map((J)=>`${J} 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:K,...J}=Z,{messages:N,...j}=k;if(!this.matches(JSON.stringify(K),N))w.push("message text changed");let _=new Set([...Object.keys(J),...Object.keys(j)]);for(let U of[..._].sort()){let O=JSON.stringify(J[U]??null);if(!this.matches(O,j[U]??null))w.push(`${U} changed`)}}if(Q!==L){let A=E(B);for(let K of $.events){if(K.type!=="tool-call")continue;let J=A.find((O)=>O.name===K.name);if(!J)throw new H(`${D}: the recorded answer calls ${K.name}, which is not offered any more.`);let N=Object.fromEntries([...JSON.stringify(J.parameters).matchAll(/"format":"([^"]+)"/g)].map(([,O])=>[O,!0])),j;try{j=JSON.parse(K.args||"{}")}catch{j=void 0}let _;try{_=m.fromJSONSchema(J.parameters,{unknownKeys:"error",formats:N})}catch(O){if(!(O instanceof v))throw O}let U=_?.safeParse(j);if(U&&U.ok===!1)throw new H(`${D}: the recorded call of ${K.name} does not fit its schema any more (${U.errors.join("; ")}).`)}if(this.recorded){let K=A.filter((J)=>!this.recorded.data.tools[J.name]?.includes(W.tool(J))).map((J)=>J.name).sort();w.push(K.length>0?`tools changed: ${K.join(", ")}`:"the tools offered changed")}else{let K=new Set(V??[]),J=new Set(I??[]),N=[...J].filter((_)=>!K.has(_)),j=[...K].filter((_)=>!J.has(_));w.push(N.length>0||j.length>0?`tools offered changed (${[...N.map((_)=>`+${_}`),...j.map((_)=>`-${_}`)].join(", ")})`:"the tools offered changed")}}this.shared.staleCalls++;for(let A of w)this.shared.stale.add(A)}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 H(`${$}: 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 H(`${$}: 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,H as RecordingMismatchError,W as Fingerprints};
|
|
5
5
|
|
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
import type { HttpMethod } from "../../http/ApiRouter";
|
|
2
2
|
import type { NamedType, TypeRef } from "../ai-client/model";
|
|
3
|
-
/**
|
|
3
|
+
/** Language-neutral description shared by the native HTTP renderers. */
|
|
4
4
|
export type HttpRouteModel = {
|
|
5
5
|
/** The exact CreateRPC key, with groups removed by the framework. */
|
|
6
6
|
key: string;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../bin/http-client/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7D,
|
|
1
|
+
{"version":3,"file":"model.d.ts","sourceRoot":"","sources":["../../../bin/http-client/model.ts"],"names":[],"mappings":"AAAA,OAAO,KAAK,EAAE,UAAU,EAAE,MAAM,sBAAsB,CAAC;AACvD,OAAO,KAAK,EAAE,SAAS,EAAE,OAAO,EAAE,MAAM,oBAAoB,CAAC;AAE7D,wEAAwE;AACxE,MAAM,MAAM,cAAc,GAAG;IAC3B,qEAAqE;IACrE,GAAG,EAAE,MAAM,CAAC;IACZ,MAAM,EAAE,UAAU,CAAC;IACnB,IAAI,EAAE,MAAM,CAAC;IACb,gFAAgF;IAChF,cAAc,EAAE;QAAE,IAAI,EAAE,MAAM,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAC;QAAC,QAAQ,EAAE,OAAO,CAAA;KAAE,EAAE,CAAC;IACzE,uEAAuE;IACvE,MAAM,EAAE,OAAO,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACnC,KAAK,EAAE;QAAE,QAAQ,EAAE,OAAO,GAAG,MAAM,CAAC;QAAC,IAAI,EAAE,OAAO,GAAG;YAAE,IAAI,EAAE,MAAM,CAAA;SAAE,CAAA;KAAE,CAAC;IACxE,QAAQ,EAAE,OAAO,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,GAAG;QAAE,IAAI,EAAE,MAAM,CAAA;KAAE,CAAC;IACxD,+EAA+E;IAC/E,KAAK,EAAE,OAAO,CAAC;CAChB,CAAC;AAEF,MAAM,MAAM,YAAY,GAAG;IACzB,MAAM,EAAE,MAAM,CAAC;IACf,MAAM,EAAE,cAAc,EAAE,CAAC;IACzB,KAAK,EAAE,SAAS,CAAC,OAAO,CAAC,EAAE,CAAC;IAC5B,QAAQ,EAAE,MAAM,EAAE,CAAC;CACpB,CAAC"}
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
import type { HttpApiModel } from "./model";
|
|
2
|
+
/** Select one JSON PATCH with a trailing string ID and a single typed rejection. */
|
|
3
|
+
export declare function patchCall(api: HttpApiModel, key: string): {
|
|
4
|
+
name: string;
|
|
5
|
+
segments: string[];
|
|
6
|
+
body: string;
|
|
7
|
+
output: string;
|
|
8
|
+
error: string;
|
|
9
|
+
status: number;
|
|
10
|
+
};
|
|
11
|
+
//# sourceMappingURL=patch.d.ts.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"patch.d.ts","sourceRoot":"","sources":["../../../bin/http-client/patch.ts"],"names":[],"mappings":"AACA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAE5C,oFAAoF;AACpF,wBAAgB,SAAS,CAAC,GAAG,EAAE,YAAY,EAAE,GAAG,EAAE,MAAM;;;;;;;EAuCvD"}
|
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
import type { HttpApiModel } from "./model";
|
|
2
|
-
/**
|
|
3
|
-
export declare function renderHttpSwift(api: HttpApiModel): string;
|
|
4
|
-
export declare function renderHttpKotlin(api: HttpApiModel, packageName: string): string;
|
|
2
|
+
/** Models for the whole API, optionally with a callable PATCH route. */
|
|
3
|
+
export declare function renderHttpSwift(api: HttpApiModel, patchKey?: string): string;
|
|
4
|
+
export declare function renderHttpKotlin(api: HttpApiModel, packageName: string, patchKey?: string): string;
|
|
5
5
|
//# sourceMappingURL=render.d.ts.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../../bin/http-client/render.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;
|
|
1
|
+
{"version":3,"file":"render.d.ts","sourceRoot":"","sources":["../../../bin/http-client/render.ts"],"names":[],"mappings":"AAeA,OAAO,KAAK,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAoG5C,wEAAwE;AACxE,wBAAgB,eAAe,CAAC,GAAG,EAAE,YAAY,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CA+C5E;AAED,wBAAgB,gBAAgB,CAAC,GAAG,EAAE,YAAY,EAAE,WAAW,EAAE,MAAM,EAAE,QAAQ,CAAC,EAAE,MAAM,GAAG,MAAM,CA2ElG"}
|
|
@@ -20,7 +20,7 @@ ${await K$(B)}`);return Q.join(`
|
|
|
20
20
|
`)}})}async function K$(Z){try{return await Bun.file(Z).text()}catch($){return`(could not be read: ${$.message})`}}function F$(Z){return typeof Z==="object"&&Z!==null&&typeof Z.next==="function"&&Symbol.asyncIterator in Z}function a4(Z,$){let Q=[...Z],B=new Map(Q.map((X,G)=>[X.id,G]));for(let X of $){let G=B.get(X.id);if(G===void 0)B.set(X.id,Q.length),Q.push(X);else Q[G]=X}return Q}function xZ(Z){let $=new Set;for(let B of Z)for(let X of B.content)if(X.type==="tool-result")$.add(X.toolCallId);let Q=new Set;for(let B of Z)for(let X of B.content)if(X.type==="tool-call"&&!$.has(X.toolCallId))Q.add(X.toolCallId);return Q}function r4(Z){for(let $=Z.length-1;$>=0;$--){let Q=Z[$].content;for(let B=Q.length-1;B>=0;B--){let X=Q[B];if(X.type==="output"&&X.partial!==!0)return X.value}}return}function e4(Z,$){return $===void 0?`"${Z}"`:`"${Z}" labelled "${$}"`}function O7(Z){return Z.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function D$(Z){if(Z.prompt!==void 0)return`user:${Z.prompt}`;let $=Z.messages?.[0];return $?`${$.role}:${O7($)}`:null}var Z7=1;function U$(Z,$,Q){let B=Q.mimeType||$.type||"";if(B&&Z.attachment.mimeType!==B)return`was ${JSON.stringify(Z.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(B)} on the replay`;let X=Boolean(Q.showModel);if(X!==Boolean(Z.shown))return X?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function P$(Z,$,Q){if(Z.agent!==$.name||Z.label!==Q.label)return`was ${e4(Z.agent,Z.label)} on the turn that escalated and is ${e4($.name,Q.label)} on the replay`;let B=D$(Q),X=Z.messages[0],G=X?`${X.role}:${O7(X)}`:null;if(B!==null&&G!==null&&B!==G)return`was started with ${JSON.stringify(G)} on the turn that escalated and with ${JSON.stringify(B)} on the replay`;return null}function $7(Z,$){let Q=Z??[];if(Q.length<$.length)return null;for(let B=0;B<$.length;B++)if(Q[B]!==$[B])return null;return Q.slice($.length)}class I0{read;create;fill;index=0;replayable;constructor(Z,$,Q){this.read=Z;this.create=$;this.fill=Q;this.replayable=Z()?.length??0}next(){let Z=this.index++;return{at:Z,recorded:Z<this.replayable?this.read()?.[Z]:void 0,write:($)=>{let Q=this.read()??this.create();if(this.fill)for(let B=Q.length;B<Z;B++)Q[B]=this.fill();Q[Z]=$}}}}class R7{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];compactMemo=new Map;lastStep;forceAgain;stepOffered;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=x();modelSteps=0;toolCallCount=0;limiter;limitHit=null;approvals=new Map;denials=[];finishReason="stop";cutCalls=0;failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;meter;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;openedWith=0;nestedSettling=new Set;shownQueue=new Map;memory;memoryBlock=null;constructor(Z,$){this.config=Z,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages],this.limiter=$.usageLimits?new C0($.usageLimits,{runId:this.runId,agent:Z.name,...$.threadId?{threadId:$.threadId}:{}},(G)=>this.writeLog(`[gemi/ai] agent "${Z.name}" usageLimits.onUsage threw`,{error:G})):null;let Q=$.nesting;if(this.depth=Q?.depth??0,this.maxDepth=Q?.maxDepth??Z.maxDepth,this.chain=Q?.chain??[Z.name],this.signingRunId=Q?.signingRunId??this.runId,this.pathPrefix=Q?.signingPath??[],this.onPending=Q?.onPending??"escalate",this.memory=new PZ({options:Z.memory,scopes:$.memory?.scopes,agent:Z.name,runId:this.runId,threadId:$.threadId,writes:Q?.memoryWrites}),$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});let B=Z.maxRunDurationMs!==void 0?Z.maxRunDurationMs:Q?null:P7;this.cancelDeadline=N0(B,()=>this.expire(B));let X=sZ();this.meter=X.meter,this.settled=X.run(()=>this.execute()),this.settled.then(X.close,X.close),X7.getStore()?.waitUntil(this.settled)}emit(Z){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Z}),this.wake()}wake(){let Z=[...this.waiters];this.waiters.clear();for(let $ of Z)$()}nextFrame(){return new Promise((Z)=>this.waiters.add(Z))}async*frames(Z=0){let $=Z>0?Z-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Z of this.frames())yield Z.event}toResponse(Z){let $=this.frames(Z?.from),Q=new TextEncoder,B=!1,X,G=new ReadableStream({start:async(V)=>{X=z7(V);try{for await(let W of $){if(B)break;V.enqueue(Q.encode(`id: ${W.seq}
|
|
21
21
|
data: ${JSON.stringify(W.event)}
|
|
22
22
|
|
|
23
|
-
`)),X.touch()}}catch{}X.stop();try{V.close()}catch{}},cancel:()=>{B=!0,X.stop()}});return new Response(G,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Z){if(!Z?.throwOnError)return this.settled;return this.settled.then(($)=>{let Q=$.error;if(Q?.toolArgumentsTooLong)throw new j7({...$,error:{...Q,toolArgumentsTooLong:Q.toolArgumentsTooLong}});if(Q)throw new HZ({...$,error:Q});return $})}stop(Z){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Z?.reason,this.controller.abort()}expire(Z){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Z,this.stopReason=`The run reached its time limit of ${O0(Z)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{await this.prepareMemory();let $=await this.resolveToolSchemas(),Q=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else if(this.answersOnlyStale())this.fail({code:"invalid_tool_result",message:"The tool calls this turn answers are no longer waiting for an answer: an earlier turn answered or refused them.",retryable:!1}),this.finishReason="error";else await this.loop()}catch($){if($ instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else if($ instanceof WZ)this.fail({code:"unknown",message:$.message,retryable:!0}),await this.finalizeMessage("error"),this.finishReason="error",this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its usage limits`,{error:$.cause});else this.fail(this.config.provider.normalizeError($),i($)),await this.finalizeMessage("error"),this.finishReason="error"}if(this.cancelDeadline(),this.limiter)try{await this.limiter.report(this.spent(),!0)}catch($){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record its usage`,{error:$})}this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),this.precompact();let Z=this.finishReason==="error"?this.failure:void 0;if(Z&&this.config.logErrors)this.logFailure(Z);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,metered:this.meter.totals(),output:this.output,...Z?{error:Z}:{}}}async resolveToolSchemas(){let Z=[...this.config.registry.values()].filter((z)=>!z.inputSchema);if(Z.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Q=new Map,B=await Promise.all(Z.map(async(z)=>{try{let J=z.tool.inputSchema,H=await J($);x0(H,`The tool "${z.tool.name}"`,"inputSchema"),Q.set(z.tool.name,H);return}catch(J){return`"${z.tool.name}": ${J instanceof Error?J.message:String(J)}`}}));if(this.controller.signal.aborted)throw new S;let X=B.filter((z)=>z!==void 0);if(X.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${X.join("; ")}`,retryable:!1};let G=new Map;for(let[z,J]of this.config.registry)G.set(z,Q.has(z)?{...J,inputSchema:Q.get(z)}:J);let V=(z)=>Q.has(z.name)?JZ(G.get(z.name)):z,W=this.config.providerTools.map((z)=>("tools"in z)?{...z,tools:z.tools.map(V)}:V(z));this.config={...this.config,registry:G,providerTools:W};return}async prepareMemory(){let Z=this.config.memory;if(!Z)return;let $=this.memory,Q=$.writableLabels(),B=$.toolKinds(),X=(z)=>z==="recall"?$.labels.length>0:Q.length>0&&B.length>0,G=new Map;for(let[z,J]of this.config.registry){if(J.namespace!==v){G.set(z,J);continue}if(!X(z))continue;let H=z==="recall"?$.labels:Q,q=BZ(z,{scopes:H,descriptions:$.describeScopes(H),kinds:B});G.set(z,{...J,inputSchema:q})}let V=this.config.providerTools.flatMap((z)=>{if(!("tools"in z)||z.name!==v)return[z];let J=z.tools.filter((H)=>G.has(H.name)).map((H)=>JZ(G.get(H.name)));return J.length>0?[{...z,tools:J}]:[]});this.config={...this.config,registry:G,providerTools:V};let W=this.params.memory?.maxTokens??Z.maxTokens??t0;try{this.memoryBlock=await $.block({maxTokens:W,recall:G.has("recall"),tools:G.has("remember")||G.has("forget")})}catch(z){let J=z instanceof Error?z.message:String(z);this.writeLog(`[gemi/ai] agent "${this.config.name}": the memory store could not be read, so this run has no <memory> block: ${J}`,{error:z})}if(this.controller.signal.aborted)throw new S}spent(){return{tokens:this.usage.totalTokens,steps:this.modelSteps,toolCalls:this.toolCallCount}}failOverLimit(Z){this.fail({code:"usage_limit",message:L0(Z),retryable:!1},{usageLimit:Z}),this.finishReason="error"}fail(Z,$={}){let Q={...Z,...$};this.failure=Q,this.emit({type:"error",error:this.redact(Q,{source:"run",failure:Q})})}redact(Z,$){let Q=V7(this.params.redactError,Z,$,(B)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:B}));return W7(Q,Z),Q}logFailure(Z){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Z.code}${Z.status!==void 0?` ${Z.status}`:""}): ${Z.message}`;this.writeLog($,{error:Z})}logToolFailure(Z,$){let Q=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Z.name)}" threw: ${Q}`,{toolCallId:Z.toolCallId,error:$})}writeLog(Z,$){let Q={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},B=!1;try{t.error(Z,Q),B=!0}catch{}if(!B||Bun.env.NODE_ENV==="development")console.error(Z,Q)}async loop(){let Z=Math.max(1,this.config.maxSteps);for(let $=1;$<=Z;$++){if(this.limiter){let z=await this.limiter.check(this.spent(),{steps:1,tokens:1});if(z){this.failOverLimit(z);return}}await this.takeInbox();let Q=this.startMessage(),B=await this.runStep(Q,$);this.modelSteps++,this.lastStep={reason:B.reason,usage:Q.usage},await this.limiter?.report(this.spent());let X=B.error?this.cutCallToModel(Q,B.detail):void 0;if(B.error&&!X){this.fail(B.error,B.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Q.content.filter((z)=>z.type==="tool-call"&&z!==X);if(G.length===0&&!X&&B.emulated&&$<Z){this.forceAgain=B.emulated,await this.finalizeMessage(B.reason);continue}if(G.length===0&&!X){this.finishReason=B.reason,await this.finalizeMessage(B.reason);return}let V=G.length>0?await this.runTools(Q,G,$):[];if(await this.limiter?.report(this.spent()),this.limitHit&&V.length===0){let z=this.limitHit;await this.finalizeMessage(B.reason),this.failOverLimit(z);return}if(V.length>0){if(this.finishReason="awaiting-input",this.depth===0)Q.pending=V;await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:V});return}let W=X?null:await this.closingText(Q,G,$);if(W!==null){if(this.finishReason="stop",await this.finalizeMessage(B.reason),W){let z=this.startMessage();s(z,"text",W),this.emit({type:"text-delta",messageId:z.id,delta:W}),await this.finalizeMessage("stop")}return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(X?"stop":B.reason)}}cutCallToModel(Z,$){let Q=$?.toolArgumentsTooLong;if(!Q||this.cutCalls>=this.config.cutCallsToModel)return;let B=Z.content.find((X)=>X.type==="tool-call"&&X.toolCallId===Q.toolCallId);if(!B)
|
|
23
|
+
`)),X.touch()}}catch{}X.stop();try{V.close()}catch{}},cancel:()=>{B=!0,X.stop()}});return new Response(G,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(Z){if(!Z?.throwOnError)return this.settled;return this.settled.then(($)=>{let Q=$.error;if(Q?.toolArgumentsTooLong)throw new j7({...$,error:{...Q,toolArgumentsTooLong:Q.toolArgumentsTooLong}});if(Q)throw new HZ({...$,error:Q});return $})}stop(Z){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Z?.reason,this.controller.abort()}expire(Z){if(this.ended||this.controller.signal.aborted)return;this.timedOutAfter=Z,this.stopReason=`The run reached its time limit of ${O0(Z)} and was stopped.`,this.controller.abort(new DOMException(this.stopReason,"TimeoutError"))}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{await this.prepareMemory();let $=await this.resolveToolSchemas(),Q=$?[]:await this.ingestTurn();if($)this.fail($),this.finishReason="error";else if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else if(this.answersOnlyStale())this.fail({code:"invalid_tool_result",message:"The tool calls this turn answers are no longer waiting for an answer: an earlier turn answered or refused them.",retryable:!1}),this.finishReason="error";else await this.loop()}catch($){if($ instanceof S||this.controller.signal.aborted)await this.finalizeAborted();else if($ instanceof WZ)this.fail({code:"unknown",message:$.message,retryable:!0}),await this.finalizeMessage("error"),this.finishReason="error",this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its usage limits`,{error:$.cause});else this.fail(this.config.provider.normalizeError($),i($)),await this.finalizeMessage("error"),this.finishReason="error"}if(this.cancelDeadline(),this.limiter)try{await this.limiter.report(this.spent(),!0)}catch($){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record its usage`,{error:$})}this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),this.precompact();let Z=this.finishReason==="error"?this.failure:void 0;if(Z&&this.config.logErrors)this.logFailure(Z);return{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,metered:this.meter.totals(),output:this.output,...Z?{error:Z}:{}}}async resolveToolSchemas(){let Z=[...this.config.registry.values()].filter((z)=>!z.inputSchema);if(Z.length===0)return;let $={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,signal:this.controller.signal},Q=new Map,B=await Promise.all(Z.map(async(z)=>{try{let J=z.tool.inputSchema,H=await J($);x0(H,`The tool "${z.tool.name}"`,"inputSchema"),Q.set(z.tool.name,H);return}catch(J){return`"${z.tool.name}": ${J instanceof Error?J.message:String(J)}`}}));if(this.controller.signal.aborted)throw new S;let X=B.filter((z)=>z!==void 0);if(X.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${X.join("; ")}`,retryable:!1};let G=new Map;for(let[z,J]of this.config.registry)G.set(z,Q.has(z)?{...J,inputSchema:Q.get(z)}:J);let V=(z)=>Q.has(z.name)?JZ(G.get(z.name)):z,W=this.config.providerTools.map((z)=>("tools"in z)?{...z,tools:z.tools.map(V)}:V(z));this.config={...this.config,registry:G,providerTools:W};return}async prepareMemory(){let Z=this.config.memory;if(!Z)return;let $=this.memory,Q=$.writableLabels(),B=$.toolKinds(),X=(z)=>z==="recall"?$.labels.length>0:Q.length>0&&B.length>0,G=new Map;for(let[z,J]of this.config.registry){if(J.namespace!==v){G.set(z,J);continue}if(!X(z))continue;let H=z==="recall"?$.labels:Q,q=BZ(z,{scopes:H,descriptions:$.describeScopes(H),kinds:B});G.set(z,{...J,inputSchema:q})}let V=this.config.providerTools.flatMap((z)=>{if(!("tools"in z)||z.name!==v)return[z];let J=z.tools.filter((H)=>G.has(H.name)).map((H)=>JZ(G.get(H.name)));return J.length>0?[{...z,tools:J}]:[]});this.config={...this.config,registry:G,providerTools:V};let W=this.params.memory?.maxTokens??Z.maxTokens??t0;try{this.memoryBlock=await $.block({maxTokens:W,recall:G.has("recall"),tools:G.has("remember")||G.has("forget")})}catch(z){let J=z instanceof Error?z.message:String(z);this.writeLog(`[gemi/ai] agent "${this.config.name}": the memory store could not be read, so this run has no <memory> block: ${J}`,{error:z})}if(this.controller.signal.aborted)throw new S}spent(){return{tokens:this.usage.totalTokens,steps:this.modelSteps,toolCalls:this.toolCallCount}}failOverLimit(Z){this.fail({code:"usage_limit",message:L0(Z),retryable:!1},{usageLimit:Z}),this.finishReason="error"}fail(Z,$={}){let Q={...Z,...$};this.failure=Q,this.emit({type:"error",error:this.redact(Q,{source:"run",failure:Q})})}redact(Z,$){let Q=V7(this.params.redactError,Z,$,(B)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:B}));return W7(Q,Z),Q}logFailure(Z){let $=`[gemi/ai] agent "${this.config.name}" run failed (${Z.code}${Z.status!==void 0?` ${Z.status}`:""}): ${Z.message}`;this.writeLog($,{error:Z})}logToolFailure(Z,$){let Q=$ instanceof Error?$.message:String($);this.writeLog(`[gemi/ai] agent "${this.config.name}" tool "${String(Z.name)}" threw: ${Q}`,{toolCallId:Z.toolCallId,error:$})}writeLog(Z,$){let Q={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},...this.depth>0?{chain:this.chain}:{},...$},B=!1;try{t.error(Z,Q),B=!0}catch{}if(!B||Bun.env.NODE_ENV==="development")console.error(Z,Q)}async loop(){let Z=Math.max(1,this.config.maxSteps);for(let $=1;$<=Z;$++){if(this.limiter){let z=await this.limiter.check(this.spent(),{steps:1,tokens:1});if(z){this.failOverLimit(z);return}}await this.takeInbox();let Q=this.startMessage(),B=await this.runStep(Q,$);this.modelSteps++,this.lastStep={reason:B.reason,usage:Q.usage},await this.limiter?.report(this.spent());let X=B.error?this.cutCallToModel(Q,B.detail):void 0;if(B.error&&!X){this.fail(B.error,B.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Q.content.filter((z)=>z.type==="tool-call"&&z!==X);if(G.length===0&&!X&&B.emulated&&$<Z){this.forceAgain=B.emulated,await this.finalizeMessage(B.reason);continue}if(G.length===0&&!X){this.finishReason=B.reason,await this.finalizeMessage(B.reason);return}let V=G.length>0?await this.runTools(Q,G,$):[];if(await this.limiter?.report(this.spent()),this.limitHit&&V.length===0){let z=this.limitHit;await this.finalizeMessage(B.reason),this.failOverLimit(z);return}if(V.length>0){if(this.finishReason="awaiting-input",this.depth===0)Q.pending=V;await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:V});return}let W=X?null:await this.closingText(Q,G,$);if(W!==null){if(this.finishReason="stop",await this.finalizeMessage(B.reason),W){let z=this.startMessage();s(z,"text",W),this.emit({type:"text-delta",messageId:z.id,delta:W}),await this.finalizeMessage("stop")}return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(X?"stop":B.reason)}}cutCallToModel(Z,$){let Q=$?.toolArgumentsTooLong;if(!Q||!Q.toolCallId||this.cutCalls>=this.config.cutCallsToModel)return;let B=Z.content.find((X)=>X.type==="tool-call"&&X.toolCallId===Q.toolCallId);if(!B)B={type:"tool-call",toolCallId:Q.toolCallId,name:Q.tool,input:{}},Z.content.push(B);return this.cutCalls++,B.input={},this.emit({type:"tool-call",messageId:Z.id,part:B}),this.addResult(Z,{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"invalid_tool_input",message:`The arguments for "${Q.tool}" were cut off after more than ${Q.limit} characters, so the call did not run. Split the work over smaller calls.`,toolCallId:B.toolCallId,retryable:!0}}),B}async takeInbox(){let Z=this.depth===0?this.params.inbox:void 0;if(!Z)return;let $;try{$=await Z.take()}catch(Q){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not read its inbox`,{error:Q});return}for(let Q of $){if(typeof Q!=="string"||Q.length===0)continue;let B={id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q}],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(B),this.produced.push(B),this.emit({type:"message",message:B}),await this.report(B)}}startMessage(){let Z={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Z,this.history.push(Z),this.produced.push(Z),this.emit({type:"message-start",messageId:Z.id,role:"assistant"}),Z}async finalizeMessage(Z){let $=this.current;if(!$)return;this.current=null;let Q=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Z,Q)$.outputTruncated=!0;for(let B of $.content)if(B.type==="text"||B.type==="reasoning"){if(typeof B.text==="string")B.text=kZ(B.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Z,...Q?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{}}),await this.report($),await this.reportDeferred()}async report(Z){if(!this.params.onMessage)return;try{await this.params.onMessage(Z)}catch{}}async runStep(Z,$){let Q=this.controller.signal,B=this.config.provider;this.stepOffered=void 0;let X=await this.prepareRequest(Z,$);if("error"in X)return{reason:"error",error:X.error};this.stepOffered=X.offered;let V=(X.toolChoice==="required"||typeof X.toolChoice==="object")&&B.capabilities.supportsForcedToolChoice===!1,W=this.forceAgain!==void 0;this.forceAgain=void 0;let z=V?[X.instructions,V$(X.toolChoice)].filter(Boolean).join(`
|
|
24
24
|
|
|
25
25
|
`):X.instructions,J={reason:"stop"},H=new Map,q=[],K=()=>{if(q.length===0)return{};let P=q;return q=[],{toolSearches:P}},Y="",D=B.stream({messages:X.messages,systemPrompt:z,tools:X.tools.length>0?X.tools:void 0,...Y$(this.config,X.instructions,X.tools),...X.toolChoice!==void 0?{toolChoice:X.toolChoice}:{},output:this.config.output?TZ(this.config.output):void 0,reasoning:X.reasoning,maxOutputTokens:X.maxOutputTokens,temperature:this.config.temperature,...this.cutCalls<this.config.cutCallsToModel?{retryToolArgumentsTooLong:!1}:{},signal:Q})[Symbol.asyncIterator]();for(;;){let P=await f(Promise.resolve(D.next()),Q);if(P.done)break;let U=P.value;switch(U.type){case"text-delta":{s(Z,"text",U.delta),this.emit({type:"text-delta",messageId:Z.id,delta:U.delta});break}case"reasoning-delta":{bZ(Z,U.id,U.delta,U.providerMetadata),this.emit({type:"reasoning-delta",messageId:Z.id,delta:U.delta,id:U.id,...U.providerMetadata?{providerMetadata:U.providerMetadata}:{}});break}case"output-delta":{Y+=U.delta,this.emit({type:"output-delta",messageId:Z.id,delta:U.delta,snapshot:R0(Y)});break}case"tool-search":{q.push({namespaces:U.namespaces,loaded:U.loaded,...U.arguments!==void 0?{arguments:U.arguments}:{}}),this.emit({type:"tool-search",loaded:U.loaded});break}case"tool-call-delta":{let L=H.get(U.toolCallId)??{name:U.name,args:""};L.args+=U.argsDelta,L.name=U.name||L.name,L.namespace=U.namespace||L.namespace,H.set(U.toolCallId,L),this.emit({type:"tool-call",messageId:Z.id,part:{type:"tool-call",toolCallId:U.toolCallId,name:L.name,input:R0(L.args),partial:!0,...L.namespace?{namespace:L.namespace}:{}}});break}case"tool-call-discard":{for(let L of U.toolCallIds)H.delete(L);this.emit({type:"tool-call-discard",messageId:Z.id,toolCallIds:U.toolCallIds});break}case"tool-call":{let L=U.namespace||H.get(U.toolCallId)?.namespace||(this.config.registry.get(U.name)?.namespace===w?w:void 0);H.delete(U.toolCallId);let O={type:"tool-call",toolCallId:U.toolCallId,name:U.name,input:B7(U.args),...L?{namespace:L}:{},...K()};Z.content.push(O),this.emit({type:"tool-call",messageId:Z.id,part:O});break}case"finish":{if(this.usage=I(this.usage,U.usage),ZZ(U.model??B.model,U.usage),Z.usage=I(Z.usage??x(),U.usage),!J.error)J={reason:U.reason};break}case"error":{J={reason:"error",error:U.error,detail:{...i(U),...U.toolArgumentsTooLong?{toolArgumentsTooLong:U.toolArgumentsTooLong}:{}}};break}case"file-rejected":{this.markFileRejected(U.fileId,U.message,i(U));break}case"retry":{this.emit({type:"retry",messageId:Z.id,attempt:U.attempt,maxRetries:U.maxRetries,code:U.error.code,delayMs:U.delayMs,...U.remainingMs!==void 0?{remainingMs:U.remainingMs}:{}});let L=this.params.onProviderRetry;if(L){let{type:O,...R}=U,E=(_)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" onProviderRetry threw`,{error:_});try{let _=L({...R,runId:this.runId,agent:this.config.name,step:$});if(_ instanceof Promise)_.catch(E)}catch(_){E(_)}}break}}}for(let[P,U]of H){let L={type:"tool-call",toolCallId:P,name:U.name,input:B7(U.args),...U.namespace?{namespace:U.namespace}:{},...K()};Z.content.push(L),this.emit({type:"tool-call",messageId:Z.id,part:L})}let j=J.reason==="length";if(j)this.outputTruncated=!0;if(this.config.output&&Y&&!J.error&&!j){let P=EZ(this.config.output,Y);if(P.ok===!0)this.output=P.value,Z.content.push({type:"output",value:P.value,text:Y});else this.emit({type:"error",error:P.error})}if(V&&!W&&!J.error)J.emulated=X.toolChoice;return J}compactJobParams(Z,$){let Q=this.config.contextWindow;if(!Q?.compact||!this.params.threadId||this.depth!==0)return;let B=Q.compact===!0?{}:Q.compact;return{history:Z,stored:this.history.filter((X)=>X!==$),window:Q,compact:B,threadId:this.params.threadId,provider:this.config.provider,store:B.store||this.params.summaryStore||w4,skills:this.skillNames()}}skillNames(){let Z=new Set;for(let[$,Q]of this.config.registry)if(Q.namespace===w)Z.add($);return Z}precompact(){let Z=this.config.contextWindow;if(!Z?.compact||Z.compact!==!0&&Z.compact.background===!1)return;try{let $=this.compactJobParams(this.historyForProvider(void 0),void 0);if($)y4($)}catch{}}async prepareRequest(Z,$){let Q=this.historyForProvider(Z),B=this.config.contextWindow,X=this.compactJobParams(Q,Z),G=!B?Q:X?await h4({...X,signal:this.controller.signal,onUsage:(Y)=>{this.usage=I(this.usage,Y)},memo:this.compactMemo}):GZ(Q,B).messages,V=await this.systemPrompt(),W=this.config.reasoning,z=this.config.maxOutputTokens,J,H;for(let Y of this.config.prepareStep){let F;try{F=await Y({step:$,messages:[...G],history:[...Q],instructions:V,reasoning:W,maxOutputTokens:z,activeTools:J,toolChoice:H,body:this.params.body??{},usage:this.usage,...this.lastStep?.usage?{lastStepUsage:this.lastStep.usage}:{},...this.lastStep?{lastFinishReason:this.lastStep.reason}:{},runId:this.runId,threadId:this.params.threadId,agent:this.config.name,depth:this.depth,context:this.context,signal:this.controller.signal})}catch(D){if(D instanceof S||this.controller.signal.aborted)throw D;return{error:{code:"unknown",message:`prepareStep threw: ${D instanceof Error?D.message:String(D)}`,retryable:!1}}}if(!F)continue;if(F.messages!==void 0){if(!Array.isArray(F.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};G=F.messages}if(F.instructions!==void 0)V=F.instructions||void 0;if(F.reasoning!==void 0)W=F.reasoning;if(F.maxOutputTokens!==void 0)z=F.maxOutputTokens;if(F.activeTools!==void 0)J=F.activeTools;if(F.toolChoice!==void 0)H=F.toolChoice}if(this.forceAgain&&H===void 0)H=this.forceAgain;let q=this.config.providerTools,K=this.config.offered;if(J)try{({providerTools:q,offered:K}=N7(this.config,J,`prepareStep (step ${$})`))}catch(Y){return{error:{code:"unknown",message:Y instanceof Error?Y.message:String(Y),retryable:!1}}}if(H!==void 0){let Y=W$(H,q,K,this.config.registry);if(Y)return{error:{code:"unknown",message:`prepareStep ${Y}`,retryable:!1}}}return{messages:G,instructions:V,reasoning:W,maxOutputTokens:z,tools:q,offered:J?K:void 0,toolChoice:H}}async systemPrompt(){let Z=[this.config.instructions,this.params.instructions,this.memoryBlock].filter(($)=>Boolean($&&$.trim()));return Z.length>0?Z.join(`
|
|
26
26
|
|
|
@@ -45,4 +45,4 @@ ${hZ(Z)}
|
|
|
45
45
|
Correct these problems and give the whole answer again.`}function A$(Z,$,Q){let B=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,X={...Q,generateId:Z,error:$},G=!1;try{t.error(B,X),G=!0}catch{}if(!G||Bun.env.NODE_ENV==="development")console.error(B,X)}async function S$(Z,$){let Q=Z.messages??[];if(Q.length===0&&!Z.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let B=[...Q];if(Z.prompt)B.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Z.prompt}],createdAt:new Date().toISOString()});let X={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},G=Z.signal??new AbortController().signal,V=x(),W="stop",z,J={},H="",q=Z.onPartial?new fZ:void 0;try{let D=Z.provider.stream({messages:[...B],systemPrompt:Z.instructions?.trim()?Z.instructions:void 0,output:TZ(Z.output),reasoning:Z.reasoning,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,signal:Z.signal})[Symbol.asyncIterator]();try{for(;;){let j=await f(Promise.resolve(D.next()),G);if(j.done)break;let P=j.value;switch(P.type){case"output-delta":if(H+=P.delta,q){let U=q.push(P.delta);if(q.changed||U.length>0)T$(Z.onPartial,q.snapshot(),{attempt:$,closed:U})}break;case"text-delta":s(X,"text",P.delta);break;case"reasoning-delta":bZ(X,P.id,P.delta,P.providerMetadata);break;case"finish":if(V=I(V,P.usage),ZZ(P.model??Z.provider.model,P.usage),!z)W=P.reason;break;case"error":W="error",z=P.error,J=i(P);break;case"retry":{let{type:U,...L}=P;try{let O=Z.onProviderRetry?.(L);if(O instanceof Promise)O.catch(()=>{})}catch{}break}}}}finally{if(G.aborted)Promise.resolve(D.return?.()).catch(()=>{})}}catch(F){if(F instanceof S||G.aborted)W="aborted",z=A7(G);else W="error",z=Z.provider.normalizeError(F),J=i(F)}let K=!1,Y;if(!z)if(W==="length")z={code:"invalid_output",message:"The model ran out of output tokens before finishing its structured answer, so it was cut off. Raise maxOutputTokens, or ask for a shorter answer.",retryable:!0};else if(!H.trim())z={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let F=EZ(Z.output,H);if(F.ok===!0)K=!0,Y=F.value;else z=F.error}if(K)X.content.push({type:"output",value:Y,text:H});else if(H)s(X,"text",H);for(let F of X.content)if((F.type==="text"||F.type==="reasoning")&&typeof F.text==="string")F.text=kZ(F.text);if(X.finishReason=W,X.usage=V,B.push(X),K)return{ok:!0,output:Y,messages:B,usage:V,finishReason:W};return{ok:!1,error:{...z,...J},messages:B,usage:V,finishReason:W}}function T$(Z,$,Q){let B=(X)=>{let G=`[gemi/ai] generate() onPartial threw: ${X instanceof Error?X.message:String(X)}`;try{t.warning(G,{error:X})}catch{console.error(G,X)}};try{let X=Z($,Q);if(X instanceof Promise)X.catch(B)}catch(X){B(X)}}function A7(Z){return Z.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}var f7=Symbol.for("gemi.ai.JobHandle");class h7{id;toolCallId;summary;deadlineAt;[f7]=!0;constructor(Z,$,Q,B){this.id=Z;this.toolCallId=$;this.summary=Q;this.deadlineAt=B}}function H7(Z){return typeof Z==="object"&&Z!==null&&Z[f7]===!0}class b0 extends C{code="jobs_require_thread";constructor(Z){super(Z,{retryable:!1});this.name="JobsRequireThreadError"}}var g=new eZ,gZ=new Set,E$=["waiting","running","ok","error"],qZ=new Set,yZ=new Map,u={get store(){return g},use(Z){g=Z},get(Z){return g.get(Z)},onSettled(Z){return gZ.add(Z),()=>{gZ.delete(Z)}},async settle(Z,$){return a(g,Z,$)},async fail(Z,$){return a(g,Z,{error:$})},async sweep(Z={}){let $=g,Q=Z.limit??100,B=await k$($),X=0;for(let G of await $.overdue(B,Q))if(await b$($,G))X++;if($.waiting)for(let G of await $.waiting(Q))try{await f0($,G)}catch(V){console.error(`Could not advance waiting background job ${G.id}.`,V)}return X},async start(Z,$,Q={}){let B=await v0(S7(Q,Z.name),{job:Z,args:$,options:Q});return dZ(B)},async track(Z={}){let $=await v0(S7(Z,"job"),{job:null,args:void 0,options:Z});return dZ($)},async cancel(Z,$={}){let Q=g,B=await Q.get(Z);if(!B||d(B.state))return!1;if($.silent)qZ.add(Z);if(!await Q.transition(Z,["waiting","running"],{state:"error",error:{code:"cancelled",message:$.reason??`The background job for "${B.toolName}" was cancelled.`,...B.toolCallId?{toolCallId:B.toolCallId}:{},retryable:!1}}))return qZ.delete(Z),!1;return await cZ(Q,Z),!0},async message(Z,$){let Q=g;if(!Q.appendInbox)throw Error("AgentJobs.message needs a job store with an inbox (appendInbox and takeInbox).");return Q.appendInbox(Z,$)},onSettledBatch(Z,$={}){let Q=new d7(Z,$),B=u.onSettled((G)=>Q.add(G)),X=()=>{B(),Q.stop()};return X.flush=(G,V)=>Q.flush(G,V?.now===!0),X}};function S7(Z,$){return{threadId:Z.threadId??"",runId:"",toolCallId:"",toolName:Z.name??$,owner:Z.owner??null,attachmentScope:Z.attachmentScope??null,deadlineMs:Z.deadlineMs??y7}}async function v0(Z,$){let Q=u.store,{job:B,args:X,options:G}=$,V=Z.deadlineMs;if(!Number.isFinite(V)||V<=0)throw new C(`A job's deadlineMs must be a positive number; got ${V}.`);let W=G.after?[...new Set(G.after)]:[],z=!1;if(W.length>0){if(!B)throw new C("A tracked job cannot wait for others: `after` is only for `start`.",{retryable:!1});if(!Q.waitingOn)throw Error("`after` needs a job store that can list waiting jobs (waitingOn).");for(let q of W){let K=await Q.get(q);if(!K)throw new C(`The job waits for ${q}, which does not exist.`,{retryable:!1});if(K.state==="error")throw new C(`The job waits for ${q}, which did not finish (${K.error?.code??"error"}). Leave it out, or start that work again.`,{retryable:!1});if(K.state!=="ok")z=!0}}if(B&&(B.name==="unset"||!B.name))throw Error("Cannot start an AgentJob with no `static name`.");let J=async()=>{let q=await Q.create({id:`ajob_${crypto.randomUUID()}`,threadId:Z.threadId,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:Z.owner,job:B?B.name:null,...G.summary!==void 0?{summary:uZ(G.summary,Z)}:{},attachmentScope:Z.attachmentScope,deadlineMs:V,...W.length>0?{after:W}:{},...G.batch!==void 0?{batch:G.batch}:{},...z?{state:"waiting",queued:{args:uZ(X,Z),deadlineMs:V}}:{}});if(B&&!z)try{await g7(B,{jobId:q.id,args:X})}catch(K){if(Q.transaction)throw K;throw await Q.transition(q.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${Z.toolName}" could not be queued.`,...Z.toolCallId?{toolCallId:Z.toolCallId}:{},retryable:!0}}).catch(()=>{}),K}return q},H=Q.transaction?await Q.transaction(J):await J();if(z)await f0(Q,H);return await Q.get(H.id)??H}async function k$(Z){return Z.now?await Z.now():Date.now()}async function b$(Z,$){let Q=await Z.transition($.id,["running"],{state:"error",error:{code:"timeout",message:`The background job for "${$.toolName}" did not finish before its deadline, so it was given up on. Its result, if it ever arrives, is ignored.`,toolCallId:$.toolCallId,retryable:!0}});if(Q)await cZ(Z,$.id);return Q}async function cZ(Z,$){yZ.get($)?.abort(new C("The background job was settled while it ran."));try{await v$(Z,$)}catch(Q){console.error(`Could not start or cancel the jobs waiting for background job ${$}.`,Q)}f$(Z,$)}async function v$(Z,$){if(!Z.waitingOn)return;for(let Q of await Z.waitingOn($))await f0(Z,Q)}async function f0(Z,$){let Q=$.after??[],B=await Promise.all(Q.map((z)=>Z.get(z))),X=Q.find((z,J)=>B[J]===null),G=B.find((z)=>z?.state==="error");if(X!==void 0||G){let z=G?.error?.code==="cancelled",J=G?.id??X;if(await Z.transition($.id,["waiting"],{state:"error",error:{code:z?"cancelled":"dependency_failed",message:G?`It waited for ${J}, which ${z?"was cancelled":"failed"}, so it did not start.`:`It waited for ${J}, which can no longer be found, so it did not start.`,...$.toolCallId?{toolCallId:$.toolCallId}:{},retryable:!1}})){if(qZ.has(J))qZ.add($.id);await cZ(Z,$.id)}return}if(B.some((z)=>z.state!=="ok"))return;if(!await Z.transition($.id,["waiting"],{state:"running",...$.queued?{deadlineMs:$.queued.deadlineMs}:{}}))return;let W=$.job?w$($.job):void 0;if(!W){if($.job===null)return;await a(Z,$.id,{error:{code:"tool_error",message:`The background job ${$.job} is not registered with the queue, so it could not start.`,retryable:!1}});return}try{await g7(W,{jobId:$.id,args:$.queued?.args})}catch(z){console.error(`Could not queue background job ${$.id} after its dependencies.`,z),await a(Z,$.id,{error:{code:"tool_error",message:`The background job for "${$.toolName}" could not be queued.`,retryable:!0}})}}function w$(Z){try{return e(w0).jobs[Z]}catch{return}}function f$(Z,$){if(qZ.delete($))return;if(gZ.size===0)return;let Q=[...gZ];(async()=>{let B=await Z.get($);if(!B||!d(B.state))return;for(let X of Q)try{await X(B)}catch(G){console.error(`An AgentJobs.onSettled listener failed for background job ${$}.`,G)}})().catch((B)=>{console.error(`Could not read background job ${$} for its onSettled listeners.`,B)})}async function a(Z,$,Q){let B=await Z.get($);if(!B||B.state!=="running")return!1;let X=Q.usage?I(B.usage??x(),Q.usage):void 0,G="error"in Q?await Z.transition($,["running"],{state:"error",error:h$(B,Q.error),...X?{usage:X}:{}}):await Z.transition($,["running"],{state:"ok",output:uZ(Q.output,B),...X?{usage:X}:{}});if(G)await cZ(Z,$);return G}function h$(Z,$){if(typeof $==="string")return{code:"tool_error",message:$,toolCallId:Z.toolCallId,retryable:!0};if($ instanceof Error){let Q={code:"tool_error",message:$.message,toolCallId:Z.toolCallId,retryable:$ instanceof C?$.retryable:!0};if(!($ instanceof C))console.error(`The background job ${Z.job??"(tracked)"} for "${Z.toolName}" failed.`,$);return k7(Q,{source:"tool",toolName:Z.toolName,cause:$})}return{code:$.code??"tool_error",message:String($.message),toolCallId:Z.toolCallId,retryable:$.retryable??!0}}function uZ(Z,$){if(Z===void 0)return null;try{return JSON.parse(JSON.stringify(Z))}catch(Q){throw Error(`The output of the background job for "${$.toolName}" is not JSON: ${String(Q)}`)}}var y7=3600000;function Y7(Z){let $=null,Q=(B,X,G={})=>{if(Z.async===void 0)throw new C(`"${Z.toolName}" called ctx.jobs, but the tool does not declare \`async\`. Add \`async: { deadlineMs }\` to its definition.`,{retryable:!1});if(!Z.jobs||!Z.threadId)throw new b0(`"${Z.toolName}" can only run in the background on a conversation the server keeps (a turn with a threadId), and this one has none.`);if(Z.depth>0)throw new b0(`"${Z.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if($)throw new C(`"${Z.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let V=G.deadlineMs??Z.async.deadlineMs??y7;if(!Number.isFinite(V)||V<=0)throw new C(`A job's deadlineMs must be a positive number; got ${V}.`);let{jobs:W,threadId:z}=Z;return $=(async()=>{let J=(await u.store.listForThread(z,{limit:50})).find((q)=>q.toolCallId===Z.toolCallId);if(J)return dZ(J);let H=await v0({threadId:z,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:W.owner,attachmentScope:Z.attachments?.scopeKey??null,deadlineMs:V},{job:B,args:X,options:G});return dZ(H)})(),$};return{start:(B,X,G)=>Q(B,X,G),track:(B)=>Q(null,void 0,B)}}function dZ(Z){return new h7(Z.id,Z.toolCallId,Z.summary,Z.deadlineAt)}function g7(Z,$){return e(w0).push(Z,JSON.stringify([$]))}class y$ extends b7{attachments=w7;attachmentStorage=E7;cancelCheckMs=5000;constructor(){super();let Z=this.run;this.run=($)=>this.$runEnvelope($,Z)}onDeadletter(Z,...$){let Q=$[0];if(!Q?.jobId)return;a(u.store,Q.jobId,{error:Z}).catch((B)=>{console.error(`Could not record the failure of background job ${Q.jobId}.`,B)})}async $runEnvelope(Z,$){let Q=u.store,B=await Q.get(Z.jobId);if(!B||B.state!=="running")return;let X=new AbortController;yZ.set(B.id,X);let G=this.cancelCheckMs>0?setInterval(()=>{Q.get(B.id).then((z)=>{if(z&&z.state!=="running"&&!X.signal.aborted)X.abort(new C("The background job was cancelled."))}).catch(()=>{})},this.cancelCheckMs):void 0;G?.unref?.();let V=new u7(B,this,X.signal),W;try{W=await $.call(this,Z.args,V)}catch(z){await T7(Q,B.id,V.usage);let J=await Q.get(B.id).catch(()=>null);if(X.signal.aborted||J&&J.state!=="running")return;throw z}finally{if(clearInterval(G),yZ.get(B.id)===X)yZ.delete(B.id)}if(this.$outcome)return await T7(Q,B.id,V.usage),W;return await a(Q,B.id,{output:W,usage:V.usage}),W}}async function T7(Z,$,Q){if(Q.totalTokens===0&&Q.inputTokens===0&&Q.outputTokens===0)return;let B=await Z.get($);if(!B)return;await Z.transition($,E$,{usage:I(B.usage??x(),Q)}).catch(()=>{})}class u7{signal;id;threadId;toolCallId;toolName;owner;summary;after;batch;checkpointed;inbox;usage=x();attachments;constructor(Z,$,Q){this.signal=Q;this.id=Z.id,this.after=Z.after??[],this.batch=Z.batch,this.checkpointed=Z.checkpoint;let B=u.store;this.inbox={take:async()=>B.takeInbox?await B.takeInbox(Z.id):[]},this.threadId=Z.threadId,this.toolCallId=Z.toolCallId,this.toolName=Z.toolName,this.owner=Z.owner,this.summary=Z.summary;let X=Z.attachmentScope?new v7($.attachments,$.attachmentStorage,{key:Z.attachmentScope}):null,G=()=>{if(!X)throw new vZ("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return X};this.attachments={put:(V,W={})=>G().put(V,W),get:(V)=>G().get(V),read:(V)=>G().read(V),file:(V)=>G().file(V)}}async checkpoint(Z){return u.store.transition(this.id,["running"],{checkpoint:uZ(Z,this)})}generate(Z){return YZ(Z,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:($)=>{this.usage=I(this.usage,$.usage)}})}async generateImage(Z,$){let{name:Q,...B}=$,X=await Z.generate({...B,signal:this.signal});return this.park(Z,X,Q)}async editImage(Z,$){let{name:Q,images:B,mask:X,...G}=$,V=async(z)=>typeof z==="string"?await this.attachments.file(z):z,W=await Z.edit({...G,images:await Promise.all(B.map(V)),...X?{mask:await V(X)}:{},signal:this.signal});return this.park(Z,W,Q)}async park(Z,$,Q){this.usage=I(this.usage,$.usage);let B=$.mimeType==="image/jpeg"?"jpg":"png";return{attachment:await this.attachments.put($.image,{name:Q??`${Z.name}.${B}`,mimeType:$.mimeType}),size:$.size,mimeType:$.mimeType,usage:$.usage}}}class d7{listener;options;groups=new Map;stopped=!1;delayMs;maxDelayMs;keyOf;constructor(Z,$){this.listener=Z;this.options=$;this.delayMs=Math.max(0,$.delayMs??1000),this.maxDelayMs=Math.max(this.delayMs,$.maxDelayMs??this.delayMs*10),this.keyOf=$.key??((Q)=>Q.threadId)}add(Z){if(this.stopped)return;let $=this.keyOf(Z),Q=this.groups.get($);if(!Q)Q={jobs:new Map,first:void 0,timer:void 0,busy:!1,again:!1},this.groups.set($,Q);Q.jobs.set(Z.id,Z),Q.first??=Date.now(),this.schedule($,!1)}flush(Z,$){for(let Q of Z===void 0?[...this.groups.keys()]:[Z])if(this.groups.has(Q))this.schedule(Q,$)}stop(){this.stopped=!0;for(let Z of this.groups.values())clearTimeout(Z.timer);this.groups.clear()}schedule(Z,$){let Q=this.groups.get(Z);if(!Q)return;if(Q.busy){Q.again=!0;return}clearTimeout(Q.timer);let B=Q.first===void 0?this.delayMs:Q.first+this.maxDelayMs-Date.now(),X=$?0:Math.max(0,Math.min(this.delayMs,B));Q.timer=setTimeout(()=>void this.run(Z),X),Q.timer.unref?.()}async run(Z){let $=this.groups.get(Z);if(!$||this.stopped)return;$.timer=void 0,$.busy=!0;try{for(;;){$.again=!1;let Q=await this.ready([...$.jobs.values()]);if(Q.length===0)break;let B=this.options.hold?await this.options.hold(Q,Z):!1;if(B===!0)break;if(typeof B==="number"&&B>0){setTimeout(()=>this.flush(Z,!0),B).unref?.();break}for(let X of Q)$.jobs.delete(X.id);try{await this.listener(Q,Z)}catch(X){console.error(`An AgentJobs.onSettledBatch listener failed for ${Z}.`,X)}if(this.stopped)return}}catch(Q){console.error(`Could not report the settled background jobs of ${Z}.`,Q)}finally{if($.busy=!1,$.jobs.size===0){if(this.groups.get(Z)===$)this.groups.delete(Z)}else if($.first=void 0,$.again)this.schedule(Z,!1)}}async ready(Z){let $=u.store,Q=new Map,B=[];for(let X of Z){if(X.batch===void 0||!$.listBatch){B.push(X);continue}let G=Q.get(X.batch);if(!G)G=new Map((await $.listBatch(X.batch)).map((J)=>[J.id,J])),Q.set(X.batch,G);let V=G,W=(J,H,q=new Set)=>{if(q.has(J.id))return!1;q.add(J.id);let K=J.after??[];return K.includes(H)||K.some((Y)=>{let F=V.get(Y);return F!==void 0&&W(F,H,q)})};if(![...V.values()].some((J)=>J.id!==X.id&&!d(J.state)&&!W(J,X.id)))B.push(X)}return B}}
|
|
46
46
|
export{d0 as ic,c7 as jc,p7 as kc,iZ as lc,XZ as mc,T as nc,sZ as oc,ZZ as pc,n7 as qc,l$ as rc,i$ as sc,d as tc,eZ as uc,h7 as vc,H7 as wc,b0 as xc,u as yc,k$ as zc,b$ as Ac,y7 as Bc,Y7 as Cc,y$ as Dc,t0 as Ec,r0 as Fc,X9 as Gc,G9 as Hc,FZ as Ic,n as Jc,z0 as Kc,p as Lc,V0 as Mc,J9 as Nc,v as Oc,J1 as Pc,RZ as Qc,_Z as Rc,F1 as Sc,N9 as Tc,R9 as Uc,_9 as Vc,GZ as Wc,A9 as Xc,E9 as Yc,b9 as Zc,v9 as _c,v4 as $c,f9 as ad,w4 as bd,C1 as cd,N1 as dd,c4 as ed,m4 as fd,s9 as gd,o as hd,h as id,wZ as jd,K7 as kd,w as ld,i1 as md,P7 as nd,HZ as od,j7 as pd,S0 as qd,J$ as rd,o1 as sd,d4 as td,YZ as ud};
|
|
47
47
|
|
|
48
|
-
//# debugId=
|
|
48
|
+
//# debugId=26C987CE74E47F1764756E2164756E21
|