gemi 0.102.0 → 0.103.0
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/ai/index.js +2 -2
- package/dist/ai/index.js.map +1 -1
- package/dist/app/index.js +1 -1
- package/dist/bun/plugin.js +1 -1
- package/dist/bun/preload.js +1 -1
- package/dist/{chunk-f6s7ddjz.js → chunk-0fney17e.js} +2 -2
- package/dist/{chunk-f6s7ddjz.js.map → chunk-0fney17e.js.map} +1 -1
- package/dist/{chunk-z8jf7jwg.js → chunk-18aqqrev.js} +2 -2
- package/dist/{chunk-z8jf7jwg.js.map → chunk-18aqqrev.js.map} +1 -1
- package/dist/{chunk-68zf43ah.js → chunk-1xzdexbq.js} +2 -2
- package/dist/{chunk-68zf43ah.js.map → chunk-1xzdexbq.js.map} +1 -1
- package/dist/{chunk-99wzvsz5.js → chunk-214av8am.js} +4 -4
- package/dist/{chunk-99wzvsz5.js.map → chunk-214av8am.js.map} +1 -1
- package/dist/{chunk-adm5g1v8.js → chunk-22k4b395.js} +2 -2
- package/dist/{chunk-adm5g1v8.js.map → chunk-22k4b395.js.map} +1 -1
- package/dist/{chunk-nffk2cj3.js → chunk-2baxmae9.js} +2 -2
- package/dist/{chunk-nffk2cj3.js.map → chunk-2baxmae9.js.map} +1 -1
- package/dist/{chunk-4x41cmg3.js → chunk-3cxbvrts.js} +3 -3
- package/dist/{chunk-4x41cmg3.js.map → chunk-3cxbvrts.js.map} +1 -1
- package/dist/chunk-3e73zaft.js +5 -0
- package/dist/{chunk-23mpa8t7.js.map → chunk-3e73zaft.js.map} +3 -3
- package/dist/{chunk-2tm56xq1.js → chunk-3m93v7bt.js} +2 -2
- package/dist/{chunk-2tm56xq1.js.map → chunk-3m93v7bt.js.map} +1 -1
- package/dist/{chunk-63cp4s8g.js → chunk-47dqttnk.js} +2 -2
- package/dist/{chunk-63cp4s8g.js.map → chunk-47dqttnk.js.map} +1 -1
- package/dist/{chunk-qttatc7h.js → chunk-4f7n1r02.js} +2 -2
- package/dist/{chunk-qttatc7h.js.map → chunk-4f7n1r02.js.map} +1 -1
- package/dist/{chunk-6397mbr2.js → chunk-4p752vk2.js} +3 -3
- package/dist/{chunk-6397mbr2.js.map → chunk-4p752vk2.js.map} +1 -1
- package/dist/{chunk-br9p390p.js → chunk-5dwtmkk8.js} +2 -2
- package/dist/{chunk-br9p390p.js.map → chunk-5dwtmkk8.js.map} +1 -1
- package/dist/{chunk-a9nxjfdy.js → chunk-5k3rm4b6.js} +2 -2
- package/dist/{chunk-a9nxjfdy.js.map → chunk-5k3rm4b6.js.map} +1 -1
- package/dist/{chunk-bvsevtpp.js → chunk-5ngv175h.js} +1 -1
- package/dist/{chunk-jhaeemjf.js → chunk-62cv9vjt.js} +2 -2
- package/dist/{chunk-jhaeemjf.js.map → chunk-62cv9vjt.js.map} +1 -1
- package/dist/{chunk-msg6re1f.js → chunk-63hvh35x.js} +2 -2
- package/dist/{chunk-msg6re1f.js.map → chunk-63hvh35x.js.map} +1 -1
- package/dist/{chunk-69yw2pb1.js → chunk-8nkdvgd9.js} +2 -2
- package/dist/{chunk-69yw2pb1.js.map → chunk-8nkdvgd9.js.map} +1 -1
- package/dist/{chunk-eqtsfvvd.js → chunk-ayss2f8c.js} +2 -2
- package/dist/{chunk-eqtsfvvd.js.map → chunk-ayss2f8c.js.map} +1 -1
- package/dist/{chunk-bf1q3m7a.js → chunk-b0jpvp5t.js} +3 -3
- package/dist/{chunk-bf1q3m7a.js.map → chunk-b0jpvp5t.js.map} +1 -1
- package/dist/{chunk-3tn480wt.js → chunk-b1dqx3b9.js} +2 -2
- package/dist/{chunk-3tn480wt.js.map → chunk-b1dqx3b9.js.map} +1 -1
- package/dist/{chunk-pjg7gqnh.js → chunk-bsq80942.js} +2 -2
- package/dist/{chunk-pjg7gqnh.js.map → chunk-bsq80942.js.map} +1 -1
- package/dist/{chunk-aa13sgs2.js → chunk-cbywzv21.js} +1 -1
- package/dist/{chunk-snz7nze3.js → chunk-cw7qfcvt.js} +2 -2
- package/dist/{chunk-snz7nze3.js.map → chunk-cw7qfcvt.js.map} +1 -1
- package/dist/{chunk-4rns9cnb.js → chunk-dtybftkq.js} +2 -2
- package/dist/{chunk-4rns9cnb.js.map → chunk-dtybftkq.js.map} +1 -1
- package/dist/{chunk-8ma08vxq.js → chunk-dyew1yf7.js} +2 -2
- package/dist/{chunk-8ma08vxq.js.map → chunk-dyew1yf7.js.map} +1 -1
- package/dist/{chunk-cp8gxeqs.js → chunk-ee92kx8s.js} +2 -2
- package/dist/{chunk-cp8gxeqs.js.map → chunk-ee92kx8s.js.map} +1 -1
- package/dist/chunk-f2n21fef.js +5 -0
- package/dist/{chunk-yhkffean.js.map → chunk-f2n21fef.js.map} +1 -1
- package/dist/{chunk-ghz3e8b7.js → chunk-fcsq613t.js} +2 -2
- package/dist/{chunk-ghz3e8b7.js.map → chunk-fcsq613t.js.map} +1 -1
- package/dist/chunk-g8qp01t6.js +17 -0
- package/dist/{chunk-9hs7prvj.js.map → chunk-g8qp01t6.js.map} +3 -3
- package/dist/{chunk-c9vga0sk.js → chunk-gvv2trvz.js} +3 -3
- package/dist/{chunk-c9vga0sk.js.map → chunk-gvv2trvz.js.map} +1 -1
- package/dist/{chunk-4qjy1bts.js → chunk-gy6d6jeg.js} +2 -2
- package/dist/{chunk-4qjy1bts.js.map → chunk-gy6d6jeg.js.map} +1 -1
- package/dist/{chunk-64j3yef2.js → chunk-gyareq03.js} +2 -2
- package/dist/{chunk-64j3yef2.js.map → chunk-gyareq03.js.map} +1 -1
- package/dist/{chunk-5wgx5n2q.js → chunk-h945tg0r.js} +2 -2
- package/dist/{chunk-5wgx5n2q.js.map → chunk-h945tg0r.js.map} +1 -1
- package/dist/{chunk-hsec03gh.js → chunk-hwc8gt4n.js} +2 -2
- package/dist/{chunk-hsec03gh.js.map → chunk-hwc8gt4n.js.map} +1 -1
- package/dist/{chunk-gykbgtvg.js → chunk-hzmnqe4x.js} +2 -2
- package/dist/{chunk-gykbgtvg.js.map → chunk-hzmnqe4x.js.map} +1 -1
- package/dist/{chunk-shb51m4y.js → chunk-j041a7ej.js} +2 -2
- package/dist/{chunk-shb51m4y.js.map → chunk-j041a7ej.js.map} +1 -1
- package/dist/{chunk-hr0m35tr.js → chunk-j3y6cs0z.js} +2 -2
- package/dist/{chunk-hr0m35tr.js.map → chunk-j3y6cs0z.js.map} +1 -1
- package/dist/{chunk-xf9axxzx.js → chunk-j6e99sra.js} +3 -3
- package/dist/{chunk-xf9axxzx.js.map → chunk-j6e99sra.js.map} +1 -1
- package/dist/{chunk-9xf2fx98.js → chunk-j9deswmn.js} +2 -2
- package/dist/{chunk-9xf2fx98.js.map → chunk-j9deswmn.js.map} +1 -1
- package/dist/{chunk-epwaxctc.js → chunk-jfnhzza6.js} +2 -2
- package/dist/{chunk-epwaxctc.js.map → chunk-jfnhzza6.js.map} +1 -1
- package/dist/{chunk-prg5k57m.js → chunk-kwkbzswm.js} +2 -2
- package/dist/{chunk-prg5k57m.js.map → chunk-kwkbzswm.js.map} +1 -1
- package/dist/{chunk-n63xjrck.js → chunk-ma5rmcbe.js} +2 -2
- package/dist/{chunk-n63xjrck.js.map → chunk-ma5rmcbe.js.map} +1 -1
- package/dist/{chunk-6abjjfjr.js → chunk-mnctdd8r.js} +2 -2
- package/dist/{chunk-6abjjfjr.js.map → chunk-mnctdd8r.js.map} +1 -1
- package/dist/{chunk-y4fp0eg9.js → chunk-p2jn4bnx.js} +2 -2
- package/dist/{chunk-y4fp0eg9.js.map → chunk-p2jn4bnx.js.map} +1 -1
- package/dist/{chunk-xp6nr441.js → chunk-pfjr510h.js} +2 -2
- package/dist/{chunk-xp6nr441.js.map → chunk-pfjr510h.js.map} +1 -1
- package/dist/{chunk-dn2mw39y.js → chunk-q8r9mvzx.js} +2 -2
- package/dist/{chunk-dn2mw39y.js.map → chunk-q8r9mvzx.js.map} +1 -1
- package/dist/{chunk-1vs4xhcg.js → chunk-r5pnz4nn.js} +2 -2
- package/dist/{chunk-1vs4xhcg.js.map → chunk-r5pnz4nn.js.map} +1 -1
- package/dist/{chunk-yk2mtcwv.js → chunk-rjcmbwcc.js} +2 -2
- package/dist/{chunk-yk2mtcwv.js.map → chunk-rjcmbwcc.js.map} +1 -1
- package/dist/{chunk-80t4tfke.js → chunk-rkre6bqc.js} +1 -1
- package/dist/{chunk-mekw2ap4.js → chunk-sedwjgvf.js} +2 -2
- package/dist/{chunk-mekw2ap4.js.map → chunk-sedwjgvf.js.map} +1 -1
- package/dist/{chunk-md8hmejq.js → chunk-spgpvz77.js} +2 -2
- package/dist/{chunk-md8hmejq.js.map → chunk-spgpvz77.js.map} +1 -1
- package/dist/{chunk-3fr22rtg.js → chunk-st0d3ndv.js} +2 -2
- package/dist/{chunk-3fr22rtg.js.map → chunk-st0d3ndv.js.map} +1 -1
- package/dist/{chunk-tymhsmgq.js → chunk-szrgwggb.js} +3 -3
- package/dist/{chunk-tymhsmgq.js.map → chunk-szrgwggb.js.map} +1 -1
- package/dist/{chunk-mb8chren.js → chunk-tcce63wk.js} +2 -2
- package/dist/{chunk-mb8chren.js.map → chunk-tcce63wk.js.map} +1 -1
- package/dist/{chunk-7vjbebst.js → chunk-v4exgqbp.js} +2 -2
- package/dist/{chunk-7vjbebst.js.map → chunk-v4exgqbp.js.map} +1 -1
- package/dist/{chunk-7fn3wwyq.js → chunk-vh1hxm9y.js} +2 -2
- package/dist/{chunk-7fn3wwyq.js.map → chunk-vh1hxm9y.js.map} +1 -1
- package/dist/{chunk-1pbwrzwp.js → chunk-vqvdptx4.js} +2 -2
- package/dist/{chunk-1pbwrzwp.js.map → chunk-vqvdptx4.js.map} +1 -1
- package/dist/{chunk-48dek9s7.js → chunk-xnggfm0s.js} +3 -3
- package/dist/{chunk-48dek9s7.js.map → chunk-xnggfm0s.js.map} +1 -1
- package/dist/{chunk-n4807648.js → chunk-xxkk60aw.js} +3 -3
- package/dist/{chunk-n4807648.js.map → chunk-xxkk60aw.js.map} +1 -1
- package/dist/{chunk-xmjhensy.js → chunk-yxh4xs3k.js} +2 -2
- package/dist/{chunk-xmjhensy.js.map → chunk-yxh4xs3k.js.map} +1 -1
- package/dist/{chunk-77kw61f4.js → chunk-zhk3z9zk.js} +3 -3
- package/dist/{chunk-77kw61f4.js.map → chunk-zhk3z9zk.js.map} +1 -1
- package/dist/{chunk-f9t39vwk.js → chunk-zm00crsx.js} +2 -2
- package/dist/{chunk-f9t39vwk.js.map → chunk-zm00crsx.js.map} +1 -1
- package/dist/{chunk-np5b3cd7.js → chunk-zmag8k0z.js} +2 -2
- package/dist/{chunk-np5b3cd7.js.map → chunk-zmag8k0z.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/McpRouter.d.ts +84 -5
- package/dist/http/McpRouter.d.ts.map +1 -1
- package/dist/http/index.d.ts +1 -1
- package/dist/http/index.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/index.js +2 -2
- package/dist/orm/index.js.map +1 -1
- 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/mcp/McpRegistry.d.ts +11 -2
- package/dist/services/mcp/McpRegistry.d.ts.map +1 -1
- package/dist/services/queue/work.js +2 -2
- package/dist/services/queue/work.js.map +1 -1
- package/dist/support/index.js +2 -2
- package/dist/support/index.js.map +1 -1
- package/package.json +1 -1
- package/dist/chunk-23mpa8t7.js +0 -5
- package/dist/chunk-9hs7prvj.js +0 -17
- package/dist/chunk-yhkffean.js +0 -5
- /package/dist/{chunk-bvsevtpp.js.map → chunk-5ngv175h.js.map} +0 -0
- /package/dist/{chunk-aa13sgs2.js.map → chunk-cbywzv21.js.map} +0 -0
- /package/dist/{chunk-80t4tfke.js.map → chunk-rkre6bqc.js.map} +0 -0
package/dist/ai/index.js
CHANGED
|
@@ -1,5 +1,5 @@
|
|
|
1
1
|
// @bun
|
|
2
|
-
import{Ab as i9,Bb as M$,Cb as S$,Db as N3,zb as T}from"../chunk-wc46df4w.js";import{Me as C3,Pe as O3,cf as E1,df as x1,ef as r,ff as KQ,tf as q3,vf as QQ,wf as d}from"../chunk-4x41cmg3.js";import{Af as cQ,xf as P3,zf as uQ}from"../chunk-9xf2fx98.js";import{Ef as RQ}from"../chunk-eqtsfvvd.js";import{Kg as LQ}from"../chunk-48dek9s7.js";import"../chunk-f6s7ddjz.js";import"../chunk-n63xjrck.js";import"../chunk-68zf43ah.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${x3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class zQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function x3(Q){let $=o9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function o9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function A(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function k(Q){if(Q instanceof zQ)return{code:"provider_error",message:Q.message,retryable:!0};if(v3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return w3(Q.status,o9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function w3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let V=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(b3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(I3(G))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||G.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function b3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function I3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function v3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class E extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new E);return new Promise((Z,J)=>{let W=()=>J(new E);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function BQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let G of Q){if(Z){if(J)J=!1;else if(G==="\\")J=!0;else if(G==='"')Z=!1;continue}if(G==='"')Z=!0;else if(G==="{")$.push("}");else if(G==="[")$.push("]");else if(G==="}"||G==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let X=$.reverse().join("");try{return JSON.parse(W+X)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+X)}catch{return{}}}}function DQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:r(Q)}}function UQ(Q,$){let Z=Q.safeParse(BQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function FQ(Q){if(Q.length>0)Q[0];return Q}function e(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function jQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function f3(Q){return mQ(Q)}async function mQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await y3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")h3(Z,J.error,$.origin);if(Q.throwOnError)throw new $Q({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function h3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{QQ.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function y3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,X=M(),G="stop",V,H={},K="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:DQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let j=await y(Promise.resolve(U.next()),W);if(j.done)break;let D=j.value;switch(D.type){case"output-delta":K+=D.delta;break;case"text-delta":e(J,"text",D.delta);break;case"reasoning-delta":jQ(J,D.id,D.delta);break;case"finish":if(X=R(X,D.usage),!V)G=D.reason;break;case"error":G="error",V=D.error,H=A(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof E||W.aborted)G="aborted",V=g3(W);else G="error",V=Q.provider.normalizeError(B),H=A(B)}let Y=!1,z;if(!V)if(G==="length")V={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(!K.trim())V={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=UQ(Q.output,K);if(B.ok===!0)Y=!0,z=B.value;else V=B.error}if(Y)J.content.push({type:"output",value:z});else if(K)e(J,"text",K);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=FQ(B.text);if(J.finishReason=G,J.usage=X,Z.push(J),Y)return{ok:!0,output:z,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...V,...H},messages:Z,usage:X,finishReason:G}}function g3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as u3,hkdfSync as c3,randomBytes as n9,timingSafeEqual as m3}from"crypto";class ZQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class pQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=LQ(),$=Q.bound(d)?Q.make(d).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 l=new ZQ;var dQ="agt2",PQ="agt1",s9=[dQ,PQ],lQ=86400000,p3=Date.now()+lQ;function t9(Q){return Q<=p3}var a9="gemi.ai.pending-call.v1",r9="gemi.ai.nested-run.v1",d3="gemi.ai.execution-receipt.v1",l3="gemi.ai.signing",CQ=new Map;function JQ(Q,$){let Z=iQ($),J=`${Q}\x00${Z}`,W=CQ.get(J);if(!W){if(W=Buffer.from(c3("sha256",Z,l3,Q,32)),CQ.size>64)CQ.clear();CQ.set(J,W)}return W}function iQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function i3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return u3("sha256",Q).update(i3($)).digest()}function e9(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&m3(Z,$)}function oQ(Q){return I(Q??null)}function Q$(Q,$,Z){return[dQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),oQ(Q.subject)]}function o3(Q,$,Z){let J=[PQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var $$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),n3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Z$(Q,$={}){let Z=JQ(a9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,Q$(Q,X,W)).toString("base64url");return[dQ,$$(Q.runId),X,W.toString(36),G].join(".")}function nQ(Q){return qQ(Q,s9)}function qQ(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:n3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function J$(Q,$,Z={}){let J=qQ(Q,s9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===PQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===PQ?g(iQ(Z.secret),o3($,J.nonce,J.expiresAt)):g(JQ(a9,Z.secret),Q$($,J.nonce,J.expiresAt));if(!e9(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var sQ="agn2",OQ="agn1",W$=[sQ,OQ];function X$(Q,$,Z){return[...G$(Q,$,Z,sQ),oQ(Q.subject)]}function G$(Q,$,Z,J=OQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function V$(Q,$={}){let Z=JQ(r9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,X$(Q,X,W)).toString("base64url");return[sQ,$$(Q.runId),X,W.toString(36),G].join(".")}function H$(Q,$,Z={}){let J=qQ(Q,W$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===OQ?g(iQ(Z.secret),G$(W,J.nonce,J.expiresAt)):g(JQ(r9,Z.secret),X$(W,J.nonce,J.expiresAt));if(!e9(Q,X))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}function Y$(Q,$,Z={}){let J=JQ(d3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),oQ($.subject)]).toString("base64url")}function K$(Q,$){return B$($,nQ(Q))}function z$(Q,$){return B$($,qQ(Q,W$))}async function B$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class WQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class i extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function tQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new i("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 Q}var f="gemi_att_";function aQ(){return`${f}${crypto.randomUUID()}`}class XQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;tQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new WQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new WQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=aQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:rQ(Z,W),body:Q,contentType:J||void 0}),G={id:Z,scopeKey:this.scope.key,objectName:X,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,G),G}}function rQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class NQ{rows=new Map;async put(Q,$){tQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){tQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var _Q=new NQ;var eQ=new TextEncoder;function D$(Q){return`id: ${Q.seq}
|
|
2
|
+
import{Ab as i9,Bb as M$,Cb as S$,Db as N3,zb as T}from"../chunk-wc46df4w.js";import{Ne as C3,Qe as O3,df as E1,ef as x1,ff as r,gf as KQ,uf as q3,wf as QQ,xf as d}from"../chunk-3cxbvrts.js";import{Af as uQ,Bf as cQ,yf as P3}from"../chunk-j9deswmn.js";import{Ff as RQ}from"../chunk-ayss2f8c.js";import{Lg as LQ}from"../chunk-xnggfm0s.js";import"../chunk-0fney17e.js";import"../chunk-ma5rmcbe.js";import"../chunk-1xzdexbq.js";class h extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${x3($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class zQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function x3(Q){let $=o9(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function o9(Q){if(!Q||typeof Q!=="object")return null;let $=Q,J=$.error&&typeof $.error==="object"?$.error:Q;if(typeof J.message!=="string"&&typeof J.code!=="string"&&typeof J.type!=="string")return null;let W=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:W,param:J.param}}function A(Q){if(!Q||typeof Q!=="object")return{};let{status:$,requestId:Z}=Q;return{...typeof $==="number"&&$>=100&&$<=599?{status:$}:{},...typeof Z==="string"&&Z?{requestId:Z}:{}}}function k(Q){if(Q instanceof zQ)return{code:"provider_error",message:Q.message,retryable:!0};if(v3(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof h)return w3(Q.status,o9(Q.body),Q.message);if(Q instanceof TypeError)return{code:"provider_error",message:`Could not reach the provider: ${Q.message}`,retryable:!0};if(Q instanceof Error)return{code:"provider_error",message:Q.message,retryable:!1};return{code:"unknown",message:String(Q),retryable:!1}}function w3(Q,$,Z){let J=$?.message??Z,W=($?.code??"").toLowerCase(),X=($?.type??"").toLowerCase(),G=`${W} ${X} ${J}`.toLowerCase();if(Q===429){let V=W==="insufficient_quota"||G.includes("quota");return{code:"rate_limited",message:J,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:J,retryable:!0};if(b3(G))return{code:"context_length_exceeded",message:J,retryable:!1};if(I3(G))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||G.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function b3(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function I3(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function v3(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}class E extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function y(Q,$){if($.aborted)return Promise.reject(new E);return new Promise((Z,J)=>{let W=()=>J(new E);$.addEventListener("abort",W,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",W))})}function M(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function R(Q,$){if(!$)return Q;let Z={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)Z.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)Z.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);if($.imageInputTokens!==void 0||Q.imageInputTokens!==void 0)Z.imageInputTokens=(Q.imageInputTokens??0)+($.imageInputTokens??0);if($.imageOutputTokens!==void 0||Q.imageOutputTokens!==void 0)Z.imageOutputTokens=(Q.imageOutputTokens??0)+($.imageOutputTokens??0);return Z}function BQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let G of Q){if(Z){if(J)J=!1;else if(G==="\\")J=!0;else if(G==='"')Z=!1;continue}if(G==='"')Z=!0;else if(G==="{")$.push("}");else if(G==="[")$.push("]");else if(G==="}"||G==="]")$.pop()}let W=Q;if(Z)W+='"';W=W.replace(/[,:]\s*$/,"");let X=$.reverse().join("");try{return JSON.parse(W+X)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+X)}catch{return{}}}}function DQ(Q){return{name:"output",schema:Q.toJSONSchema(),strict:r(Q)}}function UQ(Q,$){let Z=Q.safeParse(BQ($));if(Z.ok===!0)return{ok:!0,value:Z.value};return{ok:!1,error:{code:"invalid_output",message:`The model's structured answer did not match the output schema: ${Z.errors.join(", ")}`,retryable:!0}}}function FQ(Q){if(Q.length>0)Q[0];return Q}function e(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type===$){J.text=(J.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function jQ(Q,$,Z){let J=Q.content[Q.content.length-1];if(J&&J.type==="reasoning"&&J.id===$){J.text=(J.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function f3(Q){return mQ(Q)}async function mQ(Q,$={}){let Z=`gen_${crypto.randomUUID()}`,J=await y3(Q);if($.settled?.(J),!J.ok){if(Q.logErrors!==!1&&J.error.code!=="aborted")h3(Z,J.error,$.origin);if(Q.throwOnError)throw new $Q({runId:Z,messages:J.messages,finishReason:J.finishReason,usage:J.usage,error:J.error})}return J}function h3(Q,$,Z){let J=`[gemi/ai] generate() failed (${$.code}${$.status!==void 0?` ${$.status}`:""}): ${$.message}`,W={...Z,generateId:Q,error:$},X=!1;try{QQ.error(J,W),X=!0}catch{}if(!X||Bun.env.NODE_ENV==="development")console.error(J,W)}async function y3(Q){let $=Q.messages??[];if($.length===0&&!Q.prompt)throw Error("generate() was given neither a `prompt` nor `messages`, so there is nothing to send the model.");let Z=[...$];if(Q.prompt)Z.push({id:`msg_${crypto.randomUUID()}`,role:"user",content:[{type:"text",text:Q.prompt}],createdAt:new Date().toISOString()});let J={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()},W=Q.signal??new AbortController().signal,X=M(),G="stop",V,H={},K="";try{let U=Q.provider.stream({messages:[...Z],systemPrompt:Q.instructions?.trim()?Q.instructions:void 0,output:DQ(Q.output),reasoning:Q.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature,signal:Q.signal})[Symbol.asyncIterator]();try{for(;;){let j=await y(Promise.resolve(U.next()),W);if(j.done)break;let D=j.value;switch(D.type){case"output-delta":K+=D.delta;break;case"text-delta":e(J,"text",D.delta);break;case"reasoning-delta":jQ(J,D.id,D.delta);break;case"finish":if(X=R(X,D.usage),!V)G=D.reason;break;case"error":G="error",V=D.error,H=A(D);break}}}finally{if(W.aborted)Promise.resolve(U.return?.()).catch(()=>{})}}catch(B){if(B instanceof E||W.aborted)G="aborted",V=g3(W);else G="error",V=Q.provider.normalizeError(B),H=A(B)}let Y=!1,z;if(!V)if(G==="length")V={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(!K.trim())V={code:"invalid_output",message:"The model finished without giving a structured answer.",retryable:!0};else{let B=UQ(Q.output,K);if(B.ok===!0)Y=!0,z=B.value;else V=B.error}if(Y)J.content.push({type:"output",value:z});else if(K)e(J,"text",K);for(let B of J.content)if((B.type==="text"||B.type==="reasoning")&&typeof B.text==="string")B.text=FQ(B.text);if(J.finishReason=G,J.usage=X,Z.push(J),Y)return{ok:!0,output:z,messages:Z,usage:X,finishReason:G};return{ok:!1,error:{...V,...H},messages:Z,usage:X,finishReason:G}}function g3(Q){return Q.reason?.name==="TimeoutError"?{code:"timeout",message:"The generation timed out.",retryable:!0}:{code:"aborted",message:"The generation was stopped.",retryable:!1}}import{createHmac as u3,hkdfSync as c3,randomBytes as n9,timingSafeEqual as m3}from"crypto";class ZQ{spent=new Map;sweepAt=1024;async consume(Q,$){return this.consumeSync(Q,$)}consumeSync(Q,$,Z=Date.now()){if(this.spent.size>=this.sweepAt)this.sweep(Z);let J=this.spent.get(Q);if(J!==void 0&&J>Z)return!1;return this.spent.set(Q,$),!0}get size(){return this.spent.size}sweep(Q){for(let[$,Z]of this.spent)if(Z<=Q)this.spent.delete($);this.sweepAt=Math.max(1024,this.spent.size*2)}}class pQ{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:nonce"}async consume(Q,$){let Z=Math.max(1,Math.ceil($-Date.now()));return await this.client.send("SET",[`${this.prefix}:${Q}`,"1","PX",String(Z),"NX"])==="OK"}get client(){if(this.injectedClient)return this.injectedClient;let Q=LQ(),$=Q.bound(d)?Q.make(d).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 l=new ZQ;var dQ="agt2",PQ="agt1",s9=[dQ,PQ],lQ=86400000,p3=Date.now()+lQ;function t9(Q){return Q<=p3}var a9="gemi.ai.pending-call.v1",r9="gemi.ai.nested-run.v1",d3="gemi.ai.execution-receipt.v1",l3="gemi.ai.signing",CQ=new Map;function JQ(Q,$){let Z=iQ($),J=`${Q}\x00${Z}`,W=CQ.get(J);if(!W){if(W=Buffer.from(c3("sha256",Z,l3,Q,32)),CQ.size>64)CQ.clear();CQ.set(J,W)}return W}function iQ(Q){let $=Q??process.env.SECRET;if(!$)throw Error("Signing a pending tool call needs an app secret. Set SECRET in the environment.");return $}function I(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(I).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${I($[J])}`).join(",")}}`}function i3(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function g(Q,$){return u3("sha256",Q).update(i3($)).digest()}function e9(Q,$){let Z=Buffer.from(Q.split(".")[4],"base64url");return Z.length===$.length&&m3(Z,$)}function oQ(Q){return I(Q??null)}function Q$(Q,$,Z){return[dQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input),I(Q.path??[]),oQ(Q.subject)]}function o3(Q,$,Z){let J=[PQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),I(Q.input)];if(Q.path&&Q.path.length>0)J.push(I(Q.path));return J}var $$=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),n3=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function Z$(Q,$={}){let Z=JQ(a9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,Q$(Q,X,W)).toString("base64url");return[dQ,$$(Q.runId),X,W.toString(36),G].join(".")}function nQ(Q){return qQ(Q,s9)}function qQ(Q,$){let Z=Q.split(".");if(Z.length!==5||!$.includes(Z[0]))return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:n3(Z[1]),nonce:Z[2],expiresAt:J,version:Z[0]}}catch{return null}}function J$(Q,$,Z={}){let J=qQ(Q,s9);if(!J)return{ok:!1,reason:"malformed"};if(J.version===PQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W=J.version===PQ?g(iQ(Z.secret),o3($,J.nonce,J.expiresAt)):g(JQ(a9,Z.secret),Q$($,J.nonce,J.expiresAt));if(!e9(Q,W))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}var sQ="agn2",OQ="agn1",W$=[sQ,OQ];function X$(Q,$,Z){return[...G$(Q,$,Z,sQ),oQ(Q.subject)]}function G$(Q,$,Z,J=OQ){return[J,Q.runId,I(Q.path),Q.nestedRunId,$,String(Z),I([...Q.open].sort()),I(Q.input)]}function V$(Q,$={}){let Z=JQ(r9,$.secret),W=($.now??Date.now())+($.ttlMs??lQ),X=n9(12).toString("base64url"),G=g(Z,X$(Q,X,W)).toString("base64url");return[sQ,$$(Q.runId),X,W.toString(36),G].join(".")}function H$(Q,$,Z={}){let J=qQ(Q,W$);if(!J)return{ok:!1,reason:"malformed"};if(J.version===OQ&&!t9(J.expiresAt))return{ok:!1,reason:"forged"};let W={...$,runId:J.runId},X=J.version===OQ?g(iQ(Z.secret),G$(W,J.nonce,J.expiresAt)):g(JQ(r9,Z.secret),X$(W,J.nonce,J.expiresAt));if(!e9(Q,X))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>J.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:J.runId,nonce:J.nonce,expiresAt:J.expiresAt}}function Y$(Q,$,Z={}){let J=JQ(d3,Z.secret);return g(J,[Q,$.runId,$.toolCallId,$.name,$.kind,I($.input),I($.path??[]),oQ($.subject)]).toString("base64url")}function K$(Q,$){return B$($,nQ(Q))}function z$(Q,$){return B$($,qQ(Q,W$))}async function B$(Q,$){if(!$)return!1;return Q.consume($.nonce,$.expiresAt)}class WQ extends T{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class i extends T{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function tQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new i("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 Q}var f="gemi_att_";function aQ(){return`${f}${crypto.randomUUID()}`}class XQ{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;tQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new WQ(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new WQ(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,W=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([W],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=aQ(),J=$.mimeType??Q.type??"",W=$.name??(Q instanceof File?Q.name:Z),X=await this.storage.put({name:rQ(Z,W),body:Q,contentType:J||void 0}),G={id:Z,scopeKey:this.scope.key,objectName:X,name:W,mimeType:J||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,G),G}}function rQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class NQ{rows=new Map;async put(Q,$){tQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){tQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var _Q=new NQ;var eQ=new TextEncoder;function D$(Q){return`id: ${Q.seq}
|
|
3
3
|
data: ${JSON.stringify(Q.event)}
|
|
4
4
|
|
|
5
5
|
`}var s3=5000,t3=`: keepalive
|
|
@@ -23,4 +23,4 @@ return held`,rZ=`
|
|
|
23
23
|
if redis.call('GET', KEYS[1]) == ARGV[1] then return redis.call('DEL', KEYS[1]) end
|
|
24
24
|
return 0`;class y9{injectedClient;prefix;constructor(Q={}){this.injectedClient=Q.client,this.prefix=Q.prefix??"gemi:ai:receipt"}async claim(Q,$){let Z=await this.client.send("EVAL",[aZ,"1",this.key(Q),a$,r$($)]);if(Z==="claimed")return{status:"claimed"};let J=String(Z??"");if(J.startsWith(f9))return{status:"replay",result:JSON.parse(J.slice(f9.length))};return{status:"blocked"}}async complete(Q,$,Z){await this.client.send("SET",[this.key(Q),f9+JSON.stringify($),"PX",r$(Z)])}async release(Q){await this.client.send("EVAL",[rZ,"1",this.key(Q),a$])}key(Q){return`${this.prefix}:${Q}`}get client(){if(this.injectedClient)return this.injectedClient;let Q=LQ(),$=Q.bound(d)?Q.make(d).client:void 0;if(!$)throw Error("RedisReceiptStore could not reach the Redis client. Register RedisServiceProvider on your application, or pass a client: new RedisReceiptStore({ client }).");return $}}function r$(Q){return String(Math.max(1,Math.ceil(Q-Date.now())))}class vQ{ttlMs;clientOwnedIds;threads=new Map;lastSweep=0;constructor(Q={}){this.ttlMs=Q.ttlMs??86400000,this.clientOwnedIds=Q.clientOwnedIds??!1}async createThread(Q){let $=crypto.randomUUID();return this.threads.set($,{messages:[],touchedAt:Date.now()}),this.sweep(),{threadId:$}}async loadThread(Q){this.sweep();let $=this.threads.get(Q);if(!$)return this.clientOwnedIds?[]:null;return $.touchedAt=Date.now(),$.messages.slice()}async appendMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);Z={messages:[],touchedAt:Date.now()},this.threads.set(Q,Z)}for(let J of $){let W=Z.messages.findIndex((X)=>X.id===J.id);if(W===-1)Z.messages.push(J);else Z.messages[W]=J}Z.touchedAt=Date.now()}async removeMessages(Q,$){this.sweep();let Z=this.threads.get(Q);if(!Z)return;let J=new Set($);Z.messages=Z.messages.filter((W)=>!J.has(W.id)),Z.touchedAt=Date.now()}delete(Q){this.threads.delete(Q)}get size(){return this.threads.size}sweep(Q=Date.now()){if(Q-this.lastSweep<60000)return;this.lastSweep=Q;for(let[$,Z]of this.threads)if(Q-Z.touchedAt>this.ttlMs)this.threads.delete($)}}var g9=new vQ;function Z3(Q={}){return{messages:Q.messages?[...Q.messages]:[],pending:Q.pending?[...Q.pending]:[],error:null,threadId:Q.threadId,seq:Q.seq??-1,cursorRunId:Q.cursorRunId,runMessageIds:[],loadedTools:[]}}function J3(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...W3(Q,$.event,Z),seq:$.seq}}function W3(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0,usage:void 0};case"message-start":return p(Q,$.messageId,Z,(J)=>({...J,role:$.role}));case"text-delta":if(Q3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:J1(J.content,$.delta)}));case"reasoning-delta":if(Q3(Q,$.messageId))return Q;return p(Q,$.messageId,Z,(J)=>({...J,content:W1(J.content,$.delta,$.id)}));case"output-delta":return p(Q,$.messageId,Z,(J)=>({...J,content:$3(J.content,{type:"output",value:$.snapshot,partial:!0},(W)=>W.type==="output")}));case"tool-call":return p(Q,$.messageId,Z,(J)=>{let W=J.content.findIndex((z)=>z.type==="tool-call"&&z.toolCallId===$.part.toolCallId),X=W===-1?void 0:J.content[W],G=$.part.progress??X?.progress,V=$.part.nested??X?.nested,H=$.part.attachments??X?.attachments,K={...$.part,...G?{progress:G}:{},...V?{nested:V}:{},...H?{attachments:H}:{}},Y=J.content.slice();if(W===-1)Y.push(K);else Y[W]=K;return{...J,content:Y}});case"tool-search":{let J=$.loaded.filter((W)=>!Q.loadedTools.includes(W));if(J.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...J]}}case"tool-progress":return e$(Q,$.toolCallId,(J)=>({...J,progress:[...J.progress??[],$.data]}));case"nested-event":{let J=$;return e$(Q,$.toolCallId,(W)=>{let X=W.nested??[],G=X.findIndex((Y)=>Y.runId===J.runId),V=X[G]??{runId:J.runId,agent:J.agent,messages:[]},H=$1(V,J,Z),K=G===-1?[...X,H]:X.map((Y,z)=>z===G?H:Y);return{...W,nested:K}})}case"tool-result":{let J=p(Q,$.messageId,Z,(W)=>({...W,content:$3(W.content,$.part,(X)=>X.type==="tool-result"&&X.toolCallId===$.part.toolCallId)}));return{...J,pending:J.pending.filter((W)=>W.toolCallId!==$.part.toolCallId)}}case"message":{let J=Q.messages.findIndex((G)=>G.id===$.message.id),W=Q.messages.slice();if(J===-1)W.push($.message);else W[J]=$.message;let X=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:W,runMessageIds:X}}case"message-id":{let J=Q.messages.findIndex((X)=>X.id===$.localId);if(J===-1)return Q;let W=Q.messages.some((X)=>X.id===$.messageId)?Q.messages.filter((X,G)=>G!==J):Q.messages.map((X,G)=>G===J?{...X,id:$.messageId}:X);return{...Q,messages:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return p(Q,$.messageId,Z,(J)=>({...J,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},...$.usage?{usage:$.usage}:{},content:$.outputTruncated||$.finishReason==="length"?J.content.filter((W)=>!(W.type==="output"&&W.partial)):J.content.map((W)=>W.type==="output"&&W.partial?{...W,partial:!1}:W)}));case"usage":return{...Q,usage:$.usage};case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:X3(Q,$.finishReason)};default:return Q}}function X3(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?eZ(Z,$):Z)}function eZ(Q,$){let Z=Q.content.map((W)=>W.type==="tool-call"&&W.nested?.some((X)=>X.finishReason===void 0)?{...W,nested:W.nested.map((X)=>X.finishReason===void 0?Q1(X,$):X)}:W);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((W,X)=>W!==Q.content[X])?{...Q,content:Z}:Q}function Q1(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((J)=>J.id),loadedTools:[]};return{...Q,finishReason:$,messages:X3(Z,$)}}function e$(Q,$,Z){for(let J=Q.messages.length-1;J>=0;J--){let W=Q.messages[J],X=W.content.findIndex((K)=>K.type==="tool-call"&&K.toolCallId===$);if(X===-1)continue;if(W.finishReason!==void 0&&!Z1(Q,W,$))return Q;let G=W.content.slice();G[X]=Z(G[X]);let V=Q.messages.slice();V[J]={...W,content:G};let H=Q.runMessageIds.includes(W.id)?Q.runMessageIds:[...Q.runMessageIds,W.id];return{...Q,runMessageIds:H,messages:V}}return Q}function $1(Q,$,Z){let J={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((X)=>X.id),loadedTools:[],finishReason:Q.finishReason},W=W3(J,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:W.messages,...W.finishReason!==void 0?{finishReason:W.finishReason}:{},...W.usage!==void 0?{usage:W.usage}:{}}}function Z1(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((J)=>J.content.some((W)=>W.type==="tool-result"&&W.toolCallId===Z))}function Q3(Q,$){let Z=Q.messages.find((J)=>J.id===$);return Z!==void 0&&Z.finishReason!==void 0}function p(Q,$,Z,J){let W=Q.messages.findIndex((V)=>V.id===$),X=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(W===-1){let V={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:X,messages:[...Q.messages,J(V)]}}let G=Q.messages.slice();return G[W]=J(G[W]),{...Q,runMessageIds:X,messages:G}}function J1(Q,$){let Z=Q[Q.length-1];if(Z&&Z.type==="text")return[...Q.slice(0,-1),{type:"text",text:Z.text+$}];return[...Q,{type:"text",text:$}]}function W1(Q,$,Z){let J=Q[Q.length-1];if(J&&J.type==="reasoning"&&J.id===Z)return[...Q.slice(0,-1),{...J,text:(J.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function $3(Q,$,Z){let J=Q.findIndex(Z);if(J===-1)return[...Q,$];let W=Q.slice();return W[J]=$,W}class c9{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,J){this.store=Q;this.threadId=$;this.report=J;this.state=Z3({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[u9(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=J3(this.state,Q),$.type){case"message":this.write(()=>[u9($.message)]);return;case"tool-call":if($.part.partial)return;this.checkpoint($.messageId);return;case"message-start":case"tool-result":this.checkpoint($.messageId);return;default:return}}close(Q=[]){this.closed=!0;for(let $ of Q)this.done.add($.id)}settled(){return this.chain}checkpoint(Q){if(this.done.has(Q))return;let $=this.state.messages.find((J)=>J.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let J=u9($);if(J.finishReason===void 0&&Z)J.runId=Z;return[J]})}write(Q){let $;try{$=Q()}catch(Z){this.report(Z);return}this.chain=this.chain.then(()=>this.store.appendMessages(this.threadId,$)).catch((Z)=>this.report(Z))}}function u9(Q){return structuredClone(Q)}async function G3(Q,$){let Z=[],J=null,W=Q.slice();for(let X=0;X<W.length;X++){let G=W[X];if(G.role!=="assistant"||G.finishReason!==void 0)continue;if(G.runId&&await $(G.runId))continue;J??=new Set(Q.flatMap((K)=>K.content.flatMap((Y)=>Y.type==="tool-result"?[Y.toolCallId]:[])));let V=G.content.map((K)=>K.type==="tool-call"?V3(K):K);for(let K of G.content){if(K.type!=="tool-call"||J.has(K.toolCallId))continue;let Y={type:"tool-result",toolCallId:K.toolCallId,name:K.name,status:"denied",cause:"interrupted"};V.push(Y)}let H={...G,content:V,finishReason:"interrupted"};W[X]=H,Z.push(H)}return{messages:W,settled:Z}}function V3(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((J)=>J.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(X1)}}function X1(Q){if(Q.finishReason!==void 0)return Q;return{...Q,finishReason:"interrupted",messages:Q.messages.map(($)=>$.role==="assistant"&&$.finishReason===void 0?{...$,finishReason:"interrupted",content:$.content.map((Z)=>Z.type==="tool-call"?V3(Z):Z)}:$)}}var G1=C3,fQ=new Map,H3=new WeakMap,hQ=new Map,V1=4194304,H1=1000,Y1=5,Y3=65536,_3=()=>{};class M3{byKey=new Map;take(Q,$,Z){let J=this.byKey.get(Q);if(!J?.has($)&&(J?.size??0)>=Z)return null;if(!J)J=new Map,this.byKey.set(Q,J);J.set($,(J.get($)??0)+1);let W=!1;return()=>{if(W)return;W=!0;let X=this.byKey.get(Q),G=(X?.get($)??1)-1;if(!X)return;if(G>0)X.set($,G);else if(X.delete($),X.size===0)this.byKey.delete(Q)}}}var K3=new WeakMap;function K1(Q){let $=K3.get(Q);if(!$)$=new M3,K3.set(Q,$);return $}class S3 extends G1{static kind="agent-controller";store=g9;liveRuns=I9;attachments=_Q;attachmentStorage=q3;fileOwners=v9;nonces=l;receipts;requireKnownFiles=!1;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;maxBodyBytes=V1;maxHistoryMessages=H1;maxConcurrentRuns=Y1;runLimitKey(Q,$){return $.owner}authorizeRequest(Q,$){}runOwner(Q){let $=Q.ctx?.()?.user,Z=$?.id??$?.publicId;if(Z!==void 0&&Z!==null&&String(Z)!=="")return`user:${String(Z)}`;return null}async stream(Q=new KQ){let $=await m9(Q,this.maxBodyBytes);if($.error)return yQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,W=C1(Z);if(W.error)return yQ({body:{},error:W.error});let X=W.turn,G=J!==void 0&&Z.regenerate===!0,V=typeof Z.clientRunId==="string"?Z.clientRunId:void 0,H=R3(Z);if(this.requireThread&&!J)return x(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});if(G&&!this.store.removeMessages)return x(501,{code:"regenerate_unsupported",message:"This agent's store cannot remove messages, so a thread's answer cannot be regenerated. Implement `removeMessages` on the AgentStore."});if(!J&&Array.isArray(Z.messages)&&Z.messages.length>this.maxHistoryMessages)return l9(413,"history_too_long",`The conversation has ${Z.messages.length} messages; this agent takes at most ${this.maxHistoryMessages}.`);let K=await this.runOwner(Q),Y=V?{cancelled:!1,owner:K}:null;if(Y)hQ.set(V,Y);let z=null,B=[],U=async()=>{try{return await j()}finally{if(J&&B.length>0&&z===null)await this.store.appendMessages(J,B).catch((D)=>this.reportHookFailure(D))}},j=async()=>{let D;if(J){let O=await this.store.loadThread(J);if(!O)return x(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});if(D=await this.settleThread(J,O,{write:!0}),G){let P=N1(D);if(!P)return x(409,{code:"nothing_to_regenerate",message:`Thread ${J} has no user turn to answer again.`});B=D.slice(P.index),await this.store.removeMessages(J,B.map((E3)=>E3.id)),D=D.slice(0,P.index),X=X?.localId?{...P.turn,localId:X.localId}:P.turn}}else D=Array.isArray(Z.messages)?Z.messages:[],A1(this.nonces);let L=await this.instructions(Q,{body:H})||void 0,F=await this.context(Q,{body:H}),S=await this.attachmentsFor(Q,J,{body:H});if(Y?.cancelled)return F3();let N=J?new c9(this.store,J,D,(O)=>this.reportHookFailure(O)):null,v=`run_${crypto.randomUUID()}`,w={req:Q,runId:v,threadId:J},_=this.agent.stream({runId:v,messages:D,turn:X,threadId:J,...N?{onMessage:(O)=>N.finish(O)}:{},instructions:L,context:F,attachments:S,body:H,redactError:(O,P)=>this.redactError(O,P,w),nonces:this.nonces,receipts:this.receipts,subject:K}),b=this.liveRuns.register(_,{threadId:J,owner:K,clientRunId:V,onEvent:(O)=>this.dispatchEvent(O,w),onInternalError:(O)=>this.reportHookFailure(O),maxRunDurationMs:this.agent.maxRunDurationMs});if(z=_,N)this.follow(_,N);let{stored:q,hooks:C}=this.persistRun(_,w,b,N);return H3.set(_,q),Q.ctx?.()?.waitUntil(C),_.toResponse()};try{await this.authorizeRequest(Q,{route:"stream",threadId:J,body:H});let D=await this.foreignFile([...X?.files??[],...J?[]:M1(Z.messages)],K);if(D)return D;if(Y?.cancelled)return F3();let L=await this.runLimitKey(Q,{owner:K,threadId:J}),F=L===null?_3:K1(this.liveRuns).take(L,J?`thread:${J}`:`run:${crypto.randomUUID()}`,this.maxConcurrentRuns);if(!F)return l9(429,"too_many_runs",`You already have ${this.maxConcurrentRuns} conversations answering. Wait for one to finish, or stop it, and send again.`);try{return J?await this.withThread(J,K,U):await U()}finally{let S=z;if(S)S.result().then(F,F);else F()}}finally{if(Y&&hQ.get(V)===Y)hQ.delete(V)}}async withThread(Q,$,Z){let J=fQ.get(Q)??Promise.resolve(),W,X=new Promise((V)=>{W=V}),G=J.then(()=>X);fQ.set(Q,G),await J;try{let V=await this.liveRuns.find({threadId:Q});if(V&&this.liveRuns.isRunning(V.runId)&&!this.liveRuns.mayAccess(V.runId,$))return gQ();let H=V?this.liveRuns.get(V.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await H3.get(H);return await Z()}finally{if(W(),fQ.get(Q)===G)fQ.delete(Q)}}async attach(Q=new KQ){let $=await m9(Q,Y3);if($.error)return yQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:q1(Q,"threadId");if(!J)return x(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:J});let W=await this.liveRuns.find({threadId:J});if(W&&!this.liveRuns.mayAccess(W.runId,await this.runOwner(Q)))return gQ();if(!W)return x(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let X=typeof Z.runId==="string"?Z.runId:void 0,G=X&&X!==W.runId?void 0:O1(Q,Z);try{return U$(this.liveRuns.replay(W.runId,G))}catch(V){if(V instanceof a)return x(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof YQ)return x(404,{code:V.code,message:V.message});throw V}}async stop(Q=new KQ){let $=await m9(Q,Y3);if($.error)return yQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=await this.runOwner(Q),W=typeof Z.runId==="string"?Z.runId:void 0;if(!W&&typeof Z.clientRunId==="string"){if(W=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!W){let G=hQ.get(Z.clientRunId);if(G){if(G.owner!==null&&G.owner!==J)return gQ();return G.cancelled=!0,{stopped:!0}}}}if(!W&&typeof Z.threadId==="string")W=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let X=W?this.liveRuns.get(W):null;if(!X)return{stopped:!1};if(!this.liveRuns.mayAccess(X.runId,J))return gQ();return X.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$,Z){let J=Q.ctx()?.user,W=J?.id??J?.publicId;if(W!==void 0&&W!==null&&String(W)!=="")return{key:`user:${String(W)}`};if($)return{key:`thread:${$}`};return null}attachmentLimits(Q){return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$,Z={body:{}}){let J=await this.attachmentScope(Q,$,Z);if(!J)return null;return new XQ(this.attachments,this.attachmentStorage,J)}async upload(Q=new KQ){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let J=Z instanceof File&&Z.name?Z.name:"upload",W=Z.type||"application/octet-stream",X=B1($.get("body")),G=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof G==="string"&&G.length>0?G:void 0,body:X});let V=U1(await this.attachmentLimits(Q),Z,J,W);if(V)throw new T3(V.code,V.message);let H=typeof G==="string"&&G.length>0&&await this.store.loadThread(G)!==null?G:void 0,K=await this.runOwner(Q),Y=(N)=>this.fileOwners.record(N,{owner:K,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString()}),z=await this.attachmentDestination(Z,Q),B=S1(z,$.get("destination")),U=await this.attachmentScope(Q,H,{body:X}),j=B!=="provider"&&!U;if(j){if(B==="storage")throw Error('This upload was routed to storage, but `attachmentScope()` returned null for the request, so there is no subject to file the attachment under. Guard the route (`this.agent(Chat).middleware({ upload: "auth" })`), send a `threadId` with the upload, or override `attachmentScope()`.');R1()}if(B==="provider"||!U){let N=await z3(this.agent.provider,Z);await Y(N);let v={fileId:N,name:J,mimeType:W,size:Z.size,destination:"provider"};if(j)v.downgraded="no_scope";return v}let D=aQ(),L=await this.attachmentStorage.put({name:rQ(D,J),body:Z,contentType:W}),F=B==="both"?await z3(this.agent.provider,Z):void 0;if(F)await Y(F);let S={id:D,scopeKey:U.key,fileId:F,objectName:L,name:J,mimeType:W,size:Z.size,createdAt:new Date().toISOString(),destination:B};return await this.attachments.put(U,S),{fileId:F,attachmentId:D,name:J,mimeType:W,size:Z.size,destination:B}}async foreignFile(Q,$){let Z=new Set(Q.map((J)=>J.fileId).filter((J)=>typeof J==="string"));for(let J of Z){let W=await this.fileOwners.get(J);if(W?W.owner!==null&&W.owner!==$:this.requireKnownFiles)return _1()}return null}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(Q,$){}redactError(Q,$,Z){return i9(Q,$)}onError(Q,$){}onStreamComplete(Q,$){}reportHookFailure(Q){console.error("[gemi/ai] agent controller hook failed",Q)}async dispatchEvent(Q,$){switch(Q.type){case"tool-call":if(!Q.part.partial&&!Q.resent)await this.onToolCall({toolCallId:Q.part.toolCallId,name:String(Q.part.name),input:Q.part.input},$);return;case"awaiting-input":await this.onAwaitingInput(Q.pending,$);return;case"error":await this.onError(N3(Q.error),$);return;default:return}}async readThread(Q){let $=await this.store.loadThread(Q);return $?await this.settleThread(Q,$,{write:!1}):null}isRunLive(Q,$){return this.liveRuns.get(Q)!==null}async settleThread(Q,$,{write:Z}){let{messages:J,settled:W}=await G3($,(X)=>this.isRunLive(X,Q));if(Z&&W.length>0)try{await this.store.appendMessages(Q,W)}catch(X){this.reportHookFailure(X)}return J}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,J=null){let W=Promise.resolve(),X=(async()=>{let V;try{V=await Q.result()}catch(K){J?.close(),await J?.settled(),W=this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},$));return}let H=V.messages;if(J?.close(H),await J?.settled(),$.threadId&&H.length>0)try{await this.store.appendMessages($.threadId,H)}catch(K){this.reportHookFailure(K)}W=this.notifyRun(V,H,$)})(),G=X.then(()=>k1(Promise.all([W,Z]).then(()=>{}),this.hookHoldMs));return{stored:X,hooks:G}}async notifyRun(Q,$,Z){for(let J of $)await this.safely(()=>this.onMessage(J,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var p9=["turn","clientRunId","threadId","messages","regenerate"],z1=["text","files","toolResults"];function R3(Q,$=A3(Q)?p9:[...p9,...z1]){let Z={};for(let[J,W]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:W,writable:!0,enumerable:!0,configurable:!0})}return Z}function B1(Q){if(Q===null)return{};let $;if(typeof Q==="string")try{$=JSON.parse(Q)}catch{throw new d9("The upload's `body` field is not valid JSON.")}if($===null||typeof $!=="object"||Array.isArray($))throw new d9("The upload's `body` field must be a JSON object.");return R3($,p9)}class d9 extends uQ{constructor(Q){super(Q);this.name="InvalidUploadError",this.payload={api:{status:400,data:{error:{code:"invalid_request",message:Q}}},view:{}}}}async function z3(Q,$){try{return await Q.upload($)}catch(Z){if(Z instanceof h&&D1.has(Z.status))throw new k3(k(Z).message);throw Z}}var D1=new Set([400,413,415,422]);class T3 extends uQ{constructor(Q,$){super($);this.name="LimitedUploadError",this.payload={api:{status:422,data:{error:{code:Q,message:$}}},view:{}}}}function U1(Q,$,Z,J){if(!Q)return null;let{maxBytes:W,accept:X}=Q;if(typeof W==="number"&&$.size>W)return{code:"file_too_large",message:`${JSON.stringify(Z)} is ${B3($.size)}; the limit is ${B3(W)}.`};if(X&&X.length>0&&!X.some((G)=>F1(G,Z,J)))return{code:"unsupported_file_type",message:`${JSON.stringify(Z)} is not a type this chat accepts. Accepted: ${X.join(", ")}.`};return null}function F1(Q,$,Z){let J=Q.trim().toLowerCase();if(!J)return!1;if(J.startsWith("."))return $.toLowerCase().endsWith(J);let W=Z.toLowerCase().split(";")[0].trim();if(J.endsWith("/*"))return W.startsWith(J.slice(0,-1));return W===J}function B3(Q){if(Q<1024)return`${Q} B`;let $=["KB","MB","GB"],Z=Q/1024,J=0;while(Z>=1024&&J<$.length-1)Z/=1024,J++;return`${Math.round(Z*10)/10} ${$[J]}`}class k3 extends uQ{constructor(Q){super(Q);this.name="RejectedUploadError";let $=/(unsupported|invalid) (extension|file type|format|mime)|supported (extensions|formats?)/i.test(Q)?"unsupported_file_type":"file_rejected";this.payload={api:{status:422,data:{error:{code:$,message:Q}}},view:{}}}}async function m9(Q,$){let Z=Q?.rawRequest;if(!Z||Z.method==="GET"||Z.method==="HEAD"||!Z.body)return{body:{}};if(!j1(Z.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let J=Number(Z.headers.get("Content-Length"));if(Number.isFinite(J)&&J>$)return D3($);let W;try{let G=await L1(Z,$);if(G===null)return D3($);W=G}catch{return{body:{},error:"The request body could not be read."}}if(!W.trim())return{body:{}};let X;try{X=JSON.parse(W)}catch{return{body:{},error:"The request body is not valid JSON."}}if(X===null||typeof X!=="object"||Array.isArray(X))return{body:{},error:"The request body must be a JSON object."};return{body:X}}function j1(Q){return O3(Q)==="application/json"}async function L1(Q,$){if(!Number.isFinite($)||!Q.body)return await Q.text();let Z=Q.body.getReader(),J=[],W=0;for(;;){let{done:V,value:H}=await Z.read();if(V)break;if(W+=H.byteLength,W>$)return await Z.cancel().catch(_3),null;J.push(H)}let X=new Uint8Array(W),G=0;for(let V of J)X.set(V,G),G+=V.byteLength;return new TextDecoder().decode(X)}function D3(Q){return{body:{},status:413,code:"body_too_large",error:`The request body is larger than this agent accepts (${Q} bytes).`}}function l9(Q,$,Z){return x(Q,{...cQ(P3(Q),Z,Q),code:$})}function yQ(Q){if(Q.status===413)return l9(413,Q.code??"body_too_large",Q.error??"");return x(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function A3(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function C1(Q){let $=A3(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=P1($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;if(Object.keys(Z).length===0)return{};if($===Q.turn&&$.localId!==void 0&&$.localId!==null&&$.localId!==""){let{localId:J}=$;if(typeof J!=="string")return{error:"turn.localId must be a string."};if(J.length>U3)return{error:`turn.localId is longer than ${U3} characters.`};Z.localId=J}return{turn:Z}}var U3=200;function P1(Q){let $=[];for(let[Z,J]of Q.entries()){let W=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${W} must be an object.`;let X={};for(let Y of["fileId","attachmentId","name","mimeType"]){let z=J[Y];if(z===void 0||z===null||z==="")continue;if(typeof z!=="string")return`${W}.${Y} must be a string.`;X[Y]=z}let{fileId:G,attachmentId:V,name:H,mimeType:K}=X;if(G?.startsWith(f))return`${W}.fileId holds a gemi attachment id (${G}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(f))return`${W}.attachmentId is not a gemi attachment id: it must start with "${f}".`;if(!G&&!V)return`${W} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...G?{fileId:G}:{},...V?{attachmentId:V}:{},...H!==void 0?{name:H}:{},...K!==void 0?{mimeType:K}:{}})}return $}function O1(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let J=Math.floor($.cursor);if(J>=0)return J+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let J=Number.parseInt(Z,10);if(Number.isFinite(J))return Math.max(0,J+1)}return}function q1(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function N1(Q){let $=SQ(Q);for(let Z=Q.length-1;Z>=0;Z--){let J=Q[Z];if(J.role!=="user"||$.has(J.id))continue;let W="",X=[];for(let G of J.content){if(G.type==="text")W+=G.text;if(G.type==="file")X.push({...G.fileId?{fileId:G.fileId}:{},...G.attachmentId?{attachmentId:G.attachmentId}:{},...G.name?{name:G.name}:{},...G.mimeType?{mimeType:G.mimeType}:{}})}if(!W&&X.length===0)continue;return{index:Z,turn:{...W?{text:W}:{},...X.length>0?{files:X}:{}}}}return null}function F3(){return x(409,{code:"stopped",message:"The turn was stopped before it started."})}function gQ(){return x(403,cQ("permission","This run belongs to someone else.",403))}function _1(){return x(403,cQ("permission","A file in this turn was uploaded by someone else.",403))}function M1(Q){if(!Array.isArray(Q))return[];let $=[];for(let Z of Q){let J=Z?.content;if(!Array.isArray(J))continue;for(let W of J)if(W&&typeof W==="object"&&typeof W.fileId==="string")$.push({fileId:W.fileId})}return $}function x(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function S1(Q,$){if(typeof $!=="string"||$.length===0)return Q;if($!=="both"&&$!=="provider"&&$!=="storage")throw Error(`Unknown attachment destination "${$}". Expected "both", "provider" or "storage".`);if($===Q||Q==="both"&&$==="storage")return $;if(Q==="both"&&$==="provider")throw Error('This upload asked for the "provider" destination under a "both" policy. A client may ask for "storage", which keeps a file away from the model provider, but it may not ask the server to stop keeping its own copy while the vendor still gets the file \u2014 that is the app\'s retention decision. Change `attachmentDestination()` if this file should not be kept.');throw Error(`This upload asked for the "${$}" destination, but the server's policy for it is "${Q}", and a client hint may only ask for "storage" under a "both" policy. Change \`attachmentDestination()\` if the file really should go there.`)}var j3=!1;function R1(){if(j3)return;j3=!0,console.warn("[gemi/ai] An upload had no attachment scope, so its bytes were sent to the model provider only and no attachment id was minted \u2014 a tool cannot forward this file. Guard the route with auth, send a `threadId` with the upload, or override `attachmentScope()`.")}var T1=2147483647;function k1(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=T1))return Z;let J,W=new Promise((X)=>{J=setTimeout(X,$)});return Promise.race([Z,W]).finally(()=>clearTimeout(J))}var L3=!1;function A1(Q){if(L3||Bun.env.NODE_ENV!=="production")return;if(!(Q instanceof ZQ))return;L3=!0,console.warn("[gemi/ai] A stateless agent chat is spending approval nonces in process memory. With more than one instance a replayed approval is accepted once per instance. Set `nonces = new RedisNonceStore()` (or your own NonceStore) on the AgentController.")}export{BZ as toAgentTools,r as supportsStrict,x1 as s,i9 as redactError,I9 as liveRuns,f3 as generate,tZ as evalChain,l as defaultNonceStore,v9 as defaultFileOwners,_Q as defaultAttachmentStore,g9 as defaultAgentStore,o as ToolNamespace,T as ToolError,V9 as Skill,XQ as ScopedAttachments,GQ as SKILLS_NAMESPACE,y9 as RedisReceiptStore,pQ as RedisNonceStore,u as PendingEscalation,A9 as OpenAIProvider,j9 as OpenAIImageProvider,h9 as MemoryReceiptStore,ZQ as MemoryNonceStore,bQ as MemoryLiveRuns,IQ as MemoryFileOwners,wQ as MemoryCircuitStore,NQ as MemoryAttachmentStore,vQ as MemoryAgentStore,YQ as LiveRunNotFoundError,E1 as JSONSchemaError,i as InvalidAttachmentScopeError,AQ as ImageRequestError,EQ as ImageProvider,D9 as ImageModel,a as FrameCursorEvictedError,HQ as FallbackProvider,K9 as DEFAULT_MAX_RUN_DURATION_MS,E9 as AzureOpenAIProvider,L9 as AzureOpenAIImageProvider,WQ as AttachmentNotFoundError,c as AgentTool,$Q as AgentRunError,t as AgentProvider,S3 as AgentController,z9 as Agent};
|
|
25
25
|
|
|
26
|
-
//# debugId=
|
|
26
|
+
//# debugId=7925515A52C0340964756E2164756E21
|