gemi 0.131.0 → 0.133.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/AgentController.d.ts +73 -0
- package/dist/ai/AgentController.d.ts.map +1 -1
- package/dist/ai/AgentProvider.d.ts +25 -0
- package/dist/ai/AgentProvider.d.ts.map +1 -1
- package/dist/ai/VoiceBridge.d.ts +365 -0
- package/dist/ai/VoiceBridge.d.ts.map +1 -0
- package/dist/ai/index.d.ts +13 -0
- package/dist/ai/index.d.ts.map +1 -1
- package/dist/ai/index.js +18 -18
- package/dist/ai/index.js.map +11 -6
- package/dist/ai/providers/endpoints.d.ts +19 -0
- package/dist/ai/providers/endpoints.d.ts.map +1 -1
- package/dist/ai/providers/realtime.d.ts +272 -0
- package/dist/ai/providers/realtime.d.ts.map +1 -0
- package/dist/ai/providers/sideband.d.ts +254 -0
- package/dist/ai/providers/sideband.d.ts.map +1 -0
- package/dist/ai/runtime.d.ts.map +1 -1
- package/dist/ai/types.d.ts +15 -0
- package/dist/ai/types.d.ts.map +1 -1
- package/dist/ai/voice/index.d.ts +23 -0
- package/dist/ai/voice/index.d.ts.map +1 -0
- package/dist/ai/voice/index.js +433 -0
- package/dist/ai/voice/index.js.map +1 -0
- package/dist/ai/voice/state.d.ts +34 -0
- package/dist/ai/voice/state.d.ts.map +1 -0
- package/dist/ai/voice/useVoiceSession.d.ts +82 -0
- package/dist/ai/voice/useVoiceSession.d.ts.map +1 -0
- package/dist/ai/voice/voiceCall.d.ts +57 -0
- package/dist/ai/voice/voiceCall.d.ts.map +1 -0
- package/dist/ai/voice/wire.d.ts +66 -0
- package/dist/ai/voice/wire.d.ts.map +1 -0
- package/dist/ai/voiceConfig.d.ts +70 -0
- package/dist/ai/voiceConfig.d.ts.map +1 -0
- package/dist/ai/voiceMcp.d.ts +89 -0
- package/dist/ai/voiceMcp.d.ts.map +1 -0
- package/dist/ai/voiceStore.d.ts +52 -0
- package/dist/ai/voiceStore.d.ts.map +1 -0
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-4gmhx2ba.js → chunk-0eamc2tr.js} +2 -2
- package/dist/{chunk-4gmhx2ba.js.map → chunk-0eamc2tr.js.map} +1 -1
- package/dist/{chunk-2x0n3ze1.js → chunk-0gg4e94v.js} +2 -2
- package/dist/{chunk-2x0n3ze1.js.map → chunk-0gg4e94v.js.map} +1 -1
- package/dist/{chunk-p642ja42.js → chunk-0rhf4g12.js} +3 -3
- package/dist/{chunk-p642ja42.js.map → chunk-0rhf4g12.js.map} +1 -1
- package/dist/{chunk-dxm5gxqk.js → chunk-1awxdnb6.js} +1 -1
- package/dist/{chunk-2senwsdq.js → chunk-2cnawkke.js} +12 -12
- package/dist/{chunk-2senwsdq.js.map → chunk-2cnawkke.js.map} +3 -3
- package/dist/{chunk-fxm8fqh9.js → chunk-33hdxe7v.js} +1 -1
- package/dist/{chunk-63xekerg.js → chunk-3g5q0cj5.js} +2 -2
- package/dist/{chunk-63xekerg.js.map → chunk-3g5q0cj5.js.map} +1 -1
- package/dist/{chunk-xjs72pb0.js → chunk-3h37f124.js} +2 -2
- package/dist/{chunk-xjs72pb0.js.map → chunk-3h37f124.js.map} +1 -1
- package/dist/{chunk-65fq5a9d.js → chunk-4278e429.js} +2 -2
- package/dist/{chunk-65fq5a9d.js.map → chunk-4278e429.js.map} +1 -1
- package/dist/chunk-47e7fbsp.js +5 -0
- package/dist/{chunk-mvka90rq.js.map → chunk-47e7fbsp.js.map} +1 -1
- package/dist/{chunk-p6b0cyf8.js → chunk-4pvv8qs0.js} +2 -2
- package/dist/{chunk-p6b0cyf8.js.map → chunk-4pvv8qs0.js.map} +1 -1
- package/dist/{chunk-rjyw1thg.js → chunk-4t41m5f1.js} +2 -2
- package/dist/{chunk-rjyw1thg.js.map → chunk-4t41m5f1.js.map} +1 -1
- package/dist/{chunk-f21v4n2v.js → chunk-53rr32zm.js} +1 -1
- package/dist/{chunk-xhvknqvn.js → chunk-5pdgh9a1.js} +2 -2
- package/dist/{chunk-xhvknqvn.js.map → chunk-5pdgh9a1.js.map} +1 -1
- package/dist/{chunk-e4ay1vg9.js → chunk-65j32dtn.js} +2 -2
- package/dist/{chunk-e4ay1vg9.js.map → chunk-65j32dtn.js.map} +1 -1
- package/dist/{chunk-jxvec7jc.js → chunk-6fr6j338.js} +2 -2
- package/dist/{chunk-jxvec7jc.js.map → chunk-6fr6j338.js.map} +1 -1
- package/dist/{chunk-jd1afbrs.js → chunk-6hz63ts4.js} +4 -4
- package/dist/{chunk-jd1afbrs.js.map → chunk-6hz63ts4.js.map} +1 -1
- package/dist/{chunk-4z0rt6ws.js → chunk-6qty7at2.js} +2 -2
- package/dist/{chunk-4z0rt6ws.js.map → chunk-6qty7at2.js.map} +1 -1
- package/dist/{chunk-pzb3agv9.js → chunk-7nxnyw7x.js} +2 -2
- package/dist/{chunk-pzb3agv9.js.map → chunk-7nxnyw7x.js.map} +1 -1
- package/dist/{chunk-7n0zn5h4.js → chunk-8ryrjtn0.js} +2 -2
- package/dist/{chunk-7n0zn5h4.js.map → chunk-8ryrjtn0.js.map} +1 -1
- package/dist/{chunk-c1gq2ttb.js → chunk-8sde8337.js} +2 -2
- package/dist/{chunk-c1gq2ttb.js.map → chunk-8sde8337.js.map} +1 -1
- package/dist/{chunk-cggywjzz.js → chunk-99a4e6zf.js} +2 -2
- package/dist/{chunk-cggywjzz.js.map → chunk-99a4e6zf.js.map} +1 -1
- package/dist/chunk-b6yb3svm.js +6 -0
- package/dist/{chunk-539w9yt3.js.map → chunk-b6yb3svm.js.map} +2 -2
- package/dist/{chunk-822p54vc.js → chunk-beb265c9.js} +2 -2
- package/dist/{chunk-822p54vc.js.map → chunk-beb265c9.js.map} +1 -1
- package/dist/{chunk-hdgbh8hn.js → chunk-cxsvzqd4.js} +2 -2
- package/dist/{chunk-hdgbh8hn.js.map → chunk-cxsvzqd4.js.map} +1 -1
- package/dist/{chunk-pahr13xg.js → chunk-dt95z6et.js} +2 -2
- package/dist/{chunk-pahr13xg.js.map → chunk-dt95z6et.js.map} +1 -1
- package/dist/{chunk-hr8annr1.js → chunk-feajsgns.js} +2 -2
- package/dist/{chunk-hr8annr1.js.map → chunk-feajsgns.js.map} +1 -1
- package/dist/{chunk-2tda49mv.js → chunk-ff60bzvf.js} +2 -2
- package/dist/{chunk-2tda49mv.js.map → chunk-ff60bzvf.js.map} +1 -1
- package/dist/{chunk-b00z33zg.js → chunk-gng5e7pd.js} +1 -1
- package/dist/{chunk-mz73066c.js → chunk-gqgpwb88.js} +2 -2
- package/dist/{chunk-mz73066c.js.map → chunk-gqgpwb88.js.map} +1 -1
- package/dist/{chunk-h0xye69a.js → chunk-ha15x5ns.js} +2 -2
- package/dist/{chunk-h0xye69a.js.map → chunk-ha15x5ns.js.map} +1 -1
- package/dist/{chunk-d5g1caxb.js → chunk-hb9hm8za.js} +3 -3
- package/dist/{chunk-d5g1caxb.js.map → chunk-hb9hm8za.js.map} +1 -1
- package/dist/{chunk-8fvt7kys.js → chunk-hf492gg2.js} +1 -1
- package/dist/{chunk-fgtr9cds.js → chunk-hj88dcss.js} +3 -3
- package/dist/{chunk-fgtr9cds.js.map → chunk-hj88dcss.js.map} +1 -1
- package/dist/{chunk-hnf11jhc.js → chunk-j5g7qc5f.js} +2 -2
- package/dist/{chunk-hnf11jhc.js.map → chunk-j5g7qc5f.js.map} +1 -1
- package/dist/{chunk-e1fhy2h5.js → chunk-jgx8ggbz.js} +2 -2
- package/dist/{chunk-e1fhy2h5.js.map → chunk-jgx8ggbz.js.map} +1 -1
- package/dist/{chunk-35zw2s61.js → chunk-jx2mgvvt.js} +3 -3
- package/dist/{chunk-35zw2s61.js.map → chunk-jx2mgvvt.js.map} +1 -1
- package/dist/{chunk-w26cw41m.js → chunk-jx5zx48j.js} +2 -2
- package/dist/{chunk-w26cw41m.js.map → chunk-jx5zx48j.js.map} +1 -1
- package/dist/{chunk-z1gjgr1c.js → chunk-jy9dkgt0.js} +2 -2
- package/dist/{chunk-z1gjgr1c.js.map → chunk-jy9dkgt0.js.map} +1 -1
- package/dist/{chunk-7j48ymk1.js → chunk-k2xeskp6.js} +2 -2
- package/dist/{chunk-7j48ymk1.js.map → chunk-k2xeskp6.js.map} +1 -1
- package/dist/{chunk-jxmc33m9.js → chunk-ka991yx4.js} +2 -2
- package/dist/{chunk-jxmc33m9.js.map → chunk-ka991yx4.js.map} +1 -1
- package/dist/{chunk-65s63bdh.js → chunk-krk880my.js} +2 -2
- package/dist/{chunk-65s63bdh.js.map → chunk-krk880my.js.map} +1 -1
- package/dist/{chunk-x4yq0c9v.js → chunk-m9vwg9j1.js} +3 -3
- package/dist/{chunk-x4yq0c9v.js.map → chunk-m9vwg9j1.js.map} +1 -1
- package/dist/{chunk-x07rp3fc.js → chunk-mpqvmge4.js} +1 -1
- package/dist/{chunk-n7sbwpce.js → chunk-mw7ft5bs.js} +2 -2
- package/dist/{chunk-n7sbwpce.js.map → chunk-mw7ft5bs.js.map} +1 -1
- package/dist/{chunk-v5esvs66.js → chunk-njpnstck.js} +2 -2
- package/dist/{chunk-v5esvs66.js.map → chunk-njpnstck.js.map} +1 -1
- package/dist/{chunk-p320fd3g.js → chunk-p82868xx.js} +2 -2
- package/dist/{chunk-p320fd3g.js.map → chunk-p82868xx.js.map} +1 -1
- package/dist/{chunk-jbd723h1.js → chunk-pm8wjatv.js} +3 -3
- package/dist/{chunk-jbd723h1.js.map → chunk-pm8wjatv.js.map} +1 -1
- package/dist/{chunk-t227jn4b.js → chunk-q15f5g86.js} +2 -2
- package/dist/{chunk-t227jn4b.js.map → chunk-q15f5g86.js.map} +1 -1
- package/dist/{chunk-838cdh6v.js → chunk-qfra7gah.js} +2 -2
- package/dist/{chunk-838cdh6v.js.map → chunk-qfra7gah.js.map} +1 -1
- package/dist/{chunk-aprjvzrz.js → chunk-rnp5k8m3.js} +2 -2
- package/dist/{chunk-aprjvzrz.js.map → chunk-rnp5k8m3.js.map} +1 -1
- package/dist/{chunk-qz89m7ss.js → chunk-rzqft8q8.js} +2 -2
- package/dist/{chunk-qz89m7ss.js.map → chunk-rzqft8q8.js.map} +1 -1
- package/dist/{chunk-zc5962gh.js → chunk-s025aycr.js} +2 -2
- package/dist/{chunk-zc5962gh.js.map → chunk-s025aycr.js.map} +1 -1
- package/dist/{chunk-y14weak4.js → chunk-s21kn0x8.js} +2 -2
- package/dist/{chunk-y14weak4.js.map → chunk-s21kn0x8.js.map} +1 -1
- package/dist/{chunk-3wnczt5w.js → chunk-s55t7rxw.js} +2 -2
- package/dist/{chunk-3wnczt5w.js.map → chunk-s55t7rxw.js.map} +1 -1
- package/dist/{chunk-fzs7g6mc.js → chunk-s782bzeq.js} +2 -2
- package/dist/{chunk-fzs7g6mc.js.map → chunk-s782bzeq.js.map} +1 -1
- package/dist/{chunk-77ymcf7q.js → chunk-sa6cxt3g.js} +2 -2
- package/dist/{chunk-77ymcf7q.js.map → chunk-sa6cxt3g.js.map} +1 -1
- package/dist/{chunk-dz76qhx8.js → chunk-swwkdm75.js} +2 -2
- package/dist/{chunk-dz76qhx8.js.map → chunk-swwkdm75.js.map} +1 -1
- package/dist/{chunk-58mg4rpd.js → chunk-t33yh84d.js} +2 -2
- package/dist/{chunk-58mg4rpd.js.map → chunk-t33yh84d.js.map} +1 -1
- package/dist/{chunk-mym7egdq.js → chunk-vnw91fe1.js} +2 -2
- package/dist/{chunk-mym7egdq.js.map → chunk-vnw91fe1.js.map} +1 -1
- package/dist/{chunk-4wda9teq.js → chunk-w1cksc5z.js} +3 -3
- package/dist/{chunk-4wda9teq.js.map → chunk-w1cksc5z.js.map} +1 -1
- package/dist/chunk-wevj4981.js +122 -0
- package/dist/{chunk-fx7r6pdf.js.map → chunk-wevj4981.js.map} +3 -3
- package/dist/{chunk-ayjfs5mm.js → chunk-wrsf2abe.js} +2 -2
- package/dist/{chunk-ayjfs5mm.js.map → chunk-wrsf2abe.js.map} +1 -1
- package/dist/{chunk-j1wc4afr.js → chunk-x16ckgq1.js} +2 -2
- package/dist/{chunk-j1wc4afr.js.map → chunk-x16ckgq1.js.map} +1 -1
- package/dist/{chunk-gnaxedwh.js → chunk-x51tegk3.js} +2 -2
- package/dist/{chunk-gnaxedwh.js.map → chunk-x51tegk3.js.map} +1 -1
- package/dist/{chunk-qspam5cf.js → chunk-x5hj0mqp.js} +2 -2
- package/dist/{chunk-qspam5cf.js.map → chunk-x5hj0mqp.js.map} +1 -1
- package/dist/{chunk-dp2yz8bj.js → chunk-x9bk5s21.js} +2 -2
- package/dist/{chunk-dp2yz8bj.js.map → chunk-x9bk5s21.js.map} +1 -1
- package/dist/{chunk-p462p2xe.js → chunk-xvvsc58s.js} +2 -2
- package/dist/{chunk-p462p2xe.js.map → chunk-xvvsc58s.js.map} +1 -1
- package/dist/{chunk-0g5f8ymy.js → chunk-xymr3asa.js} +2 -2
- package/dist/{chunk-0g5f8ymy.js.map → chunk-xymr3asa.js.map} +1 -1
- package/dist/{chunk-j4y0sjdc.js → chunk-ysc7ykss.js} +2 -2
- package/dist/{chunk-j4y0sjdc.js.map → chunk-ysc7ykss.js.map} +1 -1
- package/dist/{chunk-3xy41vc0.js → chunk-z61dj480.js} +3 -3
- package/dist/{chunk-3xy41vc0.js.map → chunk-z61dj480.js.map} +1 -1
- package/dist/{chunk-0q68t71d.js → chunk-z9xxthp1.js} +3 -3
- package/dist/{chunk-0q68t71d.js.map → chunk-z9xxthp1.js.map} +1 -1
- package/dist/{chunk-47eav3ex.js → chunk-zv5qyrqg.js} +2 -2
- package/dist/{chunk-47eav3ex.js.map → chunk-zv5qyrqg.js.map} +1 -1
- package/dist/{chunk-asmszzkp.js → chunk-zyhmn3hy.js} +3 -3
- package/dist/{chunk-asmszzkp.js.map → chunk-zyhmn3hy.js.map} +1 -1
- package/dist/{chunk-zzgt759n.js → chunk-zypmy8yq.js} +2 -2
- package/dist/{chunk-zzgt759n.js.map → chunk-zypmy8yq.js.map} +1 -1
- package/dist/config/index.js +1 -1
- package/dist/console/run.js +2 -2
- package/dist/console/run.js.map +1 -1
- package/dist/container/index.js +2 -2
- package/dist/container/index.js.map +1 -1
- package/dist/database/index.js +2 -2
- package/dist/database/index.js.map +1 -1
- package/dist/email/index.js +2 -2
- package/dist/email/index.js.map +1 -1
- package/dist/facades/index.js +2 -2
- package/dist/facades/index.js.map +1 -1
- package/dist/foundation/index.js +2 -2
- package/dist/foundation/index.js.map +1 -1
- package/dist/http/ApiRouter.d.ts +27 -5
- package/dist/http/ApiRouter.d.ts.map +1 -1
- package/dist/http/index.js +2 -2
- package/dist/http/index.js.map +1 -1
- package/dist/i18n/dictionaryRuntime.js +2 -2
- package/dist/i18n/dictionaryRuntime.js.map +1 -1
- package/dist/i18n/index.js +2 -2
- package/dist/i18n/index.js.map +1 -1
- package/dist/kernel/index.js +2 -2
- package/dist/kernel/index.js.map +1 -1
- package/dist/orm/defaults.d.ts.map +1 -1
- package/dist/orm/index.js +3 -3
- package/dist/orm/index.js.map +3 -3
- package/dist/server/index.js +2 -2
- package/dist/server/index.js.map +1 -1
- package/dist/services/index.js +2 -2
- package/dist/services/index.js.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/stats/route-table.js +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/dist/vitest/index.js +1 -1
- package/package.json +2 -1
- package/dist/chunk-539w9yt3.js +0 -6
- package/dist/chunk-fx7r6pdf.js +0 -122
- package/dist/chunk-mvka90rq.js +0 -5
- /package/dist/{chunk-dxm5gxqk.js.map → chunk-1awxdnb6.js.map} +0 -0
- /package/dist/{chunk-fxm8fqh9.js.map → chunk-33hdxe7v.js.map} +0 -0
- /package/dist/{chunk-f21v4n2v.js.map → chunk-53rr32zm.js.map} +0 -0
- /package/dist/{chunk-b00z33zg.js.map → chunk-gng5e7pd.js.map} +0 -0
- /package/dist/{chunk-8fvt7kys.js.map → chunk-hf492gg2.js.map} +0 -0
- /package/dist/{chunk-x07rp3fc.js.map → chunk-mpqvmge4.js.map} +0 -0
|
@@ -1,22 +1,22 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Fd as a0,Kd as r0}from"./chunk-0g5f8ymy.js";import{Ah as SZ,Bh as o,gi as s0,ii as p,ji as LZ,li as u0}from"./chunk-p642ja42.js";import{Ai as g0}from"./chunk-rjyw1thg.js";import{Fk as l}from"./chunk-35zw2s61.js";class pZ{spent=new Map;sweepAt=1024;async consume(Z,$){return this.consumeSync(Z,$)}consumeSync(Z,$,Q=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Q);let B=this.spent.get(Z);if(B!==void 0&&B>Q)return!1;return this.spent.set(Z,$),!0}get size(){return this.spent.size}sweep(Z){for(let[$,Q]of this.spent)if(Q<=Z)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class B1{injectedClient;prefix;constructor(Z={}){this.injectedClient=Z.client,this.prefix=Z.prefix??"gemi:ai:nonce"}async consume(Z,$){let Q=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Z}`,"1","PX",String(Q),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Z=l(),$=Z.bound(LZ)?Z.make(LZ).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var DZ=new pZ;class P extends Error{retryable;constructor(Z,$={}){super(Z,$.cause!==void 0?{cause:$.cause}:void 0);this.name="ToolError",this.retryable=$.retryable??!0}}var X1={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function n(Z,$){if($.source==="tool"){if($.cause instanceof P)return Z;return{...Z,message:`The tool "${$.toolName}" failed with an unexpected error.`}}let Q=X1[Z.code];return Q===void 0?Z:{...Z,message:Q}}function mZ(Z,$,Q,B){let X;try{X=(Z??n)($,Q)}catch(Y){B(Y),X=n($,Q)}return{code:X.code,message:X.message,...X.toolCallId!==void 0?{toolCallId:X.toolCallId}:{},retryable:X.retryable}}var iZ=new WeakMap;function lZ(Z,$){if(Z!==$)iZ.set(Z,$)}function C4(Z){return iZ.get(Z)??Z}class PZ extends P{id;code="attachment_not_found";constructor(Z){super(`No attachment ${Z}.`);this.id=Z;this.name="AttachmentNotFoundError"}}class w extends P{code="invalid_attachment_scope";constructor(Z){super(Z);this.name="InvalidAttachmentScopeError"}}function UZ(Z){if(!Z||typeof Z.key!=="string"||Z.key.length===0)throw new w("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Z}var CZ="gemi_att_";function Y1(){return`${CZ}${crypto.randomUUID()}`}class OZ{store;storage;scope;constructor(Z,$,Q){this.store=Z;this.storage=$;this.scope=Q;UZ(Q)}get scopeKey(){return this.scope.key}async get(Z){let $=await this.store.find(this.scope,Z);if(!$||$.scopeKey!==this.scope.key)throw new PZ(Z);return $}async read(Z){return await this.readRecord(Z,await this.get(Z))}async readRecord(Z,$){if(!$.objectName)throw new PZ(Z);return await this.storage.read({name:$.objectName})}async file(Z){let $=await this.get(Z),B=(await this.readRecord(Z,$)).body,X=B instanceof Blob?B:B?await new Response(B).blob():new Blob([]);return new File([X],$.name,{type:$.mimeType})}async put(Z,$={}){let Q=Y1(),B=$.mimeType??Z.type??"",X=$.name??(Z instanceof File?Z.name:Q),Y=await this.storage.put({name:G1(Q,X),body:Z,contentType:B||void 0}),G={id:Q,scopeKey:this.scope.key,objectName:Y,name:X,mimeType:B||"application/octet-stream",size:Z.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,G),G}}function G1(Z,$){let Q=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Z}${Q?`.${Q[1].toLowerCase()}`:""}`}class nZ{rows=new Map;async put(Z,$){UZ(Z),this.rows.set($.id,{...$,scopeKey:Z.key})}async find(Z,$){UZ(Z);let Q=this.rows.get($);if(!Q||Q.scopeKey!==Z.key)return null;return Q}get size(){return this.rows.size}}var oZ=new nZ;class jZ{jobs=new Map;async create(Z){if(this.jobs.has(Z.id))throw Error(`A background job with the id ${Z.id} already exists.`);let $=Date.now(),{deadlineMs:Q,...B}=Z,X={...structuredClone(B),state:"running",createdAt:$,updatedAt:$,deadlineAt:$+Q};return this.jobs.set(X.id,X),this.trim(X.threadId),structuredClone(X)}async get(Z){let $=this.jobs.get(Z);return $?structuredClone($):null}async listForThread(Z,$={}){let Q=[];for(let B of this.jobs.values()){if(B.threadId!==Z)continue;if($.states&&!$.states.includes(B.state))continue;Q.push(B)}return Q.sort(tZ),($.limit===void 0?Q:Q.slice(0,$.limit)).map((B)=>structuredClone(B))}async transition(Z,$,Q){let B=this.jobs.get(Z);if(!B||!$.includes(B.state))return!1;let X=structuredClone(Q),Y=Date.now();if(Object.assign(B,X,{updatedAt:Y}),X.state&&X.state!=="running"&&B.settledAt===void 0)B.settledAt=X.settledAt??Y;return!0}async overdue(Z,$){let Q=[];for(let B of this.jobs.values())if(B.state==="running"&&B.deadlineAt<=Z)Q.push(B);return Q.sort((B,X)=>B.deadlineAt-X.deadlineAt),Q.slice(0,Math.max(0,$)).map((B)=>structuredClone(B))}async now(){return Date.now()}trim(Z){let $=[...this.jobs.values()].filter((Q)=>Q.threadId===Z&&Q.state!=="running").sort(tZ);for(let Q of $.slice(200))this.jobs.delete(Q.id)}}function tZ(Z,$){return $.createdAt-Z.createdAt||(Z.id<$.id?1:Z.id>$.id?-1:0)}class M extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function T(Z,$){if($.aborted)return Promise.reject(new M);return new Promise((Q,B)=>{let X=()=>B(new M);$.addEventListener("abort",X,{once:!0}),Z.then(Q,B).finally(()=>$.removeEventListener("abort",X))})}function j(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function O(Z,$){if(!$)return Z;let Q={inputTokens:Z.inputTokens+($.inputTokens??0),outputTokens:Z.outputTokens+($.outputTokens??0),totalTokens:Z.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Z.reasoningTokens!==void 0)Q.reasoningTokens=(Z.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Z.cachedInputTokens!==void 0)Q.cachedInputTokens=(Z.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Z.imageInputTokens!==void 0)Q.imageInputTokens=(Z.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Z.imageOutputTokens!==void 0)Q.imageOutputTokens=(Z.imageOutputTokens??0)+($.imageOutputTokens??0);return Q}function t(Z){if(!Z.trim())return{};try{return JSON.parse(Z)}catch{}let $=[],Q=!1,B=!1;for(let G of Z){if(Q){if(B)B=!1;else if(G==="\\")B=!0;else if(G==='"')Q=!1;continue}if(G==='"')Q=!0;else if(G==="{")$.push("}");else if(G==="[")$.push("]");else if(G==="}"||G==="]")$.pop()}let X=Z;if(Q)X+='"';X=X.replace(/[,:]\s*$/,"");let Y=$.reverse().join("");try{return JSON.parse(X+Y)}catch{try{return JSON.parse(X.replace(/,?\s*"[^"]*"\s*$/,"")+Y)}catch{return{}}}}function s(Z){return{name:"output",schema:Z.toJSONSchema(),strict:o(Z)}}function a(Z,$){let Q=Z.safeParse(t($));if(Q.ok===!0)return{ok:!0,value:Q.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Q.errors.join(", ")}`,retryable:!0}}}function r(Z){if(Z.length>0)Z[0];return Z}function h(Z,$,Q){let B=Z.content[Z.content.length-1];if(B&&B.type===$){B.text=(B.text??"")+Q;return}Z.content.push($==="text"?{type:"text",text:Q}:{type:"reasoning",text:Q})}function e(Z,$,Q){let B=Z.content[Z.content.length-1];if(B&&B.type==="reasoning"&&B.id===$){B.text=(B.text??"")+Q;return}Z.content.push($?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q})}import{createHmac as J1,hkdfSync as V1,randomBytes as sZ,timingSafeEqual as z1}from"crypto";var MZ="agt2",$Z="agt1",aZ=[MZ,$Z],NZ=86400000,H1=Date.now()+NZ;function rZ(Z){return Z<=H1}var eZ="gemi.ai.pending-call.v1",Z0="gemi.ai.nested-run.v1",W1="gemi.ai.execution-receipt.v1",q1="gemi.ai.signing",ZZ=new Map;function g(Z,$){let Q=RZ($),B=`${Z}\x00${Q}`,X=ZZ.get(B);if(!X){if(X=Buffer.from(V1("sha256",Q,q1,Z,32)),ZZ.size>64)ZZ.clear();ZZ.set(B,X)}return X}function RZ(Z){let $=Z??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function R(Z){if(Z===null||typeof Z!=="object")return JSON.stringify(Z)??"null";if(Array.isArray(Z))return`[${Z.map(R).join(",")}]`;let $=Z;return`{${Object.keys($).filter((B)=>$[B]!==void 0).sort().map((B)=>`${JSON.stringify(B)}:${R($[B])}`).join(",")}}`}function K1(Z){return Z.map(($)=>`${$.length}:${$}`).join("")}function S(Z,$){return J1("sha256",Z).update(K1($)).digest()}function $0(Z,$){let Q=Buffer.from(Z.split(".")[4],"base64url");return Q.length===$.length&&z1(Q,$)}function _Z(Z){return R(Z??null)}function Q0(Z,$,Q){return[MZ,Z.runId,Z.toolCallId,Z.name,Z.kind,$,String(Q),R(Z.input),R(Z.path??[]),_Z(Z.subject)]}function F1(Z,$,Q){let B=[$Z,Z.runId,Z.toolCallId,Z.name,Z.kind,$,String(Q),R(Z.input)];if(Z.path&&Z.path.length>0)B.push(R(Z.path));return B}var B0=(Z)=>Buffer.from(Z,"utf8").toString("base64url"),L1=(Z)=>Buffer.from(Z,"base64url").toString("utf8");function X0(Z,$={}){let Q=g(eZ,$.secret),X=($.now??Date.now())+($.ttlMs??NZ),Y=sZ(12).toString("base64url"),G=S(Q,Q0(Z,Y,X)).toString("base64url");return[MZ,B0(Z.runId),Y,X.toString(36),G].join(".")}function IZ(Z){return BZ(Z,aZ)}function BZ(Z,$){let Q=Z.split(".");if(Q.length!==5||!$.includes(Q[0]))return null;let B=Number.parseInt(Q[3],36);if(!Number.isFinite(B))return null;try{return{runId:L1(Q[1]),nonce:Q[2],expiresAt:B,version:Q[0]}}catch{return null}}function Y0(Z,$,Q={}){let B=BZ(Z,aZ);if(!B)return{ok:!1,reason:"malformed"};if(B.version===$Z&&!rZ(B.expiresAt))return{ok:!1,reason:"forged"};let X=B.version===$Z?S(RZ(Q.secret),F1($,B.nonce,B.expiresAt)):S(g(eZ,Q.secret),Q0($,B.nonce,B.expiresAt));if(!$0(Z,X))return{ok:!1,reason:"forged"};if((Q.now??Date.now())>B.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:B.runId,nonce:B.nonce,expiresAt:B.expiresAt}}var AZ="agn2",QZ="agn1",G0=[AZ,QZ];function J0(Z,$,Q){return[...V0(Z,$,Q,AZ),_Z(Z.subject)]}function V0(Z,$,Q,B=QZ){return[B,Z.runId,R(Z.path),Z.nestedRunId,$,String(Q),R([...Z.open].sort()),R(Z.input)]}function z0(Z,$={}){let Q=g(Z0,$.secret),X=($.now??Date.now())+($.ttlMs??NZ),Y=sZ(12).toString("base64url"),G=S(Q,J0(Z,Y,X)).toString("base64url");return[AZ,B0(Z.runId),Y,X.toString(36),G].join(".")}function H0(Z,$,Q={}){let B=BZ(Z,G0);if(!B)return{ok:!1,reason:"malformed"};if(B.version===QZ&&!rZ(B.expiresAt))return{ok:!1,reason:"forged"};let X={...$,runId:B.runId},Y=B.version===QZ?S(RZ(Q.secret),V0(X,B.nonce,B.expiresAt)):S(g(Z0,Q.secret),J0(X,B.nonce,B.expiresAt));if(!$0(Z,Y))return{ok:!1,reason:"forged"};if((Q.now??Date.now())>B.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:B.runId,nonce:B.nonce,expiresAt:B.expiresAt}}function W0(Z,$,Q={}){let B=g(W1,Q.secret);return S(B,[Z,$.runId,$.toolCallId,$.name,$.kind,R($.input),R($.path??[]),_Z($.subject)]).toString("base64url")}function q0(Z,$){return F0($,IZ(Z))}function K0(Z,$){return F0($,BZ(Z,G0))}async function F0(Z,$){if(!$)return!1;return Z.consume($.nonce,$.expiresAt)}class L0 extends Error{status;body;requestId;constructor(Z,$,Q){super(`Provider request failed with status ${Z}: ${D1($)}`);this.name="ProviderHttpError",this.status=Z,this.body=$,this.requestId=Q}}class D0 extends Error{timeoutMs;constructor(Z){super(`Provider request timed out after ${Z}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Z}}function D1(Z){let $=P0(Z);if($?.message)return $.message;if(typeof Z==="string")return Z.slice(0,500);return"no error body"}function P0(Z){if(!Z||typeof Z!=="object")return null;let $=Z,B=$.error&&typeof $.error==="object"?$.error:Z;if(typeof B.message!=="string"&&typeof B.code!=="string"&&typeof B.type!=="string")return null;let X=B.innererror?.code??B.code;return{message:B.message,type:B.type,code:X,param:B.param}}function x(Z){if(!Z||typeof Z!=="object")return{};let{status:$,requestId:Q}=Z;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Q==="string"&&Q?{requestId:Q}:{}}}function T4(Z){if(Z instanceof D0)return{code:"provider_error",message:Z.message,retryable:!0};if(O1(Z))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Z instanceof L0)return P1(Z.status,P0(Z.body),Z.message);if(Z instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Z.message}`,retryable:!0};if(Z instanceof Error)return{code:"provider_error",message:Z.message,retryable:!1};return{code:"unknown",message:String(Z),retryable:!1}}function P1(Z,$,Q){let B=$?.message??Q,X=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),G=`${X} ${Y} ${B}`.toLowerCase();if(Z===429){let z=X==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:B,retryable:!z}}if(Z>=500||Z===408||Z===409)return{code:"provider_error",message:B,retryable:!0};if(U1(G))return{code:"context_length_exceeded",message:B,retryable:!1};if(C1(G))return{code:"content_filtered",message:B,retryable:!1};if($?.param?.startsWith("tools")||G.includes("invalid schema for function"))return{code:"invalid_tool_input",message:B,retryable:!1};return{code:"provider_error",message:B,retryable:!1}}function U1(Z){return Z.includes("context_length_exceeded")||Z.includes("maximum context length")||Z.includes("context window")||Z.includes("reduce the length")}function C1(Z){return Z.includes("content_filter")||Z.includes("content_policy_violation")||Z.includes("responsibleaipolicyviolation")||Z.includes("content management policy")}function O1(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;return $.name==="AbortError"||$.code==="ABORT_ERR"}function YZ(Z){let $=new Set;for(let Q of Z)for(let B of Q.content??[]){if(B.type!=="tool-call")continue;for(let X of B.attachments??[])if(X&&"shown"in X&&X.shown)$.add(X.shown.messageId)}return $}function GZ(Z){if(Z.length===0)return[];let $=YZ(Z),Q=[0];for(let B=1;B<Z.length;B++){let X=Z[B];if(X.role==="user"&&!$.has(X.id))Q.push(B)}return Q}function x4(Z){let $=GZ(Z);return $.map((Q,B)=>Z.slice(Q,$[B+1]??Z.length))}function j1(Z){try{return JSON.stringify(Z).length}catch{return 0}}var M1=4,N1=10,R1="[Earlier turns of this conversation are not shown.]";function u(Z,$={}){let Q=[...Z],B=GZ(Q),X=_1($),Y=XZ($.maxTurns)??1/0,G=Math.max(1,Math.floor(XZ($.step)??N1));if(B.length<=1||Y>=B.length&&X===1/0)return{messages:Q,start:0,omittedTurns:0,omittedMessages:0};let z=Array.from({length:Q.length+1},()=>0);if(X!==1/0)for(let D=Q.length-1;D>=0;D--)z[D]=z[D+1]+j1(Q[D]);let V=(D)=>B.length-D<=Y&&z[B[D]]<=X,J=-1;for(let D=0;D<B.length;D+=G)if(V(D)){J=D;break}if(J<0){for(let D=0;D<B.length;D++)if(V(D)){J=D;break}}if(J<0)J=B.length-1;if(J===0)return{messages:Q,start:0,omittedTurns:0,omittedMessages:0};let H=B[J],q=Q.slice(0,H),W=q.filter((D)=>D.role==="system"),F=I1(q,Q.slice(H)),K={turns:J,messages:q.length-W.length},L=typeof $.note==="function"?$.note(K):$.note===void 0?R1:$.note;if(L){let D=F[0];F[0]={...D,content:[{type:"text",text:L},...D.content]}}return{messages:[...W,...F],start:H,omittedTurns:K.turns,omittedMessages:K.messages}}function XZ(Z){return typeof Z==="number"&&Z>0?Z:void 0}function _1(Z){let $=XZ(Z.maxBytes)??1/0,Q=XZ(Z.maxTokens);return Math.min($,Q===void 0?1/0:Q*M1)}function U0(Z,$){let Q=Array.isArray(Z?.namespaces)?Z.namespaces:[],B=Array.isArray(Z?.loaded)?Z.loaded:[];return $.namespace?Q.includes($.namespace):B.includes(String($.name))}function kZ(Z){return Array.isArray(Z.toolSearches)?Z.toolSearches:[]}function I1(Z,$){let Q=[];for(let J of Z)for(let H of J.content??[])if(H.type==="tool-call")Q.push(...kZ(H));if(Q.length===0)return $;let B=[],X=new Set,Y;if($.forEach((J,H)=>{(J.content??[]).forEach((q,W)=>{if(q.type!=="tool-call"||q.partial)return;if(B.push(...kZ(q)),B.some((K)=>U0(K,q)))return;let F=Q.filter((K)=>U0(K,q));if(F.length===0)return;for(let K of F)X.add(K);Y??={message:H,part:W}})}),!Y)return $;let G=Q.filter((J)=>X.has(J)),z=[...$],V=z[Y.message];return z[Y.message]={...V,content:V.content.map((J,H)=>H===Y.part&&J.type==="tool-call"?{...J,toolSearches:[...G,...kZ(J)]}:J)},z}var A1=1000,k1=24000,T1=20000,S1=1e5,x1=120000,E1=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),f1="[Summary of the earlier turns of this conversation, which are not shown:]",b1=8;class M0{ttlMs;threads=new Map;lastSweep=0;constructor(Z=86400000){this.ttlMs=Z}async loadSummaries(Z){this.sweep();let $=this.threads.get(Z);if(!$)return[];return $.touchedAt=Date.now(),$.summaries.slice()}async saveSummary(Z,$){this.sweep();let Q=this.threads.get(Z)??{summaries:[],touchedAt:Date.now()};Q.summaries=w1(Q.summaries,$),Q.touchedAt=Date.now(),this.threads.set(Z,Q)}delete(Z){this.threads.delete(Z)}sweep(Z=Date.now()){if(Z-this.lastSweep<60000)return;this.lastSweep=Z;for(let[$,Q]of this.threads)if(Z-Q.touchedAt>this.ttlMs)this.threads.delete($)}}function w1(Z,$){return[$,...Z.filter((Q)=>Q.cutMessageId!==$.cutMessageId)].slice(0,b1)}var N0=new M0;function y4(Z){let $=Z;return typeof $?.loadSummaries==="function"&&typeof $?.saveSummary==="function"}function R0(Z,$,Q){let B=A(Q.maxSummaryTokens)??A1,X=(V)=>Math.max(1,V-B),Y={...$,...A($.maxTokens)?{maxTokens:X($.maxTokens)}:{},...A($.maxBytes)?{maxBytes:Math.max(1,$.maxBytes-B*xZ)}:{}},G=v1($,Q),z={...Y,note:!1,...G?{maxTokens:Math.min(Y.maxTokens??1/0,X(G))}:{}};return{plain:Y,cut:u(Z,z),maxSummaryTokens:B}}function v1(Z,$){if($.triggerTokens===!1)return;let Q=A($.triggerTokens||void 0);if(Q)return Q;if(A(Z.maxTokens)||A(Z.maxBytes))return;return S1}async function _0(Z){let{history:$,window:Q,compact:B}=Z,{plain:X,cut:Y,maxSummaryTokens:G}=R0($,Q,B);if(Y.omittedTurns===0)return Y.messages;let z=`${$[Y.start].id}:${Y.start}`,V=Z.memo?.get(z);if(V===void 0){try{V=await u1(Z,Y.start,G)}catch(F){if(Z.signal.aborted)throw F;V=null}if(!Z.signal.aborted)Z.memo?.set(z,V)}if(!V)return u($,X).messages;let J=$.length-Y.start,H=Y.messages.slice(0,Y.messages.length-J),q=Y.messages.slice(Y.messages.length-J),W=$[Y.start];return[...H,{id:`summary_${W.id}`,role:"user",content:[{type:"text",text:`${f1}
|
|
3
|
-
${
|
|
2
|
+
import{Fd as a0,Kd as r0}from"./chunk-xymr3asa.js";import{Bh as kZ,Ch as o,hi as s0,ji as p,ki as LZ,mi as u0}from"./chunk-0rhf4g12.js";import{Bi as g0}from"./chunk-4t41m5f1.js";import{Gk as i}from"./chunk-jx2mgvvt.js";class pZ{spent=new Map;sweepAt=1024;async consume(Z,$){return this.consumeSync(Z,$)}consumeSync(Z,$,Q=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Q);let B=this.spent.get(Z);if(B!==void 0&&B>Q)return!1;return this.spent.set(Z,$),!0}get size(){return this.spent.size}sweep(Z){for(let[$,Q]of this.spent)if(Q<=Z)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class B1{injectedClient;prefix;constructor(Z={}){this.injectedClient=Z.client,this.prefix=Z.prefix??"gemi:ai:nonce"}async consume(Z,$){let Q=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Z}`,"1","PX",String(Q),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Z=i(),$=Z.bound(LZ)?Z.make(LZ).client:void 0;if(!$)throw Error("RedisNonceStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisNonceStore({ client }).");return $}}var DZ=new pZ;class P extends Error{retryable;constructor(Z,$={}){super(Z,$.cause!==void 0?{cause:$.cause}:void 0);this.name="ToolError",this.retryable=$.retryable??!0}}var X1={provider_error:"The model provider returned an error.",rate_limited:"The model provider is rate limiting requests. Try again shortly.",context_length_exceeded:"The conversation is too long for the model.",content_filtered:"The model provider's content filter blocked this request.",invalid_tool_input:"The model provider rejected the request.",tool_error:"A tool failed.",unknown:"The run failed unexpectedly."};function n(Z,$){if($.source==="tool"){if($.cause instanceof P)return Z;return{...Z,message:`The tool "${$.toolName}" failed with an unexpected error.`}}let Q=X1[Z.code];return Q===void 0?Z:{...Z,message:Q}}function mZ(Z,$,Q,B){let X;try{X=(Z??n)($,Q)}catch(Y){B(Y),X=n($,Q)}return{code:X.code,message:X.message,...X.toolCallId!==void 0?{toolCallId:X.toolCallId}:{},retryable:X.retryable}}var lZ=new WeakMap;function iZ(Z,$){if(Z!==$)lZ.set(Z,$)}function O4(Z){return lZ.get(Z)??Z}class PZ extends P{id;code="attachment_not_found";constructor(Z){super(`No attachment ${Z}.`);this.id=Z;this.name="AttachmentNotFoundError"}}class w extends P{code="invalid_attachment_scope";constructor(Z){super(Z);this.name="InvalidAttachmentScopeError"}}function UZ(Z){if(!Z||typeof Z.key!=="string"||Z.key.length===0)throw new w("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Z}var CZ="gemi_att_";function Y1(){return`${CZ}${crypto.randomUUID()}`}class OZ{store;storage;scope;constructor(Z,$,Q){this.store=Z;this.storage=$;this.scope=Q;UZ(Q)}get scopeKey(){return this.scope.key}async get(Z){let $=await this.store.find(this.scope,Z);if(!$||$.scopeKey!==this.scope.key)throw new PZ(Z);return $}async read(Z){return await this.readRecord(Z,await this.get(Z))}async readRecord(Z,$){if(!$.objectName)throw new PZ(Z);return await this.storage.read({name:$.objectName})}async file(Z){let $=await this.get(Z),B=(await this.readRecord(Z,$)).body,X=B instanceof Blob?B:B?await new Response(B).blob():new Blob([]);return new File([X],$.name,{type:$.mimeType})}async put(Z,$={}){let Q=Y1(),B=$.mimeType??Z.type??"",X=$.name??(Z instanceof File?Z.name:Q),Y=await this.storage.put({name:J1(Q,X),body:Z,contentType:B||void 0}),J={id:Q,scopeKey:this.scope.key,objectName:Y,name:X,mimeType:B||"application/octet-stream",size:Z.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,J),J}}function J1(Z,$){let Q=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Z}${Q?`.${Q[1].toLowerCase()}`:""}`}class nZ{rows=new Map;async put(Z,$){UZ(Z),this.rows.set($.id,{...$,scopeKey:Z.key})}async find(Z,$){UZ(Z);let Q=this.rows.get($);if(!Q||Q.scopeKey!==Z.key)return null;return Q}get size(){return this.rows.size}}var oZ=new nZ;class jZ{jobs=new Map;async create(Z){if(this.jobs.has(Z.id))throw Error(`A background job with the id ${Z.id} already exists.`);let $=Date.now(),{deadlineMs:Q,...B}=Z,X={...structuredClone(B),state:"running",createdAt:$,updatedAt:$,deadlineAt:$+Q};return this.jobs.set(X.id,X),this.trim(X.threadId),structuredClone(X)}async get(Z){let $=this.jobs.get(Z);return $?structuredClone($):null}async listForThread(Z,$={}){let Q=[];for(let B of this.jobs.values()){if(B.threadId!==Z)continue;if($.states&&!$.states.includes(B.state))continue;Q.push(B)}return Q.sort(tZ),($.limit===void 0?Q:Q.slice(0,$.limit)).map((B)=>structuredClone(B))}async transition(Z,$,Q){let B=this.jobs.get(Z);if(!B||!$.includes(B.state))return!1;let X=structuredClone(Q),Y=Date.now();if(Object.assign(B,X,{updatedAt:Y}),X.state&&X.state!=="running"&&B.settledAt===void 0)B.settledAt=X.settledAt??Y;return!0}async overdue(Z,$){let Q=[];for(let B of this.jobs.values())if(B.state==="running"&&B.deadlineAt<=Z)Q.push(B);return Q.sort((B,X)=>B.deadlineAt-X.deadlineAt),Q.slice(0,Math.max(0,$)).map((B)=>structuredClone(B))}async now(){return Date.now()}trim(Z){let $=[...this.jobs.values()].filter((Q)=>Q.threadId===Z&&Q.state!=="running").sort(tZ);for(let Q of $.slice(200))this.jobs.delete(Q.id)}}function tZ(Z,$){return $.createdAt-Z.createdAt||(Z.id<$.id?1:Z.id>$.id?-1:0)}class M extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function x(Z,$){if($.aborted)return Promise.reject(new M);return new Promise((Q,B)=>{let X=()=>B(new M);$.addEventListener("abort",X,{once:!0}),Z.then(Q,B).finally(()=>$.removeEventListener("abort",X))})}function j(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function O(Z,$){if(!$)return Z;let Q={inputTokens:Z.inputTokens+($.inputTokens??0),outputTokens:Z.outputTokens+($.outputTokens??0),totalTokens:Z.totalTokens+($.totalTokens??0)};for(let B of V1)if($[B]!==void 0||Z[B]!==void 0)Q[B]=(Z[B]??0)+($[B]??0);return Q}var V1=["reasoningTokens","cachedInputTokens","imageInputTokens","imageOutputTokens","audioInputTokens","cachedAudioInputTokens","audioOutputTokens"];function t(Z){if(!Z.trim())return{};try{return JSON.parse(Z)}catch{}let $=[],Q=!1,B=!1;for(let J of Z){if(Q){if(B)B=!1;else if(J==="\\")B=!0;else if(J==='"')Q=!1;continue}if(J==='"')Q=!0;else if(J==="{")$.push("}");else if(J==="[")$.push("]");else if(J==="}"||J==="]")$.pop()}let X=Z;if(Q)X+='"';X=X.replace(/[,:]\s*$/,"");let Y=$.reverse().join("");try{return JSON.parse(X+Y)}catch{try{return JSON.parse(X.replace(/,?\s*"[^"]*"\s*$/,"")+Y)}catch{return{}}}}function s(Z){return{name:"output",schema:Z.toJSONSchema(),strict:o(Z)}}function a(Z,$){let Q=Z.safeParse(t($));if(Q.ok===!0)return{ok:!0,value:Q.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Q.errors.join(", ")}`,retryable:!0}}}function r(Z){if(Z.length>0)Z[0];return Z}function h(Z,$,Q){let B=Z.content[Z.content.length-1];if(B&&B.type===$){B.text=(B.text??"")+Q;return}Z.content.push($==="text"?{type:"text",text:Q}:{type:"reasoning",text:Q})}function e(Z,$,Q){let B=Z.content[Z.content.length-1];if(B&&B.type==="reasoning"&&B.id===$){B.text=(B.text??"")+Q;return}Z.content.push($?{type:"reasoning",id:$,text:Q}:{type:"reasoning",text:Q})}import{createHmac as G1,hkdfSync as z1,randomBytes as sZ,timingSafeEqual as H1}from"crypto";var MZ="agt2",$Z="agt1",aZ=[MZ,$Z],NZ=86400000,W1=Date.now()+NZ;function rZ(Z){return Z<=W1}var eZ="gemi.ai.pending-call.v1",Z0="gemi.ai.nested-run.v1",q1="gemi.ai.execution-receipt.v1",K1="gemi.ai.signing",ZZ=new Map;function g(Z,$){let Q=RZ($),B=`${Z}\x00${Q}`,X=ZZ.get(B);if(!X){if(X=Buffer.from(z1("sha256",Q,K1,Z,32)),ZZ.size>64)ZZ.clear();ZZ.set(B,X)}return X}function RZ(Z){let $=Z??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function R(Z){if(Z===null||typeof Z!=="object")return JSON.stringify(Z)??"null";if(Array.isArray(Z))return`[${Z.map(R).join(",")}]`;let $=Z;return`{${Object.keys($).filter((B)=>$[B]!==void 0).sort().map((B)=>`${JSON.stringify(B)}:${R($[B])}`).join(",")}}`}function F1(Z){return Z.map(($)=>`${$.length}:${$}`).join("")}function k(Z,$){return G1("sha256",Z).update(F1($)).digest()}function $0(Z,$){let Q=Buffer.from(Z.split(".")[4],"base64url");return Q.length===$.length&&H1(Q,$)}function _Z(Z){return R(Z??null)}function Q0(Z,$,Q){return[MZ,Z.runId,Z.toolCallId,Z.name,Z.kind,$,String(Q),R(Z.input),R(Z.path??[]),_Z(Z.subject)]}function L1(Z,$,Q){let B=[$Z,Z.runId,Z.toolCallId,Z.name,Z.kind,$,String(Q),R(Z.input)];if(Z.path&&Z.path.length>0)B.push(R(Z.path));return B}var B0=(Z)=>Buffer.from(Z,"utf8").toString("base64url"),D1=(Z)=>Buffer.from(Z,"base64url").toString("utf8");function X0(Z,$={}){let Q=g(eZ,$.secret),X=($.now??Date.now())+($.ttlMs??NZ),Y=sZ(12).toString("base64url"),J=k(Q,Q0(Z,Y,X)).toString("base64url");return[MZ,B0(Z.runId),Y,X.toString(36),J].join(".")}function IZ(Z){return BZ(Z,aZ)}function BZ(Z,$){let Q=Z.split(".");if(Q.length!==5||!$.includes(Q[0]))return null;let B=Number.parseInt(Q[3],36);if(!Number.isFinite(B))return null;try{return{runId:D1(Q[1]),nonce:Q[2],expiresAt:B,version:Q[0]}}catch{return null}}function Y0(Z,$,Q={}){let B=BZ(Z,aZ);if(!B)return{ok:!1,reason:"malformed"};if(B.version===$Z&&!rZ(B.expiresAt))return{ok:!1,reason:"forged"};let X=B.version===$Z?k(RZ(Q.secret),L1($,B.nonce,B.expiresAt)):k(g(eZ,Q.secret),Q0($,B.nonce,B.expiresAt));if(!$0(Z,X))return{ok:!1,reason:"forged"};if((Q.now??Date.now())>B.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:B.runId,nonce:B.nonce,expiresAt:B.expiresAt}}var AZ="agn2",QZ="agn1",J0=[AZ,QZ];function V0(Z,$,Q){return[...G0(Z,$,Q,AZ),_Z(Z.subject)]}function G0(Z,$,Q,B=QZ){return[B,Z.runId,R(Z.path),Z.nestedRunId,$,String(Q),R([...Z.open].sort()),R(Z.input)]}function z0(Z,$={}){let Q=g(Z0,$.secret),X=($.now??Date.now())+($.ttlMs??NZ),Y=sZ(12).toString("base64url"),J=k(Q,V0(Z,Y,X)).toString("base64url");return[AZ,B0(Z.runId),Y,X.toString(36),J].join(".")}function H0(Z,$,Q={}){let B=BZ(Z,J0);if(!B)return{ok:!1,reason:"malformed"};if(B.version===QZ&&!rZ(B.expiresAt))return{ok:!1,reason:"forged"};let X={...$,runId:B.runId},Y=B.version===QZ?k(RZ(Q.secret),G0(X,B.nonce,B.expiresAt)):k(g(Z0,Q.secret),V0(X,B.nonce,B.expiresAt));if(!$0(Z,Y))return{ok:!1,reason:"forged"};if((Q.now??Date.now())>B.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:B.runId,nonce:B.nonce,expiresAt:B.expiresAt}}function W0(Z,$,Q={}){let B=g(q1,Q.secret);return k(B,[Z,$.runId,$.toolCallId,$.name,$.kind,R($.input),R($.path??[]),_Z($.subject)]).toString("base64url")}function q0(Z,$){return F0($,IZ(Z))}function K0(Z,$){return F0($,BZ(Z,J0))}async function F0(Z,$){if(!$)return!1;return Z.consume($.nonce,$.expiresAt)}class L0 extends Error{status;body;requestId;constructor(Z,$,Q){super(`Provider request failed with status ${Z}: ${P1($)}`);this.name="ProviderHttpError",this.status=Z,this.body=$,this.requestId=Q}}class D0 extends Error{timeoutMs;constructor(Z){super(`Provider request timed out after ${Z}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Z}}function P1(Z){let $=P0(Z);if($?.message)return $.message;if(typeof Z==="string")return Z.slice(0,500);return"no error body"}function P0(Z){if(!Z||typeof Z!=="object")return null;let $=Z,B=$.error&&typeof $.error==="object"?$.error:Z;if(typeof B.message!=="string"&&typeof B.code!=="string"&&typeof B.type!=="string")return null;let X=B.innererror?.code??B.code;return{message:B.message,type:B.type,code:X,param:B.param}}function S(Z){if(!Z||typeof Z!=="object")return{};let{status:$,requestId:Q}=Z;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Q==="string"&&Q?{requestId:Q}:{}}}function k4(Z){if(Z instanceof D0)return{code:"provider_error",message:Z.message,retryable:!0};if(j1(Z))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Z instanceof L0)return U1(Z.status,P0(Z.body),Z.message);if(Z instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Z.message}`,retryable:!0};if(Z instanceof Error)return{code:"provider_error",message:Z.message,retryable:!1};return{code:"unknown",message:String(Z),retryable:!1}}function U1(Z,$,Q){let B=$?.message??Q,X=($?.code??"").toLowerCase(),Y=($?.type??"").toLowerCase(),J=`${X} ${Y} ${B}`.toLowerCase();if(Z===429){let z=X==="insufficient_quota"||J.includes("quota");return{code:"rate_limited",message:B,retryable:!z}}if(Z>=500||Z===408||Z===409)return{code:"provider_error",message:B,retryable:!0};if(C1(J))return{code:"context_length_exceeded",message:B,retryable:!1};if(O1(J))return{code:"content_filtered",message:B,retryable:!1};if($?.param?.startsWith("tools")||J.includes("invalid schema for function"))return{code:"invalid_tool_input",message:B,retryable:!1};return{code:"provider_error",message:B,retryable:!1}}function C1(Z){return Z.includes("context_length_exceeded")||Z.includes("maximum context length")||Z.includes("context window")||Z.includes("reduce the length")}function O1(Z){return Z.includes("content_filter")||Z.includes("content_policy_violation")||Z.includes("responsibleaipolicyviolation")||Z.includes("content management policy")}function j1(Z){if(!Z||typeof Z!=="object")return!1;let $=Z;return $.name==="AbortError"||$.code==="ABORT_ERR"}function YZ(Z){let $=new Set;for(let Q of Z)for(let B of Q.content??[]){if(B.type!=="tool-call")continue;for(let X of B.attachments??[])if(X&&"shown"in X&&X.shown)$.add(X.shown.messageId)}return $}function JZ(Z){if(Z.length===0)return[];let $=YZ(Z),Q=[0];for(let B=1;B<Z.length;B++){let X=Z[B];if(X.role==="user"&&!$.has(X.id))Q.push(B)}return Q}function E4(Z){let $=JZ(Z);return $.map((Q,B)=>Z.slice(Q,$[B+1]??Z.length))}function M1(Z){try{return JSON.stringify(Z).length}catch{return 0}}var N1=4,R1=10,_1="[Earlier turns of this conversation are not shown.]";function u(Z,$={}){let Q=[...Z],B=JZ(Q),X=I1($),Y=XZ($.maxTurns)??1/0,J=Math.max(1,Math.floor(XZ($.step)??R1));if(B.length<=1||Y>=B.length&&X===1/0)return{messages:Q,start:0,omittedTurns:0,omittedMessages:0};let z=Array.from({length:Q.length+1},()=>0);if(X!==1/0)for(let D=Q.length-1;D>=0;D--)z[D]=z[D+1]+M1(Q[D]);let G=(D)=>B.length-D<=Y&&z[B[D]]<=X,V=-1;for(let D=0;D<B.length;D+=J)if(G(D)){V=D;break}if(V<0){for(let D=0;D<B.length;D++)if(G(D)){V=D;break}}if(V<0)V=B.length-1;if(V===0)return{messages:Q,start:0,omittedTurns:0,omittedMessages:0};let H=B[V],q=Q.slice(0,H),W=q.filter((D)=>D.role==="system"),F=A1(q,Q.slice(H)),K={turns:V,messages:q.length-W.length},L=typeof $.note==="function"?$.note(K):$.note===void 0?_1:$.note;if(L){let D=F[0];F[0]={...D,content:[{type:"text",text:L},...D.content]}}return{messages:[...W,...F],start:H,omittedTurns:K.turns,omittedMessages:K.messages}}function XZ(Z){return typeof Z==="number"&&Z>0?Z:void 0}function I1(Z){let $=XZ(Z.maxBytes)??1/0,Q=XZ(Z.maxTokens);return Math.min($,Q===void 0?1/0:Q*N1)}function U0(Z,$){let Q=Array.isArray(Z?.namespaces)?Z.namespaces:[],B=Array.isArray(Z?.loaded)?Z.loaded:[];return $.namespace?Q.includes($.namespace):B.includes(String($.name))}function TZ(Z){return Array.isArray(Z.toolSearches)?Z.toolSearches:[]}function A1(Z,$){let Q=[];for(let V of Z)for(let H of V.content??[])if(H.type==="tool-call")Q.push(...TZ(H));if(Q.length===0)return $;let B=[],X=new Set,Y;if($.forEach((V,H)=>{(V.content??[]).forEach((q,W)=>{if(q.type!=="tool-call"||q.partial)return;if(B.push(...TZ(q)),B.some((K)=>U0(K,q)))return;let F=Q.filter((K)=>U0(K,q));if(F.length===0)return;for(let K of F)X.add(K);Y??={message:H,part:W}})}),!Y)return $;let J=Q.filter((V)=>X.has(V)),z=[...$],G=z[Y.message];return z[Y.message]={...G,content:G.content.map((V,H)=>H===Y.part&&V.type==="tool-call"?{...V,toolSearches:[...J,...TZ(V)]}:V)},z}var T1=1000,x1=24000,k1=20000,S1=1e5,E1=120000,f1=["You keep a running summary of a conversation between a user and an AI assistant.","The assistant will continue the conversation with only your summary and the latest turns, so the summary has to carry everything from the earlier turns it may still need.","You are given the summary so far (possibly empty) and the turns that came after it. Answer the updated summary, which replaces the old one.","Keep: the user's goals, preferences and constraints; decisions made and why; facts, names, ids, numbers, dates, file names and URLs that may matter later; what tools were used and their important results; open questions and unfinished work.","Drop greetings, repetition and anything later turns superseded. Do not invent anything, and do not answer the user.","Write terse prose or bullet points, in the language of the conversation."].join(" "),b1="[Summary of the earlier turns of this conversation, which are not shown:]",w1=8;class M0{ttlMs;threads=new Map;lastSweep=0;constructor(Z=86400000){this.ttlMs=Z}async loadSummaries(Z){this.sweep();let $=this.threads.get(Z);if(!$)return[];return $.touchedAt=Date.now(),$.summaries.slice()}async saveSummary(Z,$){this.sweep();let Q=this.threads.get(Z)??{summaries:[],touchedAt:Date.now()};Q.summaries=v1(Q.summaries,$),Q.touchedAt=Date.now(),this.threads.set(Z,Q)}delete(Z){this.threads.delete(Z)}sweep(Z=Date.now()){if(Z-this.lastSweep<60000)return;this.lastSweep=Z;for(let[$,Q]of this.threads)if(Z-Q.touchedAt>this.ttlMs)this.threads.delete($)}}function v1(Z,$){return[$,...Z.filter((Q)=>Q.cutMessageId!==$.cutMessageId)].slice(0,w1)}var N0=new M0;function h4(Z){let $=Z;return typeof $?.loadSummaries==="function"&&typeof $?.saveSummary==="function"}function R0(Z,$,Q){let B=A(Q.maxSummaryTokens)??T1,X=(G)=>Math.max(1,G-B),Y={...$,...A($.maxTokens)?{maxTokens:X($.maxTokens)}:{},...A($.maxBytes)?{maxBytes:Math.max(1,$.maxBytes-B*SZ)}:{}},J=y1($,Q),z={...Y,note:!1,...J?{maxTokens:Math.min(Y.maxTokens??1/0,X(J))}:{}};return{plain:Y,cut:u(Z,z),maxSummaryTokens:B}}function y1(Z,$){if($.triggerTokens===!1)return;let Q=A($.triggerTokens||void 0);if(Q)return Q;if(A(Z.maxTokens)||A(Z.maxBytes))return;return S1}async function _0(Z){let{history:$,window:Q,compact:B}=Z,{plain:X,cut:Y,maxSummaryTokens:J}=R0($,Q,B);if(Y.omittedTurns===0)return Y.messages;let z=`${$[Y.start].id}:${Y.start}`,G=Z.memo?.get(z);if(G===void 0){try{G=await c1(Z,Y.start,J)}catch(F){if(Z.signal.aborted)throw F;G=null}if(!Z.signal.aborted)Z.memo?.set(z,G)}if(!G)return u($,X).messages;let V=$.length-Y.start,H=Y.messages.slice(0,Y.messages.length-V),q=Y.messages.slice(Y.messages.length-V),W=$[Y.start];return[...H,{id:`summary_${W.id}`,role:"user",content:[{type:"text",text:`${b1}
|
|
3
|
+
${G.text}`}],createdAt:W.createdAt},...q]}var C0="\x00next-turn";function I0(Z){let $=h1(Z).finally(()=>VZ.delete($));return VZ.add($),$}var VZ=new Set;async function h1(Z){try{let $={id:C0,role:"user",content:[{type:"text",text:""}],createdAt:new Date().toISOString()},Q=[...Z.history,$],B=[...Z.stored,$],{cut:X,maxSummaryTokens:Y}=R0(Q,Z.window,Z.compact);if(X.omittedTurns===0||Q[X.start].id===C0)return;let J=A0({...Z,history:Q,stored:B},X.start);if((await GZ(Z.store,Z.threadId)).some(J.matches))return;await T0(J,{...Z,history:Q,stored:B},X.start,Y).promise}catch{}}async function g4(){while(d.size>0||VZ.size>0)await Promise.allSettled([...VZ,...[...d.values()].map((Z)=>Z.promise)])}var d=new Map,E=new Map,g1=1000;function u1(Z,$){E.set(Z,O(E.get(Z)??j(),$));while(E.size>g1)E.delete(E.keys().next().value)}function O0(Z,$){let Q=E.get(Z);if(!Q)return;E.delete(Z),$(Q)}function A0(Z,$){let Q=Z.history[$].id,B=t1(Z.stored,$),X=B[$];return{key:`${Z.threadId}\x00${Q}\x00${X}`,fingerprints:B,matches:(Y)=>Y?.cutMessageId===Q&&Y.fingerprint===X}}async function c1(Z,$,Q){let B=A0(Z,$),X=(await GZ(Z.store,Z.threadId)).find(B.matches);if(X)return O0(B.key,Z.onUsage),X;let Y=T0(B,Z,$,Q);if(Y.owed)Z.onUsage(Y.owed),Y.owed=void 0;Y.payers.push(Z.onUsage);try{return await d1(Y.promise,Z.signal)}finally{Y.payers.splice(Y.payers.indexOf(Z.onUsage),1),O0(B.key,Z.onUsage)}}function T0(Z,$,Q,B){let X=d.get(Z.key);if(X)return X;let Y={promise:void 0,payers:[],owed:void 0},J=(z)=>{let G=Y.payers[0];if(G)G(z);else Y.owed=O(Y.owed??j(),z)};return Y.promise=(async()=>{let{store:z,threadId:G}=$,V=A($.compact.lockWaitMs)??k1,H=null;if(z.lockSummary){try{H=await z.lockSummary(G,$.history[Q].id,V+60000)}catch{H=null}if(!H)return m1($,Z.matches,V)}try{let q=await GZ(z,G),W=q.find(Z.matches);if(W)return W;return await l1($,q,Z.fingerprints,Q,B,J)}finally{if(H)await H().catch(()=>{})}})().catch(()=>null).finally(()=>{if(d.delete(Z.key),Y.owed)u1(Z.key,Y.owed);Y.owed=void 0}),d.set(Z.key,Y),Y}function d1(Z,$){if($.aborted)return Promise.reject($.reason);return new Promise((Q,B)=>{let X=()=>B($.reason);$.addEventListener("abort",X,{once:!0}),Z.then((Y)=>{$.removeEventListener("abort",X),Q(Y)},(Y)=>{$.removeEventListener("abort",X),B(Y)})})}async function GZ(Z,$){try{let Q=await Z.loadSummaries($);return Array.isArray(Q)?Q.filter(p1):[]}catch{return[]}}function p1(Z){let $=Z;return!!$&&typeof $.cutMessageId==="string"&&typeof $.text==="string"&&typeof $.fingerprint==="string"}async function m1(Z,$,Q){let B=Date.now()+Q;while(Date.now()<B){await new Promise((Y)=>setTimeout(Y,250));let X=(await GZ(Z.store,Z.threadId)).find($);if(X)return X}return null}async function l1(Z,$,Q,B,X,Y){let{history:J,compact:z}=Z,G=JZ(J),V=G.indexOf(B),H=new Map(G.map((_)=>[J[_].id,_])),q,W=0;for(let _ of $){let N=H.get(_.cutMessageId);if(N===void 0||N>=B||N<=W)continue;if(_.fingerprint!==Q[N])continue;q=_,W=N}let F=(A(z.chunkTokens)??x1)*SZ,K=i1(J,G,W,B,F),L=X*SZ,D=`${z.instructions??f1} Keep the summary under about ${Math.round(X*0.75)} words.`,U=q?.text??"",f=j();for(let _ of K){let N=await x0({provider:z.provider??Z.provider,instructions:D,prompt:`Summary so far:
|
|
4
4
|
${U||"(none yet: these are the first turns of the conversation)"}
|
|
5
5
|
|
|
6
6
|
The turns that came after it:
|
|
7
|
-
${_}`,output:
|
|
8
|
-
`);if(!L)return;if(
|
|
7
|
+
${_}`,output:kZ.object({summary:kZ.string()}),reasoning:z.reasoning??"low",signal:AbortSignal.timeout(E1)});if(f=O(f,N.usage),Y(N.usage),!N.ok)return null;U=c(N.output.summary.trim(),L)}if(!U)return null;let l={cutMessageId:J[B].id,text:U,turns:V<0?0:V,messages:B,fingerprint:Q[B],createdAt:new Date().toISOString(),usage:f};try{await Z.store.saveSummary(Z.threadId,l)}catch{}return l}var SZ=4;function i1(Z,$,Q,B,X){let Y=new Set,J=new Set($);for(let q=0;q<Z.length;q++)if(Z[q].role==="user"&&!J.has(q)&&q!==0)Y.add(Z[q].id);let z=Math.max(500,Math.min(20000,Math.floor(X/2))),G=[],V="",H=$.filter((q)=>q>=Q&&q<B);if(H.forEach((q,W)=>{let F=H[W+1]??B,K=[];for(let D=q;D<F;D++){let U=n1(Z[D],Y.has(Z[D].id),z);if(U)K.push(U)}let L=K.join(`
|
|
8
|
+
`);if(!L)return;if(V&&V.length+L.length+2>X)G.push(V),V="";V=V?`${V}
|
|
9
9
|
|
|
10
|
-
${L}`:L}),
|
|
11
|
-
`)}`:""}function
|
|
12
|
-
${await
|
|
10
|
+
${L}`:L}),V)G.push(V);return G}function n1(Z,$,Q){if(Z.role==="system")return"";let B=$?"Tool (file shown)":Z.role==="user"?"User":"Assistant",X=(Z.content??[]).map((Y)=>o1(Y,Q)).filter(Boolean);return X.length>0?`${B}: ${X.join(`
|
|
11
|
+
`)}`:""}function o1(Z,$){switch(Z.type){case"text":return c(Z.text??"",$);case"file":return`[file: ${Z.name??Z.mimeType??Z.fileId??"attachment"}]`;case"tool-call":return`[called ${Z.namespace?`${Z.namespace}.${String(Z.name)}`:String(Z.name)}(${c(xZ(Z.input),Math.min($,1000))})]`;case"tool-result":{let Q=Z.status==="ok"?xZ(Z.output):Z.status==="error"?`error: ${Z.error?.message??""}`:Z.status==="running"?`a background job (${Z.job?.id??"unknown"}) that was still running`:`${Z.status}${Z.reason?`: ${Z.reason}`:""}`;return`[${String(Z.name)} returned: ${c(Q,Math.min($,2000))}]`}case"output":return`[structured answer: ${c(xZ(Z.value),Math.min($,2000))}]`;default:return""}}function xZ(Z){if(typeof Z==="string")return Z;try{return JSON.stringify(Z)??""}catch{return String(Z)}}function c(Z,$){return Z.length<=$?Z:`${Z.slice(0,$)}\u2026[cut]`}function A(Z){return typeof Z==="number"&&Number.isFinite(Z)&&Z>0?Math.floor(Z):void 0}function t1(Z,$){let Q=["0"],B="";for(let X=0;X<$;X++){let Y;try{Y=JSON.stringify(Z[X])??""}catch{Y=String(Z[X]?.id)}B=j0(`${B}|${j0(Y)}`),Q.push(B)}return Q}function j0(Z){let $=3735928559,Q=1103547991;for(let B=0;B<Z.length;B++){let X=Z.charCodeAt(B);$=Math.imul($^X,2654435761),Q=Math.imul(Q^X,1597334677)}return $=Math.imul($^$>>>16,2246822507)^Math.imul(Q^Q>>>13,3266489909),Q=Math.imul(Q^Q>>>16,2246822507)^Math.imul($^$>>>13,3266489909),(4294967296*(2097151&Q)+($>>>0)).toString(36)}class v extends Error{pending;path;nested;constructor(Z){super(`A nested agent run is waiting on the user for ${Z.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Z.pending,this.path=Z.path,this.nested=Z.nested}}class WZ{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;timeoutMs;async;execute;constructor(Z){this.name=Z.name,this.description=Z.description,this.inputSchema=Z.inputSchema,this.outputSchema=Z.outputSchema,this.requiresApproval=Z.requiresApproval===!0,this.deferred=Z.deferred===!0,this.answeredBy=Z.answeredBy==="client"?"client":"server",this.execute=Z.execute??void 0,this.timeoutMs=Z.timeoutMs,this.async=Z.async}static create(Z){if(typeof Z.inputSchema!=="function")hZ(Z.inputSchema,`The tool "${Z.name}"`,"inputSchema");if(Z.timeoutMs!==void 0)qZ(Z.timeoutMs,`The tool "${Z.name}"`,"timeoutMs");if(Z.async?.deadlineMs!==void 0)qZ(Z.async.deadlineMs,`The tool "${Z.name}"`,"async.deadlineMs");if(Z.async&&Z.answeredBy==="client")throw Error(`The tool "${Z.name}" is answered by the client and cannot be \`async\`: background jobs are for tools the server runs.`);return new WZ(Z)}static ask(Z){return WZ.create({name:Z.name,description:Z.description,inputSchema:vZ,outputSchema:Z.outputSchema,answeredBy:"client"})}}var vZ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Z){let $=vZ.safeParse(Z);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Z){if(typeof Z!=="object"||Z===null||typeof Z.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Z.question}}}};class yZ{name;description;tools;deferred;constructor(Z){this.name=Z.name,this.description=Z.description,this.tools=Z.tools,this.deferred=Z.deferred===!0}static create(Z){return new yZ(Z)}}class p0{name;description;instructions;files;constructor(Z){this.name=Z.name,this.description=Z.description,this.instructions=Z.instructions,this.files=Z.files}static create(Z){return new p0(Z)}}var zZ="skills",s1="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.";function hZ(Z,$,Q){let B=Z?.toJSONSchema?.();if(B?.type==="object")return;let X=!B?"no JSON Schema":B.anyOf?"a union (`anyOf`) \u2014 `s.union(...)`":B.type!==void 0?`a schema of type ${JSON.stringify(B.type)}`:"an unconstrained schema (`s.json()`)";throw Error(`${$} declares an \`${Q}\` whose root is ${X}, but the provider only accepts an object there (OpenAI rejects \`anyOf\` or a non-object at the root of tool parameters and structured output). Wrap it in an object, e.g. \`s.object({ value: s.union([...]) })\`, and read \`.value\` off the result.`)}function qZ(Z,$,Q){if(typeof Z==="number"&&Z>0)return;throw Error(`${$} sets \`${Q}\` to ${String(Z)}, but it has to be a positive number of milliseconds. Use \`null\` for no limit.`)}function k0(Z){if(Z===void 0)return;if(Z===null||!Number.isFinite(Z))return null;return Z}var a1=2147483647;function S0(Z,$){if(Z===null||Z>a1)return()=>{};let Q=setTimeout($,Z);return()=>clearTimeout(Q)}function EZ(Z){if(Z<1000)return`${Z}ms`;if(Z<60000)return`${+(Z/1000).toFixed(1)}s`;return`${+(Z/60000).toFixed(1)}m`}var gZ={type:"object",properties:{},required:[],additionalProperties:!1},m0=600000;class KZ extends Error{code;retryable;status;requestId;toolCallId;runId;result;constructor(Z){super(Z.error.message);this.name="AgentRunError",this.code=Z.error.code,this.retryable=Z.error.retryable,this.status=Z.error.status,this.requestId=Z.error.requestId,this.toolCallId=Z.error.toolCallId,this.runId=Z.runId,this.result=Z}}var r1=8,e1=3;class l0{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;maxRunDurationMs;jobs;config;constructor(Z){this.name=Z.name,this.instructions=Z.instructions,this.provider=Z.provider,this.tools=Z.tools??[],this.skills=Z.skills??[],this.output=Z.output,this.maxSteps=Z.maxSteps??r1,this.maxDepth=Z.maxDepth??e1,this.reasoning=Z.reasoning,this.jobs=Z.jobs??{};let $=k0(Z.maxRunDurationMs);this.maxRunDurationMs=$===void 0?m0:$;let{registry:Q,providerTools:B}=Z4(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:Q,providerTools:B,output:Z.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,logErrors:Z.logErrors??!0,maxRunDurationMs:$,contextWindow:Z.contextWindow,prepareStep:Z.prepareStep?[Z.prepareStep]:[]}}static create(Z){if(Z.output)hZ(Z.output,`The agent "${Z.name}"`,"output");if(Z.maxRunDurationMs!=null)qZ(Z.maxRunDurationMs,`The agent "${Z.name}"`,"maxRunDurationMs");let $=Z.jobs?.contextBlock;if($&&$.max!==void 0&&!(Number.isInteger($.max)&&$.max>0))throw Error(`The agent "${Z.name}" sets \`jobs.contextBlock.max\` to ${String($.max)}, but it has to be a whole number above 0. Use \`contextBlock: false\` for no block.`);return new l0(Z)}stream(Z){let $={...this.config,provider:Z.provider??this.config.provider,maxSteps:Z.maxSteps??this.config.maxSteps,reasoning:Z.reasoning??this.config.reasoning,maxOutputTokens:Z.maxOutputTokens??this.config.maxOutputTokens,temperature:Z.temperature??this.config.temperature,maxRunDurationMs:Z.maxRunDurationMs!==void 0?k0(Z.maxRunDurationMs):this.config.maxRunDurationMs,contextWindow:Z.contextWindow===!1?void 0:Z.contextWindow??this.config.contextWindow,prepareStep:Z.prepareStep?[...this.config.prepareStep,Z.prepareStep]:this.config.prepareStep};if(Z.maxRunDurationMs!=null)qZ(Z.maxRunDurationMs,`Agent.stream for "${this.name}"`,"maxRunDurationMs");return new n0($,Z)}}function bZ(Z){let $=Z.inputSchema;return{name:Z.tool.name,description:Z.tool.description,parameters:$?$.toJSONSchema():gZ,strict:$?o($):!0,deferred:Z.deferred}}function fZ(Z){return typeof Z.inputSchema==="function"?void 0:Z.inputSchema}function Z4(Z,$){let Q=new Map,B=[],X=(Y)=>{if(Q.has(Y.tool.name))throw Error(`Two tools are named "${Y.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Q.set(Y.tool.name,Y)};for(let Y of Z){if(Y instanceof yZ){if(Y.name===zZ)throw Error(`"${zZ}" is reserved for the namespace skills are lowered into. Rename the namespace \u2014 silently shadowing it would make every skill unreachable with no error to read.`);let z=[];for(let G of Y.tools){let V={tool:G,namespace:Y.name,deferred:Y.deferred||G.deferred,inputSchema:fZ(G)};X(V),z.push(bZ(V))}B.push({name:Y.name,description:Y.description,tools:z});continue}let J={tool:Y,deferred:Y.deferred,inputSchema:fZ(Y)};X(J),B.push(bZ(J))}if($.length>0){let Y=[];for(let J of $){let z=$4(J);X({tool:z,namespace:zZ,deferred:!1,inputSchema:fZ(z)}),Y.push({name:J.name,description:J.description,parameters:gZ,strict:!0,deferred:!1})}B.push({name:zZ,description:s1,tools:Y})}return{registry:Q,providerTools:B}}function $4(Z){return WZ.create({name:Z.name,description:Z.description,inputSchema:{toJSONSchema:()=>gZ,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Q=[typeof Z.instructions==="function"?await Z.instructions():Z.instructions];for(let B of Z.files??[])Q.push(`--- ${B} ---
|
|
12
|
+
${await Q4(B)}`);return Q.join(`
|
|
13
13
|
|
|
14
|
-
`)}})}async function
|
|
14
|
+
`)}})}async function Q4(Z){try{return await Bun.file(Z).text()}catch($){return`(could not be read: ${$.message})`}}function B4(Z){return typeof Z==="object"&&Z!==null&&typeof Z.next==="function"&&Symbol.asyncIterator in Z}function E0(Z,$){let Q=[...Z],B=new Map(Q.map((X,Y)=>[X.id,Y]));for(let X of $){let Y=B.get(X.id);if(Y===void 0)B.set(X.id,Q.length),Q.push(X);else Q[Y]=X}return Q}function HZ(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 f0(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 b0(Z,$){return $===void 0?`"${Z}"`:`"${Z}" labelled "${$}"`}function i0(Z){return Z.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function X4(Z){if(Z.prompt!==void 0)return`user:${Z.prompt}`;let $=Z.messages?.[0];return $?`${$.role}:${i0($)}`:null}var w0=1;function Y4(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 J4(Z,$,Q){if(Z.agent!==$.name||Z.label!==Q.label)return`was ${b0(Z.agent,Z.label)} on the turn that escalated and is ${b0($.name,Q.label)} on the replay`;let B=X4(Q),X=Z.messages[0],Y=X?`${X.role}:${i0(X)}`:null;if(B!==null&&Y!==null&&B!==Y)return`was started with ${JSON.stringify(Y)} on the turn that escalated and with ${JSON.stringify(B)} on the replay`;return null}function v0(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 wZ{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 n0{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];compactMemo=new Map;lastStep;produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=j();finishReason="stop";failure;output;stopReason;timedOutAfter;cancelDeadline=()=>{};settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Z,$){this.config=Z,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];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",$.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:m0;this.cancelDeadline=S0(B,()=>this.expire(B)),this.settled=this.execute(),g0.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,Y=new ReadableStream({start:async(J)=>{X=u0(J);try{for await(let z of $){if(B)break;J.enqueue(Q.encode(`id: ${z.seq}
|
|
15
15
|
data: ${JSON.stringify(z.event)}
|
|
16
16
|
|
|
17
|
-
`)),X.touch()}}catch{}X.stop();try{
|
|
17
|
+
`)),X.touch()}}catch{}X.stop();try{J.close()}catch{}},cancel:()=>{B=!0,X.stop()}});return new Response(Y,{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(($)=>{if($.error)throw new KZ({...$,error:$.error});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 ${EZ(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{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 await this.loop()}catch($){if($ instanceof M||this.controller.signal.aborted)await this.finalizeAborted();else this.fail(this.config.provider.normalizeError($),S($)),await this.finalizeMessage("error"),this.finishReason="error"}this.cancelDeadline(),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,output:this.output,...Z?{error:Z}:{}}}async resolveToolSchemas(){let Z=[...this.config.registry.values()].filter((G)=>!G.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(G)=>{try{let V=G.tool.inputSchema,H=await V($);hZ(H,`The tool "${G.tool.name}"`,"inputSchema"),Q.set(G.tool.name,H);return}catch(V){return`"${G.tool.name}": ${V instanceof Error?V.message:String(V)}`}}));if(this.controller.signal.aborted)throw new M;let X=B.filter((G)=>G!==void 0);if(X.length>0)return{code:"tool_error",message:`Could not resolve the input schema of ${X.join("; ")}`,retryable:!1};let Y=new Map;for(let[G,V]of this.config.registry)Y.set(G,Q.has(G)?{...V,inputSchema:Q.get(G)}:V);let J=(G)=>Q.has(G.name)?bZ(Y.get(G.name)):G,z=this.config.providerTools.map((G)=>("tools"in G)?{...G,tools:G.tools.map(J)}:J(G));this.config={...this.config,registry:Y,providerTools:z};return}fail(Z,$={}){let Q={...Z,...$};this.failure=Q,this.emit({type:"error",error:this.redact(Q,{source:"run",failure:Q})})}redact(Z,$){let Q=mZ(this.params.redactError,Z,$,(B)=>this.writeLog(`[gemi/ai] agent "${this.config.name}" redactError threw`,{error:B}));return iZ(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{p.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;$++){let Q=this.startMessage(),B=await this.runStep(Q,$);if(this.lastStep={reason:B.reason,usage:Q.usage},B.error){this.fail(B.error,B.detail),await this.finalizeMessage("error"),this.finishReason="error";return}let X=Q.content.filter((J)=>J.type==="tool-call");if(X.length===0){this.finishReason=B.reason,await this.finalizeMessage(B.reason);return}let Y=await this.runTools(Q,X,$);if(Y.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:Y});return}if($===Z){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(B.reason)}}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=r(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,X=await this.prepareRequest(Z,$);if("error"in X)return{reason:"error",error:X.error};let Y={reason:"stop"},J=new Map,z=[],G=()=>{if(z.length===0)return{};let F=z;return z=[],{toolSearches:F}},V="",q=B.stream({messages:X.messages,systemPrompt:X.instructions,tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?s(this.config.output):void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:Q})[Symbol.asyncIterator]();for(;;){let F=await x(Promise.resolve(q.next()),Q);if(F.done)break;let K=F.value;switch(K.type){case"text-delta":{h(Z,"text",K.delta),this.emit({type:"text-delta",messageId:Z.id,delta:K.delta});break}case"reasoning-delta":{e(Z,K.id,K.delta),this.emit({type:"reasoning-delta",messageId:Z.id,delta:K.delta,id:K.id});break}case"output-delta":{V+=K.delta,this.emit({type:"output-delta",messageId:Z.id,delta:K.delta,snapshot:t(V)});break}case"tool-search":{z.push({namespaces:K.namespaces,loaded:K.loaded,...K.arguments!==void 0?{arguments:K.arguments}:{}}),this.emit({type:"tool-search",loaded:K.loaded});break}case"tool-call-delta":{let L=J.get(K.toolCallId)??{name:K.name,args:""};L.args+=K.argsDelta,L.name=K.name||L.name,L.namespace=K.namespace||L.namespace,J.set(K.toolCallId,L),this.emit({type:"tool-call",messageId:Z.id,part:{type:"tool-call",toolCallId:K.toolCallId,name:L.name,input:t(L.args),partial:!0,...L.namespace?{namespace:L.namespace}:{}}});break}case"tool-call":{let L=K.namespace||J.get(K.toolCallId)?.namespace;J.delete(K.toolCallId);let D={type:"tool-call",toolCallId:K.toolCallId,name:K.name,input:h0(K.args),...L?{namespace:L}:{},...G()};Z.content.push(D),this.emit({type:"tool-call",messageId:Z.id,part:D});break}case"finish":{if(this.usage=O(this.usage,K.usage),Z.usage=O(Z.usage??j(),K.usage),!Y.error)Y={reason:K.reason};break}case"error":{Y={reason:"error",error:K.error,detail:S(K)};break}case"file-rejected":{this.markFileRejected(K.fileId,K.message,S(K));break}}}for(let[F,K]of J){let L={type:"tool-call",toolCallId:F,name:K.name,input:h0(K.args),...K.namespace?{namespace:K.namespace}:{},...G()};Z.content.push(L),this.emit({type:"tool-call",messageId:Z.id,part:L})}let W=Y.reason==="length";if(W)this.outputTruncated=!0;if(this.config.output&&V&&!Y.error&&!W){let F=a(this.config.output,V);if(F.ok===!0)this.output=F.value,Z.content.push({type:"output",value:F.value});else this.emit({type:"error",error:F.error})}return Y}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||N0}}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($)I0($)}catch{}}async prepareRequest(Z,$){let Q=this.historyForProvider(Z),B=this.config.contextWindow,X=this.compactJobParams(Q,Z),Y=!B?Q:X?await _0({...X,signal:this.controller.signal,onUsage:(z)=>{this.usage=O(this.usage,z)},memo:this.compactMemo}):u(Q,B).messages,J=await this.systemPrompt();for(let z of this.config.prepareStep){let G;try{G=await z({step:$,messages:[...Y],history:[...Q],instructions:J,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(V){if(V instanceof M||this.controller.signal.aborted)throw V;return{error:{code:"unknown",message:`prepareStep threw: ${V instanceof Error?V.message:String(V)}`,retryable:!1}}}if(!G)continue;if(G.messages!==void 0){if(!Array.isArray(G.messages))return{error:{code:"unknown",message:"prepareStep answered `messages` that is not an array.",retryable:!1}};Y=G.messages}if(G.instructions!==void 0)J=G.instructions||void 0}return{messages:Y,instructions:J}}async systemPrompt(){let Z=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Z.length>0?Z.join(`
|
|
18
18
|
|
|
19
|
-
`):void 0}async runTools(Z,$,Q){let B=[],X=[];for(let Y of $){let G=this.config.registry.get(String(Y.name));if(!G){this.addResult(Z,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let z=G.inputSchema.safeParse(Y.input);if(z.ok===!1){this.addResult(Z,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${z.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=z.value;let V=y0(G.tool);if(V){if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(Y));continue}B.push({toolCallId:Y.toolCallId,name:Y.name,input:z.value,kind:V,signature:X0(this.claimsFor(Y.toolCallId,String(Y.name),V,z.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}X.push(this.executeTool(G,Z.id,Y,z.value,Q).then(async(J)=>{this.addResult(Z,J),await this.settleShown(Y.toolCallId)}).catch((J)=>{if(J instanceof v){if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(Y));return}B.push(...J.pending);return}}))}return await T(Promise.all(X).then(()=>{return}),this.controller.signal),B}claimsFor(Z,$,Q,B){return{runId:this.signingRunId,toolCallId:Z,name:$,kind:Q,input:B,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy(Z){return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"refused",reason:`"${String(Z.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Z,$,Q,B,X,Y){let G=Z.tool.timeoutMs;if(G===void 0)return this.runToolBody(Z,$,Q,B,X,Y,this.controller.signal,()=>!1);let z=new AbortController,V=this.controller.signal,J=()=>z.abort(V.reason);if(V.aborted)J();else V.addEventListener("abort",J,{once:!0});let H=!1,q=this.runToolBody(Z,$,Q,B,X,Y,z.signal,()=>H),W=()=>{},F=new Promise((K)=>{W=x0(G,()=>{let L=`"${String(Q.name)}" did not finish within ${EZ(G)} (timeoutMs: ${G}) and was cancelled.`;z.abort(new DOMException(L,"TimeoutError")),K({type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"error",error:{code:"timeout",message:L,toolCallId:Q.toolCallId,retryable:!0}})})});q.catch(()=>{});try{return await Promise.race([q,F])}finally{H=!0,W()}}async runToolBody(Z,$,Q,B,X,Y,G,z){let V=this.toolFiles(Q,G),J={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Q.toolCallId,signal:G,step:X,depth:this.depth,resumed:Y!==void 0,attachments:V.attachments,generateImage:V.generateImage,editImage:V.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Q,G,Y),generate:(H)=>this.generateForTool(H,G,Q.toolCallId),jobs:d0({jobs:this.depth===0?this.params.jobs:void 0,threadId:this.params.threadId,runId:this.runId,toolCallId:Q.toolCallId,toolName:String(Q.name),depth:this.depth,async:Z.tool.async,attachments:this.params.attachments??null})};try{let H=Z.tool.execute(B,J),q;if(Q4(H)){let W=await H.next();while(!W.done){if(z())throw H.return(void 0).catch(()=>{}),new M;this.emit({type:"tool-progress",toolCallId:Q.toolCallId,data:W.value}),W=await H.next()}q=W.value}else q=await H;if(c0(q)){if(q.toolCallId!==Q.toolCallId)throw new P(`"${String(Q.name)}" returned the handle of a job another tool call started. Return the handle from this call's own ctx.jobs.`,{retryable:!1});return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"running",job:{id:q.id,...q.summary!==void 0?{summary:q.summary}:{}}}}return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"ok",output:q}}catch(H){if(H instanceof M||this.controller.signal.aborted)throw new M;if(H instanceof v)throw H;let q=H instanceof P;if(!q&&this.config.logErrors)this.logToolFailure(Q,H);let W={code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Q.toolCallId,retryable:q?H.retryable:!0};return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"error",error:this.redact(W,{source:"tool",toolName:String(Q.name),cause:H})}}}async generateForTool(Z,$,Q){let B=this.controller.signal;return m({...Z,signal:Z.signal?AbortSignal.any([$,Z.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Q},settled:(X)=>{if(this.usage=O(this.usage,X.usage),B.aborted)throw new M}})}nestedRunner(Z,$,Q,B){let X=new wZ(()=>$.nested,()=>$.nested=[]);return async(Y,G={})=>{let{at:z,recorded:V,write:J}=X.next();if(V){let H=Y4(V,Y,G);if(H)throw new P(`Nested run ${z} of "${String($.name)}" ${H}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??j(),output:f0(V.messages),nested:V}}return this.runNested(Z,$,Q,Y,G,J,V,B?.answers??[])}}async runNested(Z,$,Q,B,X,Y,G,z){let V=[...this.chain,B.name];if(this.chain.includes(B.name))throw new P(`"${B.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let J=this.depth+1;if(J>this.maxDepth)throw new P(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${J}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let H=X.label,q=[...this.pathPrefix,$.toolCallId],W=this.onPending==="deny"?"deny":X.onPending??"escalate",F=G!==void 0,K=F?HZ(G.messages):new Set,L=F?z.filter((C)=>{let I=v0(C.path,q);if(I===null)return!1;return K.has(I.length>0?I[0]:C.toolCallId)}):[],D=B.stream({messages:F?G.messages:X.messages??[],turn:F?{toolResults:L}:X.prompt?{text:X.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Q,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:X.instructions,maxOutputTokens:X.maxOutputTokens,temperature:X.temperature,runId:F?G.runId:void 0,nesting:{depth:J,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:q,onPending:W}}),U=[],f=(C)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:D.runId,agent:B.name,label:H,event:C}),i=(async()=>{for await(let C of D){if(C.type==="awaiting-input")U=C.pending;if(f(C),C.type==="run-start"&&!F)for(let I of X.messages??[])f({type:"message",message:I});if(C.type==="error")this.emit({type:"error",error:C.error,nested:{toolCallId:$.toolCallId,runId:D.runId,agent:B.name}})}})(),_=(async()=>{let C=await D.result();await i;let I=F?E0(G.messages,C.messages):E0(X.messages??[],C.messages),dZ={runId:D.runId,agent:B.name,label:H,messages:I,finishReason:C.finishReason,usage:F?O(G.usage??j(),C.usage):C.usage,...C.finishReason==="awaiting-input"?{signature:z0({runId:this.signingRunId,path:q,nestedRunId:D.runId,open:[...HZ(I)],input:$.input,subject:this.params.subject??null})}:{}};return Y(dZ),this.usage=O(this.usage,C.usage),{result:C,record:dZ}})(),N=_.then(()=>{return},()=>{return});this.nestedSettling.add(N);let b,k;try{({result:b,record:k}=await _)}finally{this.nestedSettling.delete(N)}if(this.controller.signal.aborted)throw new M;if(b.finishReason==="awaiting-input"){if(U.length===0)throw new P(`"${B.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Z,part:$,resent:!0}),new v({pending:U,path:q,nested:k})}return{runId:k.runId,agent:B.name,messages:k.messages,finishReason:b.finishReason,usage:k.usage??j(),output:b.output??f0(k.messages),...b.error?{error:b.error}:{},nested:k}}addResult(Z,$){Z.content.push($),this.emit({type:"tool-result",messageId:Z.id,part:$})}toolFiles(Z,$){let Q=this.params.attachments??null,B=new wZ(()=>Z.attachments,()=>Z.attachments=[],()=>({failed:!0})),X=()=>{if(!Q)throw new w("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Q},Y=async(J,H,q)=>{let W=X(),F=H.mimeType||J.type||"",K=H.name??(J instanceof File?J.name:"attachment"),L;if(H.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw new P(`"${String(Z.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);L=await U.upload(new File([J],K,{type:F||void 0}))}return{attachment:await W.put(J,{name:K,mimeType:F,fileId:L}),...q?{generated:q}:{},...L?{shown:{fileId:L,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},G=(J,H,q)=>{let W=J.generated?"image":"put";if(W===H)return;throw new P(`Attachment ${q} of "${String(Z.name)}" was ${W==="image"?"a generated image":"a stored file"} on the first attempt and is ${H==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},z=async(J,H,q)=>{let{at:W,recorded:F,write:K}=B.next();if(F&&"attachment"in F){if(G(F,"image",W),F.shown)this.queueShown(Z.toolCallId,F);return{attachment:F.attachment,size:F.generated.size,mimeType:F.attachment.mimeType,usage:F.generated.usage}}let L=await q();this.usage=O(this.usage,L.usage);let D=L.mimeType==="image/jpeg"?"jpg":"png",U=await Y(L.image,{name:H.name??`${J.name}.${D}`,mimeType:L.mimeType,...H.showModel?{showModel:!0}:{}},{size:L.size,usage:L.usage});if(K(U),U.shown)this.queueShown(Z.toolCallId,U);return{attachment:U.attachment,size:L.size,mimeType:L.mimeType,usage:L.usage}},V=async(J)=>typeof J==="string"?await X().file(J):J;return{generateImage:(J,H)=>z(J,H,()=>J.generate({...H,signal:$})),editImage:(J,H)=>z(J,H,async()=>{let{images:q,mask:W,...F}=H;return await J.edit({...F,images:await Promise.all(q.map(V)),...W?{mask:await V(W)}:{},signal:$})}),attachments:{get:(J)=>X().get(J),read:(J)=>X().read(J),file:(J)=>X().file(J),put:async(J,H={})=>{let{at:q,recorded:W,write:F}=B.next();if(W&&"attachment"in W){G(W,"put",q);let L=X4(W,J,H);if(L)throw new P(`Attachment ${q} of "${String(Z.name)}" ${L}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(W.shown)this.queueShown(Z.toolCallId,W);return W.attachment}let K=await Y(J,H);if(F(K),K.shown)this.queueShown(Z.toolCallId,K);return K.attachment}}}}toolTurn(Z){let $=this.history.findIndex((Y)=>Y.id===Z),Q=YZ(this.history),B;for(let Y=$-1;Y>=0;Y--){let G=this.history[Y];if(G.role!=="user"||Q.has(G.id))continue;B=G;break}let X=[];for(let Y of B?.content??[]){if(Y.type!=="file")continue;let G=Y.attachmentId;if(typeof G!=="string"||!G.startsWith(CZ))continue;if(!X.includes(G))X.push(G)}return Object.freeze({attachments:Object.freeze(X)})}queueShown(Z,$){let Q=$.shown;if(!Q)return;let B=this.shownQueue.get(Z)??[];if(B.some((X)=>X.id===Q.messageId))return;B.push({id:Q.messageId,role:"user",content:[{type:"file",fileId:Q.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Q.createdAt,finishReason:"stop"}),this.shownQueue.set(Z,B)}async settleShown(Z){let $=this.shownQueue.get(Z);if(!$||$.length===0)return;if(this.shownQueue.delete(Z),this.ended||this.controller.signal.aborted)return;for(let Q of $){if(this.history.some((B)=>B.id===Q.id))continue;this.history.push(Q),this.produced.push(Q),this.emit({type:"message",message:Q}),this.unreported.add(Q)}}historyForProvider(Z){let $=this.history.filter((Y)=>Y!==Z),Q=YZ($),B=[];for(let Y of $){if(!Q.has(Y.id))continue;for(let G of Y.content)if(G.type==="file")B.push(G)}if(B.length<=w0)return $;let X=new Set(B.slice(0,B.length-w0));return $.map((Y)=>{if(!Y.content.some((G)=>G.type==="file"&&X.has(G)))return Y;return{...Y,content:Y.content.map((G)=>G.type==="file"&&X.has(G)?{type:"text",text:`[A ${G.mimeType||"file"} produced by a tool (attachment ${G.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:G)}})}async ingestTurn(){let Z=this.params.turn,$=this.openCalls(),Q=[];if($.length>0){let B=new Set,X=new Set,Y=new Map;for(let G of Z?.toolResults??[]){let z=`${(G.path??[]).join("/")}#${G.toolCallId}`;if(X.has(z))continue;X.add(z);let V=(W)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:W,toolCallId:G.toolCallId,retryable:!1}}),J=v0(G.path,this.pathPrefix);if(J===null){V(`The answer for "${G.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(J.length>0){let W=J[0],F=$.find((D)=>D.call.toolCallId===W);if(!F){V(`No pending tool call with id "${W}" to deliver a nested answer to.`);continue}let K=this.parkedBelow(F.call,J,G.toolCallId);if(K.ok===!1){let D=`The answer for "${G.toolCallId}" is addressed under "${W}", which`;V(K.reason==="unparked"?`${D} has no sub-agent run waiting on that question.`:K.reason==="expired"?`${D} parked a sub-agent run that has since expired. Ask again.`:`${D} carries a record of a parked sub-agent run the server did not sign.`);continue}let L=Y.get(W);if(!L){if(!await this.spend(K0,K.signature)){V(`The answer for "${G.toolCallId}" is addressed under "${W}", which has already been re-entered on that record. Ask again.`);continue}L=[],Y.set(W,L),B.add(W)}L.push(G);continue}let H=$.find((W)=>W.call.toolCallId===G.toolCallId);if(!H){V(`No pending tool call with id "${G.toolCallId}".`);continue}let q=await this.resolveAnswer(H,G,Q);if(q===null)continue;if(B.add(G.toolCallId),q!=="open")this.attachToHistory(H,q),await this.settleShown(G.toolCallId)}for(let[G,z]of Y){let V=$.find((H)=>H.call.toolCallId===G),J=await this.reenter(V,z,Q);if(J)this.attachToHistory(V,J),await this.settleShown(G)}for(let G of $){if(B.has(G.call.toolCallId))continue;this.attachToHistory(G,{type:"tool-result",toolCallId:G.call.toolCallId,name:G.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Z&&(Z.text||Z.files&&Z.files.length>0)){let B={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Z.text?[{type:"text",text:Z.text}]:[],...(Z.files??[]).map((X)=>({type:"file",...X.fileId?{fileId:X.fileId}:{},name:X.name,mimeType:X.mimeType,...X.attachmentId?{attachmentId:X.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(B),this.produced.push(B),this.depth>0)this.emit({type:"message",message:B});else if(Z.localId)this.emit({type:"message-id",localId:Z.localId,messageId:B.id,message:B});if(await this.report(B),this.params.onTurn)try{await this.params.onTurn(B)}catch{}}return Q}parkedBelow(Z,$,Q){let B=$.length>1?$[1]:Q,X=[...this.pathPrefix,Z.toolCallId],Y=(Z.nested??[]).find((z)=>z.finishReason==="awaiting-input"&&HZ(z.messages).has(B));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let G=H0(Y.signature,{path:X,nestedRunId:Y.runId,open:[...HZ(Y.messages)],input:Z.input,subject:this.params.subject??null});if(G.ok===!1)return{ok:!1,reason:G.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Z,$,Q){let B=String(Z.call.name),X=this.config.registry.get(B);if(!X||!X.tool.execute)return{type:"tool-result",toolCallId:Z.call.toolCallId,name:Z.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${B}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Z.call.toolCallId,retryable:!1}};let Y=X.inputSchema.safeParse(Z.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Z.call.toolCallId,name:Z.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${B}": ${Y.errors.join(", ")}`,toolCallId:Z.call.toolCallId,retryable:!0}};let G=this.amendCall(Z);G.input=Y.value;try{return await T(this.executeTool(X,Z.message.id,G,Y.value,0,{answers:$}),this.controller.signal)}catch(z){if(z instanceof v)return Q.push(...z.pending),null;throw z}}amendCall(Z){let $=this.amend(Z.message),Q=$.content.indexOf(Z.call),B={...Z.call,nested:(Z.call.nested??[]).map((X)=>({...X})),...Z.call.attachments?{attachments:Z.call.attachments.map((X)=>({...X}))}:{}};if(Q>=0)$.content[Q]=B;return this.unreported.add($),B}openCalls(){let Z=new Set;for(let Q of this.history)for(let B of Q.content)if(B.type==="tool-result")Z.add(B.toolCallId);let $=[];for(let Q of this.history)for(let B of Q.content)if(B.type==="tool-call"&&!Z.has(B.toolCallId))$.push({message:Q,call:B});return $}async spend(Z,$){try{return await Z($,this.params.nonces??DZ)}catch(Q){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Q}),!1}}async recordReceipt(Z,$){let Q=await $;try{await Z.store.complete(Z.id,Q,Z.expiresAt)}catch(B){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:B})}return Q}async resolveAnswer(Z,$,Q){let B=Z.call,X=String(B.name),Y=this.config.registry.get(X),G=(q)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:q,toolCallId:B.toolCallId,retryable:!1}}),null};if(!Y)return G(`The tool "${X}" no longer exists, so its answer cannot be checked.`);let z=y0(Y.tool);if(!z)return G(`"${X}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return G(`The answer for "${X}" carried no signature.`);let V=IZ($.signature);if(!V)return G(`The signature for "${X}" is malformed.`);let J=Y0($.signature,{...this.claimsFor(B.toolCallId,X,z,B.input),runId:V.runId});if(J.ok===!1)return G(J.reason==="expired"?`The approval for "${X}" has expired. Ask again.`:`The answer for "${X}" does not match the call the server made.`);let H;if(this.params.receipts&&z==="approval"&&"approve"in $&&$.approve===!0){let q=this.params.receipts,W=W0(this.config.name,{...this.claimsFor(B.toolCallId,X,z,B.input),runId:V.runId}),F;try{F=await q.claim(W,V.expiresAt)}catch(K){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:K}),G(`The approval for "${X}" could not be checked. Ask again.`)}if(F.status==="replay")return{...F.result,toolCallId:B.toolCallId,name:B.name};if(F.status==="blocked")return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"tool_error",message:`"${X}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:B.toolCallId,retryable:!1}};H={store:q,id:W,expiresAt:V.expiresAt}}if(!await this.spend(q0,$.signature))return await H?.store.release(H.id).catch((q)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:q})}),G(`The answer for "${X}" has already been used. Ask again.`);if("approve"in $){if(z!=="approval")return G(`"${X}" is answered by the client, not approved.`);if($.approve===!0){let q=this.amendCall(Z),W=this.executeTool(Y,Z.message.id,q,q.input,0);try{return await T(H?this.recordReceipt(H,W):W,this.controller.signal)}catch(F){if(F instanceof v)return Q.push(...F.pending),"open";throw F}}return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(z==="approval")return G(`"${X}" is approved, not answered: the server produces its result.`);let q=Y.tool.outputSchema,W=q?q.safeParse($.output):{ok:!0,value:$.output};if(W.ok===!1)return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${X}" did not match its output schema: ${W.errors.join(", ")}`,toolCallId:B.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"ok",output:W.value}}return G(`The answer for "${X}" carried neither an approval nor an output.`)}attachToHistory(Z,$){let Q=this.amend(Z.message);Q.content.push($),this.unreported.add(Q),this.emit({type:"tool-result",messageId:Q.id,part:$})}markFileRejected(Z,$,Q){for(let G of this.history){if(!G.content.some((J)=>J.type==="file"&&J.fileId===Z&&!J.providerRejected))continue;let V=this.produced.includes(G)?G:this.amend(G);if(V.content=V.content.map((J)=>J.type==="file"&&J.fileId===Z&&!J.providerRejected?{...J,providerRejected:!0}:J),V!==this.current)this.unreported.add(V)}if(!this.config.logErrors)return;let B=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Z}${Q.status!==void 0?` (${Q.status})`:""}; it was left out of the request and will not be sent again: ${$}`,X={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Z,...Q},Y=!1;try{p.warning(B,X),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.warn(B,X)}amend(Z){let $=this.amended.get(Z.id);if($)return $;let Q={...Z,content:[...Z.content]},B=this.history.indexOf(Z);if(B>=0)this.history[B]=Q;return this.produced.push(Q),this.amended.set(Z.id,Q),Q}async reportDeferred(){let Z=[...this.unreported];this.unreported.clear();for(let $ of Z)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Z=this.current;if(Z){let $=new Set(Z.content.filter((Q)=>Q.type==="tool-result").map((Q)=>Q.toolCallId));for(let Q of[...Z.content]){if(Q.type!=="tool-call"||$.has(Q.toolCallId))continue;delete Q.partial,this.addResult(Z,{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"stopped",reason:this.stopReason})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${EZ(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function y0(Z){if(Z.answeredBy==="client")return Z.inputSchema===vZ?"question":"client";return Z.requiresApproval?"approval":null}function h0(Z){if(!Z||!Z.trim())return{};try{return JSON.parse(Z)}catch{return Z}}function T0(Z){return m(Z)}async function m(Z,$={}){let Q=`gen_${crypto.randomUUID()}`,B=await J4(Z);if($.settled?.(B),!B.ok){if(Z.logErrors!==!1&&B.error.code!=="aborted")G4(Q,B.error,$.origin);if(Z.throwOnError)throw new KZ({runId:Q,messages:B.messages,finishReason:B.finishReason,usage:B.usage,error:B.error})}return B}function G4(Z,$,Q){let B=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,X={...Q,generateId:Z,error:$},Y=!1;try{p.error(B,X),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.error(B,X)}async function J4(Z){let $=Z.messages??[];if($.length===0&&!Z.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Q=[...$];if(Z.prompt)Q.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Z.prompt}],createdAt:new Date().toISOString()});let B={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},X=Z.signal??new AbortController().signal,Y=j(),G="stop",z,V={},J="";try{let F=Z.provider.stream({messages:[...Q],systemPrompt:Z.instructions?.trim()?Z.instructions:void 0,output:s(Z.output),reasoning:Z.reasoning,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,signal:Z.signal})[Symbol.asyncIterator]();try{for(;;){let K=await T(Promise.resolve(F.next()),X);if(K.done)break;let L=K.value;switch(L.type){case"output-delta":J+=L.delta;break;case"text-delta":h(B,"text",L.delta);break;case"reasoning-delta":e(B,L.id,L.delta);break;case"finish":if(Y=O(Y,L.usage),!z)G=L.reason;break;case"error":G="error",z=L.error,V=x(L);break}}}finally{if(X.aborted)Promise.resolve(F.return?.()).catch(()=>{})}}catch(W){if(W instanceof M||X.aborted)G="aborted",z=V4(X);else G="error",z=Z.provider.normalizeError(W),V=x(W)}let H=!1,q;if(!z)if(G==="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(!J.trim())z={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let W=a(Z.output,J);if(W.ok===!0)H=!0,q=W.value;else z=W.error}if(H)B.content.push({type:"output",value:q});else if(J)h(B,"text",J);for(let W of B.content)if((W.type==="text"||W.type==="reasoning")&&typeof W.text==="string")W.text=r(W.text);if(B.finishReason=G,B.usage=Y,Q.push(B),H)return{ok:!0,output:q,messages:Q,usage:Y,finishReason:G};return{ok:!1,error:{...z,...V},messages:Q,usage:Y,finishReason:G}}function V4(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 e0=Symbol.for("gemi.ai.JobHandle");class Z1{id;toolCallId;summary;deadlineAt;[e0]=!0;constructor(Z,$,Q,B){this.id=Z;this.toolCallId=$;this.summary=Q;this.deadlineAt=B}}function c0(Z){return typeof Z==="object"&&Z!==null&&Z[e0]===!0}class uZ extends P{code="jobs_require_thread";constructor(Z){super(Z,{retryable:!1});this.name="JobsRequireThreadError"}}var y=new jZ,z4=["running","ok","error"],cZ={get store(){return y},use(Z){y=Z},get(Z){return y.get(Z)},async settle(Z,$){return FZ(y,Z,$)},async fail(Z,$){return FZ(y,Z,{error:$})},async sweep(Z={}){let $=y,Q=Z.limit??100,B=await H4($),X=0;for(let Y of await $.overdue(B,Q))if(await W4($,Y))X++;return X}};async function H4(Z){return Z.now?await Z.now():Date.now()}function W4(Z,$){return 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}})}async function FZ(Z,$,Q){let B=await Z.get($);if(!B||B.state!=="running")return!1;let X=Q.usage?O(B.usage??j(),Q.usage):void 0;if("error"in Q)return Z.transition($,["running"],{state:"error",error:q4(B,Q.error),...X?{usage:X}:{}});return Z.transition($,["running"],{state:"ok",output:$1(Q.output,B),...X?{usage:X}:{}})}function q4(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 P?$.retryable:!0};if(!($ instanceof P))console.error(`The background job ${Z.job??"(tracked)"} for "${Z.toolName}" failed.`,$);return n(Q,{source:"tool",toolName:Z.toolName,cause:$})}return{code:$.code??"tool_error",message:String($.message),toolCallId:Z.toolCallId,retryable:$.retryable??!0}}function $1(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 K4=3600000;function d0(Z){let $=null,Q=(B,X,Y={})=>{if(Z.async===void 0)throw new P(`"${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 uZ(`"${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 uZ(`"${Z.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if($)throw new P(`"${Z.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let G=Y.deadlineMs??Z.async.deadlineMs??K4;if(!Number.isFinite(G)||G<=0)throw new P(`A job's deadlineMs must be a positive number; got ${G}.`);let{jobs:z,threadId:V}=Z;return $=(async()=>{let J=cZ.store,H=(await J.listForThread(V,{limit:50})).find((F)=>F.toolCallId===Z.toolCallId);if(H)return o0(H);let q=async()=>{let F=await J.create({id:`ajob_${crypto.randomUUID()}`,threadId:V,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:z.owner,job:B?B.name:null,...Y.summary!==void 0?{summary:$1(Y.summary,Z)}:{},attachmentScope:Z.attachments?.scopeKey??null,deadlineMs:G});if(B)try{await F4(B,{jobId:F.id,args:X})}catch(K){if(J.transaction)throw K;throw await J.transition(F.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${Z.toolName}" could not be queued.`,toolCallId:Z.toolCallId,retryable:!0}}).catch(()=>{}),K}return F},W=J.transaction?await J.transaction(q):await q();return o0(W)})(),$};return{start:(B,X,Y)=>Q(B,X,Y),track:(B)=>Q(null,void 0,B)}}function o0(Z){return new Z1(Z.id,Z.toolCallId,Z.summary,Z.deadlineAt)}function F4(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start an AgentJob with no `static name`.");return l(a0).push(Z,JSON.stringify([$]))}class L4 extends r0{attachments=oZ;attachmentStorage=s0;constructor(){super();let Z=this.run;this.run=($)=>this.$runEnvelope($,Z)}onDeadletter(Z,...$){let Q=$[0];if(!Q?.jobId)return;FZ(cZ.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=cZ.store,B=await Q.get(Z.jobId);if(!B||B.state!=="running")return;let X=new Q1(B,this),Y;try{Y=await $.call(this,Z.args,X)}catch(G){throw await t0(Q,B.id,X.usage),G}if(this.$outcome)return await t0(Q,B.id,X.usage),Y;return await FZ(Q,B.id,{output:Y,usage:X.usage}),Y}}async function t0(Z,$,Q){if(Q.totalTokens===0&&Q.inputTokens===0&&Q.outputTokens===0)return;let B=await Z.get($);if(!B)return;await Z.transition($,z4,{usage:O(B.usage??j(),Q)}).catch(()=>{})}class Q1{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=j();attachments;constructor(Z,$){this.id=Z.id,this.threadId=Z.threadId,this.toolCallId=Z.toolCallId,this.toolName=Z.toolName,this.owner=Z.owner,this.summary=Z.summary;let Q=Z.attachmentScope?new OZ($.attachments,$.attachmentStorage,{key:Z.attachmentScope}):null,B=()=>{if(!Q)throw new w("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Q};this.attachments={put:(X,Y={})=>B().put(X,Y),get:(X)=>B().get(X),read:(X)=>B().read(X),file:(X)=>B().file(X)}}generate(Z){return m(Z,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:($)=>{this.usage=O(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,...Y}=$,G=async(V)=>typeof V==="string"?await this.attachments.file(V):V,z=await Z.edit({...Y,images:await Promise.all(B.map(G)),...X?{mask:await G(X)}:{},signal:this.signal});return this.park(Z,z,Q)}async park(Z,$,Q){this.usage=O(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}}}
|
|
20
|
-
export{pZ as Xb,B1 as Yb,DZ as Zb,g as _b,R as $b,j as ac,O as bc,P as cc,n as dc,
|
|
19
|
+
`):void 0}async runTools(Z,$,Q){let B=[],X=[];for(let Y of $){let J=this.config.registry.get(String(Y.name));if(!J){this.addResult(Z,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(Y.name)}".`,toolCallId:Y.toolCallId,retryable:!0}});continue}let z=J.inputSchema.safeParse(Y.input);if(z.ok===!1){this.addResult(Z,{type:"tool-result",toolCallId:Y.toolCallId,name:Y.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(Y.name)}": ${z.errors.join(", ")}`,toolCallId:Y.toolCallId,retryable:!0}});continue}Y.input=z.value;let G=y0(J.tool);if(G){if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(Y));continue}B.push({toolCallId:Y.toolCallId,name:Y.name,input:z.value,kind:G,signature:X0(this.claimsFor(Y.toolCallId,String(Y.name),G,z.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}X.push(this.executeTool(J,Z.id,Y,z.value,Q).then(async(V)=>{this.addResult(Z,V),await this.settleShown(Y.toolCallId)}).catch((V)=>{if(V instanceof v){if(this.onPending==="deny"){this.addResult(Z,this.deniedByPolicy(Y));return}B.push(...V.pending);return}}))}return await x(Promise.all(X).then(()=>{return}),this.controller.signal),B}claimsFor(Z,$,Q,B){return{runId:this.signingRunId,toolCallId:Z,name:$,kind:Q,input:B,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0,subject:this.params.subject??null}}deniedByPolicy(Z){return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"refused",reason:`"${String(Z.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Z,$,Q,B,X,Y){let J=Z.tool.timeoutMs;if(J===void 0)return this.runToolBody(Z,$,Q,B,X,Y,this.controller.signal,()=>!1);let z=new AbortController,G=this.controller.signal,V=()=>z.abort(G.reason);if(G.aborted)V();else G.addEventListener("abort",V,{once:!0});let H=!1,q=this.runToolBody(Z,$,Q,B,X,Y,z.signal,()=>H),W=()=>{},F=new Promise((K)=>{W=S0(J,()=>{let L=`"${String(Q.name)}" did not finish within ${EZ(J)} (timeoutMs: ${J}) and was cancelled.`;z.abort(new DOMException(L,"TimeoutError")),K({type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"error",error:{code:"timeout",message:L,toolCallId:Q.toolCallId,retryable:!0}})})});q.catch(()=>{});try{return await Promise.race([q,F])}finally{H=!0,W()}}async runToolBody(Z,$,Q,B,X,Y,J,z){let G=this.toolFiles(Q,J),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Q.toolCallId,signal:J,step:X,depth:this.depth,resumed:Y!==void 0,attachments:G.attachments,generateImage:G.generateImage,editImage:G.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Q,J,Y),generate:(H)=>this.generateForTool(H,J,Q.toolCallId),jobs:d0({jobs:this.depth===0?this.params.jobs:void 0,threadId:this.params.threadId,runId:this.runId,toolCallId:Q.toolCallId,toolName:String(Q.name),depth:this.depth,async:Z.tool.async,attachments:this.params.attachments??null})};try{let H=Z.tool.execute(B,V),q;if(B4(H)){let W=await H.next();while(!W.done){if(z())throw H.return(void 0).catch(()=>{}),new M;this.emit({type:"tool-progress",toolCallId:Q.toolCallId,data:W.value}),W=await H.next()}q=W.value}else q=await H;if(c0(q)){if(q.toolCallId!==Q.toolCallId)throw new P(`"${String(Q.name)}" returned the handle of a job another tool call started. Return the handle from this call's own ctx.jobs.`,{retryable:!1});return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"running",job:{id:q.id,...q.summary!==void 0?{summary:q.summary}:{}}}}return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"ok",output:q}}catch(H){if(H instanceof M||this.controller.signal.aborted)throw new M;if(H instanceof v)throw H;let q=H instanceof P;if(!q&&this.config.logErrors)this.logToolFailure(Q,H);let W={code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:Q.toolCallId,retryable:q?H.retryable:!0};return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"error",error:this.redact(W,{source:"tool",toolName:String(Q.name),cause:H})}}}async generateForTool(Z,$,Q){let B=this.controller.signal;return m({...Z,signal:Z.signal?AbortSignal.any([$,Z.signal]):$},{origin:{agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},toolCallId:Q},settled:(X)=>{if(this.usage=O(this.usage,X.usage),B.aborted)throw new M}})}nestedRunner(Z,$,Q,B){let X=new wZ(()=>$.nested,()=>$.nested=[]);return async(Y,J={})=>{let{at:z,recorded:G,write:V}=X.next();if(G){let H=J4(G,Y,J);if(H)throw new P(`Nested run ${z} of "${String($.name)}" ${H}. `+"runAgent is memoized by call index, so a body whose runAgent calls depend on a condition that changed between turns cannot be resumed \u2014 the answer would be paired with a different sub-run. "+"Make the sequence of runAgent calls, and what each one is asked, the same every time this tool runs, or branch on ctx.resumed.");if(G.finishReason!=="awaiting-input")return{runId:G.runId,agent:G.agent,messages:G.messages,finishReason:G.finishReason??"stop",usage:G.usage??j(),output:f0(G.messages),nested:G}}return this.runNested(Z,$,Q,Y,J,V,G,B?.answers??[])}}async runNested(Z,$,Q,B,X,Y,J,z){let G=[...this.chain,B.name];if(this.chain.includes(B.name))throw new P(`"${B.name}" is already running further up this chain: ${G.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw new P(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${G.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let H=X.label,q=[...this.pathPrefix,$.toolCallId],W=this.onPending==="deny"?"deny":X.onPending??"escalate",F=J!==void 0,K=F?HZ(J.messages):new Set,L=F?z.filter((C)=>{let I=v0(C.path,q);if(I===null)return!1;return K.has(I.length>0?I[0]:C.toolCallId)}):[],D=B.stream({messages:F?J.messages:X.messages??[],turn:F?{toolResults:L}:X.prompt?{text:X.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:Q,threadId:this.params.threadId,redactError:this.params.redactError,nonces:this.params.nonces,receipts:this.params.receipts,subject:this.params.subject,instructions:X.instructions,maxOutputTokens:X.maxOutputTokens,temperature:X.temperature,runId:F?J.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:G,signingRunId:this.signingRunId,signingPath:q,onPending:W}}),U=[],f=(C)=>this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:D.runId,agent:B.name,label:H,event:C}),l=(async()=>{for await(let C of D){if(C.type==="awaiting-input")U=C.pending;if(f(C),C.type==="run-start"&&!F)for(let I of X.messages??[])f({type:"message",message:I});if(C.type==="error")this.emit({type:"error",error:C.error,nested:{toolCallId:$.toolCallId,runId:D.runId,agent:B.name}})}})(),_=(async()=>{let C=await D.result();await l;let I=F?E0(J.messages,C.messages):E0(X.messages??[],C.messages),dZ={runId:D.runId,agent:B.name,label:H,messages:I,finishReason:C.finishReason,usage:F?O(J.usage??j(),C.usage):C.usage,...C.finishReason==="awaiting-input"?{signature:z0({runId:this.signingRunId,path:q,nestedRunId:D.runId,open:[...HZ(I)],input:$.input,subject:this.params.subject??null})}:{}};return Y(dZ),this.usage=O(this.usage,C.usage),{result:C,record:dZ}})(),N=_.then(()=>{return},()=>{return});this.nestedSettling.add(N);let b,T;try{({result:b,record:T}=await _)}finally{this.nestedSettling.delete(N)}if(this.controller.signal.aborted)throw new M;if(b.finishReason==="awaiting-input"){if(U.length===0)throw new P(`"${B.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Z,part:$,resent:!0}),new v({pending:U,path:q,nested:T})}return{runId:T.runId,agent:B.name,messages:T.messages,finishReason:b.finishReason,usage:T.usage??j(),output:b.output??f0(T.messages),...b.error?{error:b.error}:{},nested:T}}addResult(Z,$){Z.content.push($),this.emit({type:"tool-result",messageId:Z.id,part:$})}toolFiles(Z,$){let Q=this.params.attachments??null,B=new wZ(()=>Z.attachments,()=>Z.attachments=[],()=>({failed:!0})),X=()=>{if(!Q)throw new w("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return Q},Y=async(V,H,q)=>{let W=X(),F=H.mimeType||V.type||"",K=H.name??(V instanceof File?V.name:"attachment"),L;if(H.showModel){let U=this.config.provider;if(!U.capabilities.fileInput)throw new P(`"${String(Z.name)}" asked to show a file to ${U.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);L=await U.upload(new File([V],K,{type:F||void 0}))}return{attachment:await W.put(V,{name:K,mimeType:F,fileId:L}),...q?{generated:q}:{},...L?{shown:{fileId:L,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},J=(V,H,q)=>{let W=V.generated?"image":"put";if(W===H)return;throw new P(`Attachment ${q} of "${String(Z.name)}" was ${W==="image"?"a generated image":"a stored file"} on the first attempt and is ${H==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},z=async(V,H,q)=>{let{at:W,recorded:F,write:K}=B.next();if(F&&"attachment"in F){if(J(F,"image",W),F.shown)this.queueShown(Z.toolCallId,F);return{attachment:F.attachment,size:F.generated.size,mimeType:F.attachment.mimeType,usage:F.generated.usage}}let L=await q();this.usage=O(this.usage,L.usage);let D=L.mimeType==="image/jpeg"?"jpg":"png",U=await Y(L.image,{name:H.name??`${V.name}.${D}`,mimeType:L.mimeType,...H.showModel?{showModel:!0}:{}},{size:L.size,usage:L.usage});if(K(U),U.shown)this.queueShown(Z.toolCallId,U);return{attachment:U.attachment,size:L.size,mimeType:L.mimeType,usage:L.usage}},G=async(V)=>typeof V==="string"?await X().file(V):V;return{generateImage:(V,H)=>z(V,H,()=>V.generate({...H,signal:$})),editImage:(V,H)=>z(V,H,async()=>{let{images:q,mask:W,...F}=H;return await V.edit({...F,images:await Promise.all(q.map(G)),...W?{mask:await G(W)}:{},signal:$})}),attachments:{get:(V)=>X().get(V),read:(V)=>X().read(V),file:(V)=>X().file(V),put:async(V,H={})=>{let{at:q,recorded:W,write:F}=B.next();if(W&&"attachment"in W){J(W,"put",q);let L=Y4(W,V,H);if(L)throw new P(`Attachment ${q} of "${String(Z.name)}" ${L}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(W.shown)this.queueShown(Z.toolCallId,W);return W.attachment}let K=await Y(V,H);if(F(K),K.shown)this.queueShown(Z.toolCallId,K);return K.attachment}}}}toolTurn(Z){let $=this.history.findIndex((Y)=>Y.id===Z),Q=YZ(this.history),B;for(let Y=$-1;Y>=0;Y--){let J=this.history[Y];if(J.role!=="user"||Q.has(J.id))continue;B=J;break}let X=[];for(let Y of B?.content??[]){if(Y.type!=="file")continue;let J=Y.attachmentId;if(typeof J!=="string"||!J.startsWith(CZ))continue;if(!X.includes(J))X.push(J)}return Object.freeze({attachments:Object.freeze(X)})}queueShown(Z,$){let Q=$.shown;if(!Q)return;let B=this.shownQueue.get(Z)??[];if(B.some((X)=>X.id===Q.messageId))return;B.push({id:Q.messageId,role:"user",content:[{type:"file",fileId:Q.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Q.createdAt,finishReason:"stop"}),this.shownQueue.set(Z,B)}async settleShown(Z){let $=this.shownQueue.get(Z);if(!$||$.length===0)return;if(this.shownQueue.delete(Z),this.ended||this.controller.signal.aborted)return;for(let Q of $){if(this.history.some((B)=>B.id===Q.id))continue;this.history.push(Q),this.produced.push(Q),this.emit({type:"message",message:Q}),this.unreported.add(Q)}}historyForProvider(Z){let $=this.history.filter((Y)=>Y!==Z),Q=YZ($),B=[];for(let Y of $){if(!Q.has(Y.id))continue;for(let J of Y.content)if(J.type==="file")B.push(J)}if(B.length<=w0)return $;let X=new Set(B.slice(0,B.length-w0));return $.map((Y)=>{if(!Y.content.some((J)=>J.type==="file"&&X.has(J)))return Y;return{...Y,content:Y.content.map((J)=>J.type==="file"&&X.has(J)?{type:"text",text:`[A ${J.mimeType||"file"} produced by a tool (attachment ${J.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:J)}})}async ingestTurn(){let Z=this.params.turn,$=this.openCalls(),Q=[];if($.length>0){let B=new Set,X=new Set,Y=new Map;for(let J of Z?.toolResults??[]){let z=`${(J.path??[]).join("/")}#${J.toolCallId}`;if(X.has(z))continue;X.add(z);let G=(W)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:W,toolCallId:J.toolCallId,retryable:!1}}),V=v0(J.path,this.pathPrefix);if(V===null){G(`The answer for "${J.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let W=V[0],F=$.find((D)=>D.call.toolCallId===W);if(!F){G(`No pending tool call with id "${W}" to deliver a nested answer to.`);continue}let K=this.parkedBelow(F.call,V,J.toolCallId);if(K.ok===!1){let D=`The answer for "${J.toolCallId}" is addressed under "${W}", which`;G(K.reason==="unparked"?`${D} has no sub-agent run waiting on that question.`:K.reason==="expired"?`${D} parked a sub-agent run that has since expired. Ask again.`:`${D} carries a record of a parked sub-agent run the server did not sign.`);continue}let L=Y.get(W);if(!L){if(!await this.spend(K0,K.signature)){G(`The answer for "${J.toolCallId}" is addressed under "${W}", which has already been re-entered on that record. Ask again.`);continue}L=[],Y.set(W,L),B.add(W)}L.push(J);continue}let H=$.find((W)=>W.call.toolCallId===J.toolCallId);if(!H){G(`No pending tool call with id "${J.toolCallId}".`);continue}let q=await this.resolveAnswer(H,J,Q);if(q===null)continue;if(B.add(J.toolCallId),q!=="open")this.attachToHistory(H,q),await this.settleShown(J.toolCallId)}for(let[J,z]of Y){let G=$.find((H)=>H.call.toolCallId===J),V=await this.reenter(G,z,Q);if(V)this.attachToHistory(G,V),await this.settleShown(J)}for(let J of $){if(B.has(J.call.toolCallId))continue;this.attachToHistory(J,{type:"tool-result",toolCallId:J.call.toolCallId,name:J.call.name,status:"denied",cause:"refused"})}await this.reportDeferred()}if(Z&&(Z.text||Z.files&&Z.files.length>0)){let B={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Z.text?[{type:"text",text:Z.text}]:[],...(Z.files??[]).map((X)=>({type:"file",...X.fileId?{fileId:X.fileId}:{},name:X.name,mimeType:X.mimeType,...X.attachmentId?{attachmentId:X.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};if(this.history.push(B),this.produced.push(B),this.depth>0)this.emit({type:"message",message:B});else if(Z.localId)this.emit({type:"message-id",localId:Z.localId,messageId:B.id,message:B});if(await this.report(B),this.params.onTurn)try{await this.params.onTurn(B)}catch{}}return Q}parkedBelow(Z,$,Q){let B=$.length>1?$[1]:Q,X=[...this.pathPrefix,Z.toolCallId],Y=(Z.nested??[]).find((z)=>z.finishReason==="awaiting-input"&&HZ(z.messages).has(B));if(!Y)return{ok:!1,reason:"unparked"};if(typeof Y.signature!=="string")return{ok:!1,reason:"unsigned"};let J=H0(Y.signature,{path:X,nestedRunId:Y.runId,open:[...HZ(Y.messages)],input:Z.input,subject:this.params.subject??null});if(J.ok===!1)return{ok:!1,reason:J.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:Y.signature}}async reenter(Z,$,Q){let B=String(Z.call.name),X=this.config.registry.get(B);if(!X||!X.tool.execute)return{type:"tool-result",toolCallId:Z.call.toolCallId,name:Z.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${B}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Z.call.toolCallId,retryable:!1}};let Y=X.inputSchema.safeParse(Z.call.input);if(Y.ok===!1)return{type:"tool-result",toolCallId:Z.call.toolCallId,name:Z.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${B}": ${Y.errors.join(", ")}`,toolCallId:Z.call.toolCallId,retryable:!0}};let J=this.amendCall(Z);J.input=Y.value;try{return await x(this.executeTool(X,Z.message.id,J,Y.value,0,{answers:$}),this.controller.signal)}catch(z){if(z instanceof v)return Q.push(...z.pending),null;throw z}}amendCall(Z){let $=this.amend(Z.message),Q=$.content.indexOf(Z.call),B={...Z.call,nested:(Z.call.nested??[]).map((X)=>({...X})),...Z.call.attachments?{attachments:Z.call.attachments.map((X)=>({...X}))}:{}};if(Q>=0)$.content[Q]=B;return this.unreported.add($),B}openCalls(){let Z=new Set;for(let Q of this.history)for(let B of Q.content)if(B.type==="tool-result")Z.add(B.toolCallId);let $=[];for(let Q of this.history)for(let B of Q.content)if(B.type==="tool-call"&&!Z.has(B.toolCallId))$.push({message:Q,call:B});return $}async spend(Z,$){try{return await Z($,this.params.nonces??DZ)}catch(Q){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not spend a nonce`,{error:Q}),!1}}async recordReceipt(Z,$){let Q=await $;try{await Z.store.complete(Z.id,Q,Z.expiresAt)}catch(B){this.writeLog(`[gemi/ai] agent "${this.config.name}" could not record a tool receipt`,{error:B})}return Q}async resolveAnswer(Z,$,Q){let B=Z.call,X=String(B.name),Y=this.config.registry.get(X),J=(q)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:q,toolCallId:B.toolCallId,retryable:!1}}),null};if(!Y)return J(`The tool "${X}" no longer exists, so its answer cannot be checked.`);let z=y0(Y.tool);if(!z)return J(`"${X}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return J(`The answer for "${X}" carried no signature.`);let G=IZ($.signature);if(!G)return J(`The signature for "${X}" is malformed.`);let V=Y0($.signature,{...this.claimsFor(B.toolCallId,X,z,B.input),runId:G.runId});if(V.ok===!1)return J(V.reason==="expired"?`The approval for "${X}" has expired. Ask again.`:`The answer for "${X}" does not match the call the server made.`);let H;if(this.params.receipts&&z==="approval"&&"approve"in $&&$.approve===!0){let q=this.params.receipts,W=W0(this.config.name,{...this.claimsFor(B.toolCallId,X,z,B.input),runId:G.runId}),F;try{F=await q.claim(W,G.expiresAt)}catch(K){return this.writeLog(`[gemi/ai] agent "${this.config.name}" could not claim a tool receipt`,{error:K}),J(`The approval for "${X}" could not be checked. Ask again.`)}if(F.status==="replay")return{...F.result,toolCallId:B.toolCallId,name:B.name};if(F.status==="blocked")return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"tool_error",message:`"${X}" was already approved and started, and its result is not recorded yet: it is still running, or it stopped before finishing. It was not run again.`,toolCallId:B.toolCallId,retryable:!1}};H={store:q,id:W,expiresAt:G.expiresAt}}if(!await this.spend(q0,$.signature))return await H?.store.release(H.id).catch((q)=>{this.writeLog(`[gemi/ai] agent "${this.config.name}" could not release a tool receipt`,{error:q})}),J(`The answer for "${X}" has already been used. Ask again.`);if("approve"in $){if(z!=="approval")return J(`"${X}" is answered by the client, not approved.`);if($.approve===!0){let q=this.amendCall(Z),W=this.executeTool(Y,Z.message.id,q,q.input,0);try{return await x(H?this.recordReceipt(H,W):W,this.controller.signal)}catch(F){if(F instanceof v)return Q.push(...F.pending),"open";throw F}}return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(z==="approval")return J(`"${X}" is approved, not answered: the server produces its result.`);let q=Y.tool.outputSchema,W=q?q.safeParse($.output):{ok:!0,value:$.output};if(W.ok===!1)return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${X}" did not match its output schema: ${W.errors.join(", ")}`,toolCallId:B.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:B.toolCallId,name:B.name,status:"ok",output:W.value}}return J(`The answer for "${X}" carried neither an approval nor an output.`)}attachToHistory(Z,$){let Q=this.amend(Z.message);Q.content.push($),this.unreported.add(Q),this.emit({type:"tool-result",messageId:Q.id,part:$})}markFileRejected(Z,$,Q){for(let J of this.history){if(!J.content.some((V)=>V.type==="file"&&V.fileId===Z&&!V.providerRejected))continue;let G=this.produced.includes(J)?J:this.amend(J);if(G.content=G.content.map((V)=>V.type==="file"&&V.fileId===Z&&!V.providerRejected?{...V,providerRejected:!0}:V),G!==this.current)this.unreported.add(G)}if(!this.config.logErrors)return;let B=`[gemi/ai] agent "${this.config.name}": the provider refused file ${Z}${Q.status!==void 0?` (${Q.status})`:""}; it was left out of the request and will not be sent again: ${$}`,X={agent:this.config.name,runId:this.runId,...this.params.threadId?{threadId:this.params.threadId}:{},fileId:Z,...Q},Y=!1;try{p.warning(B,X),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.warn(B,X)}amend(Z){let $=this.amended.get(Z.id);if($)return $;let Q={...Z,content:[...Z.content]},B=this.history.indexOf(Z);if(B>=0)this.history[B]=Q;return this.produced.push(Q),this.amended.set(Z.id,Q),Q}async reportDeferred(){let Z=[...this.unreported];this.unreported.clear();for(let $ of Z)await this.report($)}async finalizeAborted(){if(this.nestedSettling.size>0)await Promise.all([...this.nestedSettling]);for(let $ of this.openCalls()){if($.message===this.current)continue;this.attachToHistory($,{type:"tool-result",toolCallId:$.call.toolCallId,name:$.call.name,status:"denied",cause:"stopped",reason:this.stopReason})}await this.reportDeferred();let Z=this.current;if(Z){let $=new Set(Z.content.filter((Q)=>Q.type==="tool-result").map((Q)=>Q.toolCallId));for(let Q of[...Z.content]){if(Q.type!=="tool-call"||$.has(Q.toolCallId))continue;delete Q.partial,this.addResult(Z,{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"stopped",reason:this.stopReason})}}if(this.timedOutAfter!==void 0){this.fail({code:"timeout",message:`The run did not finish within its time limit of ${EZ(this.timedOutAfter)} (maxRunDurationMs: ${this.timedOutAfter}) and was stopped.`,retryable:!0}),this.finishReason="error",await this.finalizeMessage("error");return}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function y0(Z){if(Z.answeredBy==="client")return Z.inputSchema===vZ?"question":"client";return Z.requiresApproval?"approval":null}function h0(Z){if(!Z||!Z.trim())return{};try{return JSON.parse(Z)}catch{return Z}}function x0(Z){return m(Z)}async function m(Z,$={}){let Q=`gen_${crypto.randomUUID()}`,B=await G4(Z);if($.settled?.(B),!B.ok){if(Z.logErrors!==!1&&B.error.code!=="aborted")V4(Q,B.error,$.origin);if(Z.throwOnError)throw new KZ({runId:Q,messages:B.messages,finishReason:B.finishReason,usage:B.usage,error:B.error})}return B}function V4(Z,$,Q){let B=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,X={...Q,generateId:Z,error:$},Y=!1;try{p.error(B,X),Y=!0}catch{}if(!Y||Bun.env.NODE_ENV==="development")console.error(B,X)}async function G4(Z){let $=Z.messages??[];if($.length===0&&!Z.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Q=[...$];if(Z.prompt)Q.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Z.prompt}],createdAt:new Date().toISOString()});let B={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},X=Z.signal??new AbortController().signal,Y=j(),J="stop",z,G={},V="";try{let F=Z.provider.stream({messages:[...Q],systemPrompt:Z.instructions?.trim()?Z.instructions:void 0,output:s(Z.output),reasoning:Z.reasoning,maxOutputTokens:Z.maxOutputTokens,temperature:Z.temperature,signal:Z.signal})[Symbol.asyncIterator]();try{for(;;){let K=await x(Promise.resolve(F.next()),X);if(K.done)break;let L=K.value;switch(L.type){case"output-delta":V+=L.delta;break;case"text-delta":h(B,"text",L.delta);break;case"reasoning-delta":e(B,L.id,L.delta);break;case"finish":if(Y=O(Y,L.usage),!z)J=L.reason;break;case"error":J="error",z=L.error,G=S(L);break}}}finally{if(X.aborted)Promise.resolve(F.return?.()).catch(()=>{})}}catch(W){if(W instanceof M||X.aborted)J="aborted",z=z4(X);else J="error",z=Z.provider.normalizeError(W),G=S(W)}let H=!1,q;if(!z)if(J==="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(!V.trim())z={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let W=a(Z.output,V);if(W.ok===!0)H=!0,q=W.value;else z=W.error}if(H)B.content.push({type:"output",value:q});else if(V)h(B,"text",V);for(let W of B.content)if((W.type==="text"||W.type==="reasoning")&&typeof W.text==="string")W.text=r(W.text);if(B.finishReason=J,B.usage=Y,Q.push(B),H)return{ok:!0,output:q,messages:Q,usage:Y,finishReason:J};return{ok:!1,error:{...z,...G},messages:Q,usage:Y,finishReason:J}}function z4(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 e0=Symbol.for("gemi.ai.JobHandle");class Z1{id;toolCallId;summary;deadlineAt;[e0]=!0;constructor(Z,$,Q,B){this.id=Z;this.toolCallId=$;this.summary=Q;this.deadlineAt=B}}function c0(Z){return typeof Z==="object"&&Z!==null&&Z[e0]===!0}class uZ extends P{code="jobs_require_thread";constructor(Z){super(Z,{retryable:!1});this.name="JobsRequireThreadError"}}var y=new jZ,H4=["running","ok","error"],cZ={get store(){return y},use(Z){y=Z},get(Z){return y.get(Z)},async settle(Z,$){return FZ(y,Z,$)},async fail(Z,$){return FZ(y,Z,{error:$})},async sweep(Z={}){let $=y,Q=Z.limit??100,B=await W4($),X=0;for(let Y of await $.overdue(B,Q))if(await q4($,Y))X++;return X}};async function W4(Z){return Z.now?await Z.now():Date.now()}function q4(Z,$){return 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}})}async function FZ(Z,$,Q){let B=await Z.get($);if(!B||B.state!=="running")return!1;let X=Q.usage?O(B.usage??j(),Q.usage):void 0;if("error"in Q)return Z.transition($,["running"],{state:"error",error:K4(B,Q.error),...X?{usage:X}:{}});return Z.transition($,["running"],{state:"ok",output:$1(Q.output,B),...X?{usage:X}:{}})}function K4(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 P?$.retryable:!0};if(!($ instanceof P))console.error(`The background job ${Z.job??"(tracked)"} for "${Z.toolName}" failed.`,$);return n(Q,{source:"tool",toolName:Z.toolName,cause:$})}return{code:$.code??"tool_error",message:String($.message),toolCallId:Z.toolCallId,retryable:$.retryable??!0}}function $1(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 F4=3600000;function d0(Z){let $=null,Q=(B,X,Y={})=>{if(Z.async===void 0)throw new P(`"${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 uZ(`"${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 uZ(`"${Z.toolName}" can only run in the background from the top-level agent, not from a sub-agent.`);if($)throw new P(`"${Z.toolName}" started a background job already: a tool call has at most one.`,{retryable:!1});let J=Y.deadlineMs??Z.async.deadlineMs??F4;if(!Number.isFinite(J)||J<=0)throw new P(`A job's deadlineMs must be a positive number; got ${J}.`);let{jobs:z,threadId:G}=Z;return $=(async()=>{let V=cZ.store,H=(await V.listForThread(G,{limit:50})).find((F)=>F.toolCallId===Z.toolCallId);if(H)return o0(H);let q=async()=>{let F=await V.create({id:`ajob_${crypto.randomUUID()}`,threadId:G,runId:Z.runId,toolCallId:Z.toolCallId,toolName:Z.toolName,owner:z.owner,job:B?B.name:null,...Y.summary!==void 0?{summary:$1(Y.summary,Z)}:{},attachmentScope:Z.attachments?.scopeKey??null,deadlineMs:J});if(B)try{await L4(B,{jobId:F.id,args:X})}catch(K){if(V.transaction)throw K;throw await V.transition(F.id,["running"],{state:"error",error:{code:"tool_error",message:`The background job for "${Z.toolName}" could not be queued.`,toolCallId:Z.toolCallId,retryable:!0}}).catch(()=>{}),K}return F},W=V.transaction?await V.transaction(q):await q();return o0(W)})(),$};return{start:(B,X,Y)=>Q(B,X,Y),track:(B)=>Q(null,void 0,B)}}function o0(Z){return new Z1(Z.id,Z.toolCallId,Z.summary,Z.deadlineAt)}function L4(Z,$){if(Z.name==="unset"||!Z.name)throw Error("Cannot start an AgentJob with no `static name`.");return i(a0).push(Z,JSON.stringify([$]))}class D4 extends r0{attachments=oZ;attachmentStorage=s0;constructor(){super();let Z=this.run;this.run=($)=>this.$runEnvelope($,Z)}onDeadletter(Z,...$){let Q=$[0];if(!Q?.jobId)return;FZ(cZ.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=cZ.store,B=await Q.get(Z.jobId);if(!B||B.state!=="running")return;let X=new Q1(B,this),Y;try{Y=await $.call(this,Z.args,X)}catch(J){throw await t0(Q,B.id,X.usage),J}if(this.$outcome)return await t0(Q,B.id,X.usage),Y;return await FZ(Q,B.id,{output:Y,usage:X.usage}),Y}}async function t0(Z,$,Q){if(Q.totalTokens===0&&Q.inputTokens===0&&Q.outputTokens===0)return;let B=await Z.get($);if(!B)return;await Z.transition($,H4,{usage:O(B.usage??j(),Q)}).catch(()=>{})}class Q1{id;threadId;toolCallId;toolName;owner;summary;signal=new AbortController().signal;usage=j();attachments;constructor(Z,$){this.id=Z.id,this.threadId=Z.threadId,this.toolCallId=Z.toolCallId,this.toolName=Z.toolName,this.owner=Z.owner,this.summary=Z.summary;let Q=Z.attachmentScope?new OZ($.attachments,$.attachmentStorage,{key:Z.attachmentScope}):null,B=()=>{if(!Q)throw new w("The run that started this job had no attachment scope, so the job cannot store or read files. See `attachmentScope()` on the controller.");return Q};this.attachments={put:(X,Y={})=>B().put(X,Y),get:(X)=>B().get(X),read:(X)=>B().read(X),file:(X)=>B().file(X)}}generate(Z){return m(Z,{origin:{threadId:this.threadId,toolCallId:this.toolCallId,jobId:this.id},settled:($)=>{this.usage=O(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,...Y}=$,J=async(G)=>typeof G==="string"?await this.attachments.file(G):G,z=await Z.edit({...Y,images:await Promise.all(B.map(J)),...X?{mask:await J(X)}:{},signal:this.signal});return this.park(Z,z,Q)}async park(Z,$,Q){this.usage=O(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}}}
|
|
20
|
+
export{pZ as Xb,B1 as Yb,DZ as Zb,g as _b,R as $b,j as ac,O as bc,P as cc,n as dc,O4 as ec,PZ as fc,w as gc,CZ as hc,Y1 as ic,OZ as jc,J1 as kc,nZ as lc,oZ as mc,jZ as nc,Z1 as oc,c0 as pc,uZ as qc,cZ as rc,W4 as sc,q4 as tc,F4 as uc,d0 as vc,D4 as wc,L0 as xc,D0 as yc,S as zc,k4 as Ac,YZ as Bc,JZ as Cc,E4 as Dc,M1 as Ec,R1 as Fc,_1 as Gc,u as Hc,T1 as Ic,S1 as Jc,f1 as Kc,b1 as Lc,M0 as Mc,v1 as Nc,N0 as Oc,h4 as Pc,g4 as Qc,v as Rc,WZ as Sc,yZ as Tc,p0 as Uc,zZ as Vc,m0 as Wc,KZ as Xc,l0 as Yc,x0 as Zc,m as _c};
|
|
21
21
|
|
|
22
|
-
//# debugId=
|
|
22
|
+
//# debugId=8E6696563CBE82B264756E2164756E21
|