gemi 0.60.0 → 0.61.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.
Files changed (183) hide show
  1. package/dist/ai/Agent.d.ts +533 -25
  2. package/dist/ai/Agent.d.ts.map +1 -1
  3. package/dist/ai/Agent.test-d.d.ts +2 -0
  4. package/dist/ai/Agent.test-d.d.ts.map +1 -0
  5. package/dist/ai/AgentController.d.ts +275 -6
  6. package/dist/ai/AgentController.d.ts.map +1 -1
  7. package/dist/ai/AgentProvider.d.ts +255 -0
  8. package/dist/ai/AgentProvider.d.ts.map +1 -0
  9. package/dist/ai/Schema.d.ts +125 -0
  10. package/dist/ai/Schema.d.ts.map +1 -0
  11. package/dist/ai/Schema.test-d.d.ts +2 -0
  12. package/dist/ai/Schema.test-d.d.ts.map +1 -0
  13. package/dist/ai/client/index.d.ts +24 -0
  14. package/dist/ai/client/index.d.ts.map +1 -0
  15. package/dist/ai/client/index.js +1053 -0
  16. package/dist/ai/client/index.js.map +1 -0
  17. package/dist/ai/client/reducer.d.ts +127 -0
  18. package/dist/ai/client/reducer.d.ts.map +1 -0
  19. package/dist/ai/client/reducer.test-d.d.ts +2 -0
  20. package/dist/ai/client/reducer.test-d.d.ts.map +1 -0
  21. package/dist/ai/client/sse.d.ts +54 -0
  22. package/dist/ai/client/sse.d.ts.map +1 -0
  23. package/dist/ai/example.d.ts +129 -0
  24. package/dist/ai/example.d.ts.map +1 -0
  25. package/dist/ai/index.d.ts +35 -0
  26. package/dist/ai/index.d.ts.map +1 -0
  27. package/dist/ai/index.js +20 -0
  28. package/dist/ai/index.js.map +23 -0
  29. package/dist/ai/live/harness.d.ts +137 -0
  30. package/dist/ai/live/harness.d.ts.map +1 -0
  31. package/dist/ai/providers/call.d.ts +42 -0
  32. package/dist/ai/providers/call.d.ts.map +1 -0
  33. package/dist/ai/providers/capabilities.d.ts +50 -0
  34. package/dist/ai/providers/capabilities.d.ts.map +1 -0
  35. package/dist/ai/providers/errors.d.ts +37 -0
  36. package/dist/ai/providers/errors.d.ts.map +1 -0
  37. package/dist/ai/providers/fakeProvider.d.ts +35 -0
  38. package/dist/ai/providers/fakeProvider.d.ts.map +1 -0
  39. package/dist/ai/providers/http.d.ts +46 -0
  40. package/dist/ai/providers/http.d.ts.map +1 -0
  41. package/dist/ai/providers/request.d.ts +69 -0
  42. package/dist/ai/providers/request.d.ts.map +1 -0
  43. package/dist/ai/providers/stream.d.ts +42 -0
  44. package/dist/ai/providers/stream.d.ts.map +1 -0
  45. package/dist/ai/signing.d.ts +195 -0
  46. package/dist/ai/signing.d.ts.map +1 -0
  47. package/dist/ai/store/LiveRuns.d.ts +142 -0
  48. package/dist/ai/store/LiveRuns.d.ts.map +1 -0
  49. package/dist/ai/store/MemoryAgentStore.d.ts +61 -0
  50. package/dist/ai/store/MemoryAgentStore.d.ts.map +1 -0
  51. package/dist/ai/store/index.d.ts +4 -0
  52. package/dist/ai/store/index.d.ts.map +1 -0
  53. package/dist/ai/store/sse.d.ts +58 -0
  54. package/dist/ai/store/sse.d.ts.map +1 -0
  55. package/dist/ai/store/stubAgentRun.d.ts +56 -0
  56. package/dist/ai/store/stubAgentRun.d.ts.map +1 -0
  57. package/dist/ai/types.d.ts +443 -0
  58. package/dist/ai/types.d.ts.map +1 -0
  59. package/dist/ai/useChat.d.ts +253 -7
  60. package/dist/ai/useChat.d.ts.map +1 -1
  61. package/dist/chunk-1aqzcgfr.js +5 -0
  62. package/dist/chunk-1aqzcgfr.js.map +10 -0
  63. package/dist/{chunk-get4mkx8.js → chunk-1b7e9rj7.js} +2 -2
  64. package/dist/{chunk-get4mkx8.js.map → chunk-1b7e9rj7.js.map} +1 -1
  65. package/dist/{chunk-x8beq9c4.js → chunk-3aemqfdr.js} +2 -2
  66. package/dist/{chunk-x8beq9c4.js.map → chunk-3aemqfdr.js.map} +1 -1
  67. package/dist/{chunk-j06g4sqc.js → chunk-528n3vgy.js} +2 -2
  68. package/dist/{chunk-j06g4sqc.js.map → chunk-528n3vgy.js.map} +1 -1
  69. package/dist/{chunk-2khdxyjb.js → chunk-57a0nqfj.js} +1 -1
  70. package/dist/chunk-57a0nqfj.js.map +10 -0
  71. package/dist/{chunk-c40n5r4v.js → chunk-5mhcwnyd.js} +2 -2
  72. package/dist/{chunk-c40n5r4v.js.map → chunk-5mhcwnyd.js.map} +1 -1
  73. package/dist/{chunk-gwchvzdp.js → chunk-71pk1mxx.js} +2 -2
  74. package/dist/{chunk-gwchvzdp.js.map → chunk-71pk1mxx.js.map} +1 -1
  75. package/dist/{chunk-spbgpndn.js → chunk-7t1hjs9f.js} +2 -2
  76. package/dist/{chunk-spbgpndn.js.map → chunk-7t1hjs9f.js.map} +1 -1
  77. package/dist/{chunk-9gsdcjt7.js → chunk-7xvaace2.js} +3 -3
  78. package/dist/{chunk-9gsdcjt7.js.map → chunk-7xvaace2.js.map} +1 -1
  79. package/dist/{chunk-fxy42w6n.js → chunk-8ag0da2s.js} +2 -2
  80. package/dist/{chunk-fxy42w6n.js.map → chunk-8ag0da2s.js.map} +1 -1
  81. package/dist/chunk-8r8epsef.js +5 -0
  82. package/dist/chunk-8r8epsef.js.map +11 -0
  83. package/dist/chunk-91cj3nxk.js +6 -0
  84. package/dist/{chunk-y3zz410b.js.map → chunk-91cj3nxk.js.map} +2 -2
  85. package/dist/{chunk-0fm6jh9b.js → chunk-9nmvm20t.js} +2 -2
  86. package/dist/{chunk-0fm6jh9b.js.map → chunk-9nmvm20t.js.map} +1 -1
  87. package/dist/{chunk-98a3k7bp.js → chunk-9xpa7dpy.js} +2 -2
  88. package/dist/{chunk-98a3k7bp.js.map → chunk-9xpa7dpy.js.map} +1 -1
  89. package/dist/{chunk-qva4841r.js → chunk-a1exbqcq.js} +3 -3
  90. package/dist/{chunk-qva4841r.js.map → chunk-a1exbqcq.js.map} +1 -1
  91. package/dist/{chunk-cw9y6k15.js → chunk-bb19bwg6.js} +2 -2
  92. package/dist/{chunk-cw9y6k15.js.map → chunk-bb19bwg6.js.map} +1 -1
  93. package/dist/{chunk-3gvjn3q4.js → chunk-cf7bvd12.js} +1 -1
  94. package/dist/{chunk-rkbv3df7.js → chunk-djp2xeqe.js} +2 -2
  95. package/dist/{chunk-rkbv3df7.js.map → chunk-djp2xeqe.js.map} +1 -1
  96. package/dist/chunk-ds44bqr9.js +4 -0
  97. package/dist/{chunk-4mcyyh1v.js.map → chunk-ds44bqr9.js.map} +4 -9
  98. package/dist/{chunk-wzvs3sym.js → chunk-exndjhza.js} +3 -3
  99. package/dist/{chunk-wzvs3sym.js.map → chunk-exndjhza.js.map} +1 -1
  100. package/dist/{chunk-f6dd4gd8.js → chunk-f233yzxf.js} +2 -2
  101. package/dist/{chunk-f6dd4gd8.js.map → chunk-f233yzxf.js.map} +1 -1
  102. package/dist/chunk-fz5g2z6h.js +4 -0
  103. package/dist/{chunk-fbvvqf9b.js.map → chunk-fz5g2z6h.js.map} +2 -2
  104. package/dist/{chunk-vj9538yn.js → chunk-gcszdwcb.js} +2 -2
  105. package/dist/{chunk-vj9538yn.js.map → chunk-gcszdwcb.js.map} +1 -1
  106. package/dist/{chunk-pkjq9833.js → chunk-htesx7ym.js} +4 -4
  107. package/dist/{chunk-pkjq9833.js.map → chunk-htesx7ym.js.map} +1 -1
  108. package/dist/chunk-hyxmmj9b.js +5 -0
  109. package/dist/{chunk-khf9xda6.js.map → chunk-hyxmmj9b.js.map} +2 -2
  110. package/dist/{chunk-stq96kya.js → chunk-k2sjvt0c.js} +2 -2
  111. package/dist/{chunk-stq96kya.js.map → chunk-k2sjvt0c.js.map} +1 -1
  112. package/dist/{chunk-zhbrkpb3.js → chunk-k75phgj4.js} +4 -4
  113. package/dist/{chunk-zhbrkpb3.js.map → chunk-k75phgj4.js.map} +1 -1
  114. package/dist/{chunk-y64j80v9.js → chunk-m0tp7zjp.js} +2 -2
  115. package/dist/{chunk-y64j80v9.js.map → chunk-m0tp7zjp.js.map} +1 -1
  116. package/dist/{chunk-06j6rsew.js → chunk-m45j7p1y.js} +2 -2
  117. package/dist/{chunk-06j6rsew.js.map → chunk-m45j7p1y.js.map} +1 -1
  118. package/dist/chunk-mca9wsvs.js +5 -0
  119. package/dist/{chunk-z2tcxwyr.js.map → chunk-mca9wsvs.js.map} +3 -4
  120. package/dist/{chunk-tey1xayb.js → chunk-ms13evzp.js} +2 -2
  121. package/dist/{chunk-tey1xayb.js.map → chunk-ms13evzp.js.map} +1 -1
  122. package/dist/{chunk-bn1v4sfs.js → chunk-r962ae93.js} +2 -2
  123. package/dist/{chunk-bn1v4sfs.js.map → chunk-r962ae93.js.map} +1 -1
  124. package/dist/{chunk-23h0dmx2.js → chunk-s41ees18.js} +2 -2
  125. package/dist/{chunk-23h0dmx2.js.map → chunk-s41ees18.js.map} +1 -1
  126. package/dist/chunk-snb68dgr.js +4 -0
  127. package/dist/{chunk-hwhw98hc.js.map → chunk-snb68dgr.js.map} +1 -1
  128. package/dist/chunk-sz051605.js +5 -0
  129. package/dist/chunk-sz051605.js.map +14 -0
  130. package/dist/{chunk-2cwcfwg3.js → chunk-tr3cbx8k.js} +2 -2
  131. package/dist/{chunk-2cwcfwg3.js.map → chunk-tr3cbx8k.js.map} +2 -2
  132. package/dist/{chunk-dgasxgsm.js → chunk-vqcswg7h.js} +2 -2
  133. package/dist/{chunk-dgasxgsm.js.map → chunk-vqcswg7h.js.map} +2 -2
  134. package/dist/{chunk-zqsfanvk.js → chunk-wpb1xpdp.js} +2 -2
  135. package/dist/{chunk-zqsfanvk.js.map → chunk-wpb1xpdp.js.map} +1 -1
  136. package/dist/{chunk-z1e55w67.js → chunk-ybqss0jy.js} +2 -2
  137. package/dist/{chunk-z1e55w67.js.map → chunk-ybqss0jy.js.map} +1 -1
  138. package/dist/{chunk-cejf873g.js → chunk-yk5wqmyh.js} +2 -2
  139. package/dist/{chunk-cejf873g.js.map → chunk-yk5wqmyh.js.map} +1 -1
  140. package/dist/{chunk-8kj3zrm9.js → chunk-ywntv8yw.js} +4 -4
  141. package/dist/{chunk-8kj3zrm9.js.map → chunk-ywntv8yw.js.map} +1 -1
  142. package/dist/chunks/{ThemeProvider-ByU4BQdL.js → ThemeProvider-BZ2SsSZ3.js} +60 -39
  143. package/dist/chunks/ThemeProvider-BZ2SsSZ3.js.map +1 -0
  144. package/dist/chunks/useParams-BN3XXfmG.js +20 -0
  145. package/dist/chunks/useParams-BN3XXfmG.js.map +1 -0
  146. package/dist/client/index.js +3 -3
  147. package/dist/client/index.js.map +1 -1
  148. package/dist/client/useDictionary.d.ts.map +1 -1
  149. package/dist/database/index.js +1 -1
  150. package/dist/facades/index.js +2 -2
  151. package/dist/facades/index.js.map +1 -1
  152. package/dist/http/ApiRouter.d.ts +30 -2
  153. package/dist/http/ApiRouter.d.ts.map +1 -1
  154. package/dist/http/index.js +2 -2
  155. package/dist/http/index.js.map +1 -1
  156. package/dist/i18n/defineDictionary.d.ts +7 -4
  157. package/dist/i18n/defineDictionary.d.ts.map +1 -1
  158. package/dist/i18n/dictionaryRegistry.d.ts +38 -14
  159. package/dist/i18n/dictionaryRegistry.d.ts.map +1 -1
  160. package/dist/i18n/dictionaryRuntime.js +1 -1
  161. package/dist/i18n/index.js +2 -2
  162. package/dist/i18n/index.js.map +2 -2
  163. package/dist/kernel/index.js +2 -2
  164. package/dist/kernel/index.js.map +2 -2
  165. package/dist/orm/index.js +2 -2
  166. package/dist/orm/index.js.map +2 -2
  167. package/dist/server/index.js +1 -1
  168. package/dist/services/index.js +2 -2
  169. package/dist/services/index.js.map +2 -2
  170. package/dist/testing/index.js +2 -1
  171. package/dist/testing/index.js.map +1 -1
  172. package/package.json +3 -1
  173. package/dist/chunk-2khdxyjb.js.map +0 -10
  174. package/dist/chunk-4mcyyh1v.js +0 -4
  175. package/dist/chunk-fbvvqf9b.js +0 -4
  176. package/dist/chunk-hwhw98hc.js +0 -4
  177. package/dist/chunk-khf9xda6.js +0 -5
  178. package/dist/chunk-q0y0j3ne.js +0 -5
  179. package/dist/chunk-q0y0j3ne.js.map +0 -11
  180. package/dist/chunk-y3zz410b.js +0 -6
  181. package/dist/chunk-z2tcxwyr.js +0 -5
  182. package/dist/chunks/ThemeProvider-ByU4BQdL.js.map +0 -1
  183. /package/dist/{chunk-3gvjn3q4.js.map → chunk-cf7bvd12.js.map} +0 -0
@@ -0,0 +1,20 @@
1
+ // @bun
2
+ import{_e as C2,jf as v}from"../chunk-sz051605.js";import"../chunk-mca9wsvs.js";import"../chunk-4dan69s4.js";var kQ=new WeakMap;function WQ(Q){let $=kQ.get(Q);if(!$)throw Error("gemi/ai: expected a schema built with `s`, got a foreign object");return $}function u(Q){let $=M2(L2(Q.node),Q.optional||Q.nullable);return Q.description?{description:Q.description,...$}:$}function L2(Q){switch(Q.kind){case"string":return{type:"string"};case"number":return{type:"number"};case"boolean":return{type:"boolean"};case"literal":return{type:typeof Q.value,const:Q.value};case"enum":return{type:"string",enum:Q.values};case"array":return{type:"array",items:u(Q.item)};case"object":return{type:"object",properties:Object.fromEntries(Object.entries(Q.shape).map(([$,G])=>[$,u(G)])),required:Object.keys(Q.shape),additionalProperties:!1};case"union":return{anyOf:Q.members.map(u)}}}function M2(Q,$){if(!$)return Q;if(Q.anyOf)return{...Q,anyOf:[...Q.anyOf,{type:"null"}]};if(Q.enum||Q.const!==void 0)return{anyOf:[Q,{type:"null"}]};if(typeof Q.type==="string")return{...Q,type:[Q.type,"null"]};return{anyOf:[Q,{type:"null"}]}}function q2(Q){if(Q===null)return"null";if(Array.isArray(Q))return"array";return typeof Q}function P2(Q,$){if(typeof $==="number"&&!Number.isFinite($))return String($);if(Q.kind==="literal"||Q.kind==="enum"){if(typeof $==="string"||typeof $==="number"||typeof $==="boolean")return JSON.stringify($)}return q2($)}function T2(Q){let $=Q.node,G=(()=>{switch($.kind){case"string":case"number":case"boolean":return $.kind;case"literal":return JSON.stringify($.value);case"enum":return`one of ${$.values.map((Z)=>JSON.stringify(Z)).join(" | ")}`;case"array":return"array";case"object":return"object";case"union":return"one of the variants"}})();return Q.optional||Q.nullable?`${G} or null`:G}function xQ(Q){return Q?`${Q}: `:""}function JQ(Q,$){if($===null||$===void 0)return Q.optional||Q.nullable?1:0;let G=Q.node;switch(G.kind){case"string":return typeof $==="string"?1:0;case"number":return typeof $==="number"?1:0;case"boolean":return typeof $==="boolean"?1:0;case"literal":return $===G.value?10:0;case"enum":return typeof $==="string"&&G.values.includes($)?10:0;case"array":return Array.isArray($)?1:0;case"object":{if(typeof $!=="object"||Array.isArray($))return 0;let Z=$,W=1;for(let[J,Y]of Object.entries(G.shape))W+=JQ(Y,Z[J]);return W}case"union":return G.members.reduce((Z,W)=>Math.max(Z,JQ(W,$)),0)}}function w(Q,$,G,Z){if(Q.optional&&($===null||$===void 0))return{drop:!0,value:void 0};if(Q.nullable&&$===null)return{drop:!1,value:null};return{drop:!1,value:S2(Q,$,G,Z)}}function S2(Q,$,G,Z){let W=Q.node,J=()=>{Z.push(`${xQ(G)}expected ${T2(Q)}, got ${P2(W,$)}`);return};switch(W.kind){case"string":return typeof $==="string"?$:J();case"number":return typeof $==="number"&&Number.isFinite($)?$:J();case"boolean":return typeof $==="boolean"?$:J();case"literal":return $===W.value?$:J();case"enum":return typeof $==="string"&&W.values.includes($)?$:J();case"array":{if(!Array.isArray($))return J();return $.map((Y,H)=>{let X=w(W.item,Y,`${G}[${H}]`,Z);return X.drop?void 0:X.value})}case"object":{if(typeof $!=="object"||$===null||Array.isArray($))return J();let Y=$,H={};for(let[X,V]of Object.entries(W.shape)){let B=w(V,Y[X],G?`${G}.${X}`:X,Z);if(!B.drop)H[X]=B.value}return H}case"union":{let Y;for(let H of W.members){let X=[],V=w(H,$,G,X);if(X.length===0)return V.drop?void 0:V.value;let B=JQ(H,$);if(!Y||B>Y.score)Y={errors:X,score:B}}Z.push(`${xQ(G)}no matching variant; closest: ${Y.errors.join("; ")}`);return}}}function N(Q){return c(Q)}function c(Q){let $={toJSONSchema:()=>u(Q),parse(G){let Z=[],W=w(Q,G,"",Z);if(Z.length>0)throw Error(Z.join("; "));return W.drop?void 0:W.value},safeParse(G){let Z=[],W=w(Q,G,"",Z);if(Z.length>0)return{ok:!1,errors:Z};return{ok:!0,value:W.drop?void 0:W.value}},describe:(G)=>c({...Q,description:G}),optional:()=>c({...Q,optional:!0}),nullable:()=>c({...Q,nullable:!0,optional:!1})};return kQ.set($,Q),$}function C(Q){return{node:Q,optional:!1,nullable:!1}}var R2={string:()=>N(C({kind:"string"})),number:()=>N(C({kind:"number"})),boolean:()=>N(C({kind:"boolean"})),literal:(Q)=>N(C({kind:"literal",value:Q})),enum:(Q)=>N(C({kind:"enum",values:Q})),object:(Q)=>N(C({kind:"object",shape:Object.fromEntries(Object.entries(Q).map(([$,G])=>[$,WQ(G)]))})),array:(Q)=>N(C({kind:"array",item:WQ(Q)})),union:(Q)=>N(C({kind:"union",members:Q.map(WQ)}))};import{createHmac as E2,randomBytes as IQ,timingSafeEqual as wQ}from"crypto";var YQ="agt1",bQ=86400000;function m(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 M(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(M).join(",")}]`;let $=Q;return`{${Object.keys($).filter((Z)=>$[Z]!==void 0).sort().map((Z)=>`${JSON.stringify(Z)}:${M($[Z])}`).join(",")}}`}function A2(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return E2("sha256",Q).update(A2($)).digest()}function hQ(Q,$,G){let Z=[YQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(G),M(Q.input)];if(Q.path&&Q.path.length>0)Z.push(M(Q.path));return Z}var fQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),x2=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function vQ(Q,$={}){let G=m($.secret),W=($.now??Date.now())+($.ttlMs??bQ),J=IQ(12).toString("base64url"),Y=p(G,hQ(Q,J,W)).toString("base64url");return[YQ,fQ(Q.runId),J,W.toString(36),Y].join(".")}function d(Q){return XQ(Q,YQ)}function XQ(Q,$){let G=Q.split(".");if(G.length!==5||G[0]!==$)return null;let Z=Number.parseInt(G[3],36);if(!Number.isFinite(Z))return null;try{return{runId:x2(G[1]),nonce:G[2],expiresAt:Z}}catch{return null}}function yQ(Q,$,G={}){let Z=m(G.secret),W=d(Q);if(!W)return{ok:!1,reason:"malformed"};let J=Buffer.from(Q.split(".")[4],"base64url"),Y=p(Z,hQ($,W.nonce,W.expiresAt));if(J.length!==Y.length||!wQ(J,Y))return{ok:!1,reason:"forged"};if((G.now??Date.now())>W.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:W.runId,nonce:W.nonce,expiresAt:W.expiresAt}}var i="agn1";function gQ(Q,$,G){return[i,Q.runId,M(Q.path),Q.nestedRunId,$,String(G),M([...Q.open].sort()),M(Q.input)]}function uQ(Q,$={}){let G=m($.secret),W=($.now??Date.now())+($.ttlMs??bQ),J=IQ(12).toString("base64url"),Y=p(G,gQ(Q,J,W)).toString("base64url");return[i,fQ(Q.runId),J,W.toString(36),Y].join(".")}function cQ(Q,$,G={}){let Z=m(G.secret),W=XQ(Q,i);if(!W)return{ok:!1,reason:"malformed"};let J=Buffer.from(Q.split(".")[4],"base64url"),Y=p(Z,gQ({...$,runId:W.runId},W.nonce,W.expiresAt));if(J.length!==Y.length||!wQ(J,Y))return{ok:!1,reason:"forged"};if((G.now??Date.now())>W.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:W.runId,nonce:W.nonce,expiresAt:W.expiresAt}}var A=new Map,mQ=1024;function k2(Q){for(let[$,G]of A)if(G<=Q)A.delete($);mQ=Math.max(1024,A.size*2)}function pQ(Q,$={}){return iQ(d(Q),$)}function dQ(Q,$={}){return iQ(XQ(Q,i),$)}function iQ(Q,$){if(!Q)return!1;let G=$.now??Date.now();if(A.size>=mQ)k2(G);let Z=A.get(Q.nonce);if(Z!==void 0&&Z>G)return!1;return A.set(Q.nonce,Q.expiresAt),!0}var HQ=new TextEncoder;function lQ(Q){return`id: ${Q.seq}
3
+ data: ${JSON.stringify(Q.event)}
4
+
5
+ `}var I2=5000,w2=`: keepalive
6
+
7
+ `;function VQ(Q,$=I2){let G=null,Z=!1,W=()=>{if(Z)return;if(G!==null)clearTimeout(G);G=setTimeout(()=>{if(G=null,Z)return;try{Q.enqueue(HQ.encode(w2))}catch{J();return}W()},$)},J=()=>{if(Z=!0,G!==null)clearTimeout(G);G=null};return W(),{touch:W,stop:J}}function b2(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function oQ(Q,$=200){let G=Q[Symbol.asyncIterator](),Z=-1,W,J=new ReadableStream({start(Y){W=VQ(Y)},async pull(Y){try{let H=await G.next();if(H.done){W.stop(),Y.close();return}Z=H.value.seq,Y.enqueue(HQ.encode(lQ(H.value))),W.touch()}catch(H){let X={type:"error",error:h2(H)};W.stop(),Y.enqueue(HQ.encode(lQ({seq:Z+1,event:X}))),Y.close()}},cancel(Y){W.stop(),G.return?.(Y)}});return new Response(J,{status:$,headers:b2()})}function h2(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class q extends Error{pending;path;nested;constructor(Q){super(`A nested agent run is waiting on the user for ${Q.pending.length} tool call(s).`);this.name="PendingEscalation",this.pending=Q.pending,this.path=Q.path,this.nested=Q.nested}}class h{name;description;inputSchema;outputSchema;requiresApproval;deferred;answeredBy;execute;constructor(Q){this.name=Q.name,this.description=Q.description,this.inputSchema=Q.inputSchema,this.outputSchema=Q.outputSchema,this.requiresApproval=Q.requiresApproval===!0,this.deferred=Q.deferred===!0,this.answeredBy=Q.answeredBy==="client"?"client":"server",this.execute=Q.execute??void 0}static create(Q){return new h(Q)}static ask(Q){return h.create({name:Q.name,description:Q.description,inputSchema:zQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var zQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=zQ.safeParse(Q);if($.ok===!1)throw Error($.errors.join(", "));return $.value},safeParse(Q){if(typeof Q!=="object"||Q===null||typeof Q.question!=="string")return{ok:!1,errors:["question: expected a string"]};return{ok:!0,value:{question:Q.question}}}};class s{name;description;tools;deferred;constructor(Q){this.name=Q.name,this.description=Q.description,this.tools=Q.tools,this.deferred=Q.deferred===!0}static create(Q){return new s(Q)}}class DQ{name;description;instructions;files;constructor(Q){this.name=Q.name,this.description=Q.description,this.instructions=Q.instructions,this.files=Q.files}static create(Q){return new DQ(Q)}}var b="skills",f2="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.",$2={type:"object",properties:{},required:[],additionalProperties:!1},v2=8,y2=3;class UQ{name;tools;skills;provider;output;instructions;maxSteps;maxDepth;reasoning;config;constructor(Q){this.name=Q.name,this.instructions=Q.instructions,this.provider=Q.provider,this.tools=Q.tools??[],this.skills=Q.skills??[],this.output=Q.output,this.maxSteps=Q.maxSteps??v2,this.maxDepth=Q.maxDepth??y2,this.reasoning=Q.reasoning;let{registry:$,providerTools:G}=g2(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:$,providerTools:G,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning}}static create(Q){return new UQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning};return new Z2($,Q)}}function nQ(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:!0,deferred:Q.deferred}}function g2(Q,$){let G=new Map,Z=[],W=(J)=>{if(G.has(J.tool.name))throw Error(`Two tools are named "${J.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);G.set(J.tool.name,J)};for(let J of Q){if(J instanceof s){if(J.name===b)throw Error(`"${b}" 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 H=[];for(let X of J.tools){let V={tool:X,namespace:J.name,deferred:J.deferred||X.deferred};W(V),H.push(nQ(V))}Z.push({name:J.name,description:J.description,tools:H});continue}let Y={tool:J,deferred:J.deferred};W(Y),Z.push(nQ(Y))}if($.length>0){let J=[];for(let Y of $){let H=u2(Y);W({tool:H,namespace:b,deferred:!1}),J.push({name:Y.name,description:Y.description,parameters:$2,strict:!0,deferred:!1})}Z.push({name:b,description:f2,tools:J})}return{registry:G,providerTools:Z}}function u2(Q){return h.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>$2,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let G=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let Z of Q.files??[])G.push(`--- ${Z} ---
8
+ ${await c2(Z)}`);return G.join(`
9
+
10
+ `)}})}async function c2(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}class P extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function l(Q,$){if($.aborted)return Promise.reject(new P);return new Promise((G,Z)=>{let W=()=>Z(new P);$.addEventListener("abort",W,{once:!0}),Q.then(G,Z).finally(()=>$.removeEventListener("abort",W))})}function o(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function BQ(Q,$){if(!$)return Q;let G={inputTokens:Q.inputTokens+($.inputTokens??0),outputTokens:Q.outputTokens+($.outputTokens??0),totalTokens:Q.totalTokens+($.totalTokens??0)};if($.reasoningTokens!==void 0||Q.reasoningTokens!==void 0)G.reasoningTokens=(Q.reasoningTokens??0)+($.reasoningTokens??0);if($.cachedInputTokens!==void 0||Q.cachedInputTokens!==void 0)G.cachedInputTokens=(Q.cachedInputTokens??0)+($.cachedInputTokens??0);return G}function m2(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function KQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],G=!1,Z=!1;for(let Y of Q){if(G){if(Z)Z=!1;else if(Y==="\\")Z=!0;else if(Y==='"')G=!1;continue}if(Y==='"')G=!0;else if(Y==="{")$.push("}");else if(Y==="[")$.push("]");else if(Y==="}"||Y==="]")$.pop()}let W=Q;if(G)W+='"';W=W.replace(/[,:]\s*$/,"");let J=$.reverse().join("");try{return JSON.parse(W+J)}catch{try{return JSON.parse(W.replace(/,?\s*"[^"]*"\s*$/,"")+J)}catch{return{}}}}function sQ(Q,$){let G=[...Q],Z=new Map(G.map((W,J)=>[W.id,J]));for(let W of $){let J=Z.get(W.id);if(J===void 0)Z.set(W.id,G.length),G.push(W);else G[J]=W}return G}function n(Q){let $=new Set;for(let Z of Q)for(let W of Z.content)if(W.type==="tool-result")$.add(W.toolCallId);let G=new Set;for(let Z of Q)for(let W of Z.content)if(W.type==="tool-call"&&!$.has(W.toolCallId))G.add(W.toolCallId);return G}function tQ(Q){for(let $=Q.length-1;$>=0;$--){let G=Q[$].content;for(let Z=G.length-1;Z>=0;Z--){let W=G[Z];if(W.type==="output"&&W.partial!==!0)return W.value}}return}function aQ(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function G2(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function p2(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${G2($)}`:null}function d2(Q,$,G){if(Q.agent!==$.name||Q.label!==G.label)return`was ${aQ(Q.agent,Q.label)} on the turn that escalated and is ${aQ($.name,G.label)} on the replay`;let Z=p2(G),W=Q.messages[0],J=W?`${W.role}:${G2(W)}`:null;if(Z!==null&&J!==null&&Z!==J)return`was started with ${JSON.stringify(J)} on the turn that escalated and with ${JSON.stringify(Z)} on the replay`;return null}function rQ(Q,$){let G=Q??[];if(G.length<$.length)return null;for(let Z=0;Z<$.length;Z++)if(G[Z]!==$[Z])return null;return G.slice($.length)}class Z2{runId;config;params;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;amended=new Map;unreported=new Set;usage=o();finishReason="stop";output;stopReason;settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;constructor(Q,$){this.config=Q,this.params=$,this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let G=$.nesting;if(this.depth=G?.depth??0,this.maxDepth=G?.maxDepth??Q.maxDepth,this.chain=G?.chain??[Q.name],this.signingRunId=G?.signingRunId??this.runId,this.pathPrefix=G?.signingPath??[],this.onPending=G?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});this.settled=this.execute()}emit(Q){if(this.ended)return;this.buffer.push({seq:++this.seq,event:Q}),this.wake()}wake(){let Q=[...this.waiters];this.waiters.clear();for(let $ of Q)$()}nextFrame(){return new Promise((Q)=>this.waiters.add(Q))}async*frames(Q=0){let $=Q>0?Q-1:0;for(;;){while($<this.buffer.length)yield this.buffer[$++];if(this.ended)return;await this.nextFrame()}}async*[Symbol.asyncIterator](){for await(let Q of this.frames())yield Q.event}toResponse(Q){let $=this.frames(Q?.from),G=new TextEncoder,Z=!1,W,J=new ReadableStream({start:async(Y)=>{W=VQ(Y);try{for await(let H of $){if(Z)break;Y.enqueue(G.encode(`id: ${H.seq}
11
+ data: ${JSON.stringify(H.event)}
12
+
13
+ `)),W.touch()}}catch{}W.stop();try{Y.close()}catch{}},cancel:()=>{Z=!0,W.stop()}});return new Response(J,{headers:{"Content-Type":"text/event-stream; charset=utf-8","Cache-Control":"no-cache, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}})}result(){return this.settled}stop(Q){if(this.ended||this.controller.signal.aborted)return;this.stopReason=Q?.reason,this.controller.abort()}async execute(){this.emit({type:"run-start",runId:this.runId,threadId:this.params.threadId});try{let Q=await this.ingestTurn();if(Q.length>0)this.finishReason="awaiting-input",this.emit({type:"awaiting-input",runId:this.runId,pending:Q});else await this.loop()}catch(Q){if(Q instanceof P||this.controller.signal.aborted)await this.finalizeAborted();else{let $=this.config.provider.normalizeError(Q);this.emit({type:"error",error:$}),await this.finalizeMessage("error"),this.finishReason="error"}}return this.emit({type:"usage",usage:this.usage}),this.emit({type:"run-end",runId:this.runId,finishReason:this.finishReason}),this.ended=!0,this.wake(),{runId:this.runId,messages:this.produced,finishReason:this.finishReason,usage:this.usage,output:this.output}}async loop(){let Q=Math.max(1,this.config.maxSteps);for(let $=1;$<=Q;$++){let G=this.startMessage(),Z=await this.runStep(G);if(Z.error){this.emit({type:"error",error:Z.error}),await this.finalizeMessage("error"),this.finishReason="error";return}let W=G.content.filter((Y)=>Y.type==="tool-call");if(W.length===0){this.finishReason=Z.reason,await this.finalizeMessage(Z.reason);return}let J=await this.runTools(G,W,$);if(J.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:J});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(Z.reason)}}startMessage(){let Q={id:`msg_${crypto.randomUUID()}`,role:"assistant",content:[],createdAt:new Date().toISOString()};return this.current=Q,this.history.push(Q),this.produced.push(Q),this.emit({type:"message-start",messageId:Q.id,role:"assistant"}),Q}async finalizeMessage(Q){let $=this.current;if(!$)return;this.current=null,$.finishReason=Q;for(let G of $.content)if(G.type==="text"||G.type==="reasoning"){if(typeof G.text==="string")G.text=i2(G.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q}),await this.report($)}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,G=this.config.provider,Z={reason:"stop"},W=new Map,J="",H=G.stream({messages:this.history.filter((X)=>X!==Q),systemPrompt:await this.systemPrompt(),tools:this.config.providerTools.length>0?this.config.providerTools:void 0,output:this.config.output?{name:"output",schema:this.config.output.toJSONSchema()}:void 0,reasoning:this.config.reasoning,signal:$})[Symbol.asyncIterator]();for(;;){let X=await l(Promise.resolve(H.next()),$);if(X.done)break;let V=X.value;switch(V.type){case"text-delta":{l2(Q,"text",V.delta),this.emit({type:"text-delta",messageId:Q.id,delta:V.delta});break}case"reasoning-delta":{o2(Q,V.id,V.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:V.delta,id:V.id});break}case"output-delta":{J+=V.delta,this.emit({type:"output-delta",messageId:Q.id,delta:V.delta,snapshot:KQ(J)});break}case"tool-search":{this.emit({type:"tool-search",loaded:V.loaded});break}case"tool-call-delta":{let B=W.get(V.toolCallId)??{name:V.name,args:""};B.args+=V.argsDelta,B.name=V.name||B.name,W.set(V.toolCallId,B),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:V.toolCallId,name:B.name,input:KQ(B.args),partial:!0}});break}case"tool-call":{W.delete(V.toolCallId);let B={type:"tool-call",toolCallId:V.toolCallId,name:V.name,input:Q2(V.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B});break}case"finish":{if(this.usage=BQ(this.usage,V.usage),!Z.error)Z={reason:V.reason};break}case"error":{Z={reason:"error",error:V.error};break}}}for(let[X,V]of W){let B={type:"tool-call",toolCallId:X,name:V.name,input:Q2(V.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B})}if(this.config.output&&J&&!Z.error){let X=this.config.output.safeParse(KQ(J));if(X.ok===!0)this.output=X.value,Q.content.push({type:"output",value:X.value});else this.emit({type:"error",error:{code:"unknown",message:`The model's structured answer did not match the output schema: ${X.errors.join(", ")}`,retryable:!0}})}return Z}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
14
+
15
+ `):void 0}async runTools(Q,$,G){let Z=[],W=[];for(let J of $){let Y=this.config.registry.get(String(J.name));if(!Y){this.addResult(Q,{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(J.name)}".`,toolCallId:J.toolCallId,retryable:!0}});continue}let H=Y.tool.inputSchema.safeParse(J.input);if(H.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(J.name)}": ${H.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}});continue}J.input=H.value;let X=eQ(Y.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(J));continue}Z.push({toolCallId:J.toolCallId,name:J.name,input:H.value,kind:X,signature:vQ(this.claimsFor(J.toolCallId,String(J.name),X,H.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}W.push(this.executeTool(Y,Q.id,J,H.value,G).then((V)=>this.addResult(Q,V)).catch((V)=>{if(V instanceof q){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(J));return}Z.push(...V.pending);return}}))}return await l(Promise.all(W).then(()=>{return}),this.controller.signal),Z}claimsFor(Q,$,G,Z){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:G,input:Z,path:this.pathPrefix.length>0?[...this.pathPrefix]:void 0}}deniedByPolicy(Q){return{type:"tool-result",toolCallId:Q.toolCallId,name:Q.name,status:"denied",cause:"refused",reason:`"${String(Q.name)}" needs the user, and this run was started with onPending: "deny". Answer from what you already have.`}}async executeTool(Q,$,G,Z,W,J){let Y={req:this.params.req,runId:this.runId,threadId:this.params.threadId,toolCallId:G.toolCallId,signal:this.controller.signal,step:W,depth:this.depth,resumed:J!==void 0,runAgent:this.nestedRunner($,G,J)};try{let H=Q.tool.execute(Z,Y),X;if(m2(H)){let V=await H.next();while(!V.done)this.emit({type:"tool-progress",toolCallId:G.toolCallId,data:V.value}),V=await H.next();X=V.value}else X=await H;return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:X}}catch(H){if(H instanceof P||this.controller.signal.aborted)throw new P;if(H instanceof q)throw H;return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"tool_error",message:H instanceof Error?H.message:String(H),toolCallId:G.toolCallId,retryable:!0}}}}nestedRunner(Q,$,G){let Z=$.nested?.length??0,W=0,J=()=>$.nested??($.nested=[]);return async(Y,H={})=>{let X=W++,V=J(),B=X<Z?V[X]:void 0;if(B){let K=d2(B,Y,H);if(K)throw Error(`Nested run ${X} of "${String($.name)}" ${K}. `+"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(B.finishReason!=="awaiting-input")return{runId:B.runId,agent:B.agent,messages:B.messages,finishReason:B.finishReason??"stop",usage:B.usage??o(),output:tQ(B.messages),nested:B}}return this.runNested(Q,$,Y,H,X,V,B,G?.answers??[])}}async runNested(Q,$,G,Z,W,J,Y,H){let X=[...this.chain,G.name];if(this.chain.includes(G.name))throw Error(`"${G.name}" is already running further up this chain: ${X.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let V=this.depth+1;if(V>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${V}: ${X.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let B=Z.label,K=[...this.pathPrefix,$.toolCallId],z=this.onPending==="deny"?"deny":Z.onPending??"escalate",j=Y!==void 0,F=j?n(Y.messages):new Set,D=j?H.filter((U)=>{let E=rQ(U.path,K);if(E===null)return!1;return F.has(E.length>0?E[0]:U.toolCallId)}):[],O=G.stream({messages:j?Y.messages:Z.messages??[],turn:j?{toolResults:D}:Z.prompt?{text:Z.prompt}:void 0,req:this.params.req,signal:this.controller.signal,threadId:this.params.threadId,instructions:Z.instructions,runId:j?Y.runId:void 0,nesting:{depth:V,maxDepth:this.maxDepth,chain:X,signingRunId:this.signingRunId,signingPath:K,onPending:z}}),_=[],y=(async()=>{for await(let U of O){if(U.type==="awaiting-input")_=U.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:O.runId,agent:G.name,label:B,event:U})}})(),I=(async()=>{let U=await O.result();await y;let E=j?sQ(Y.messages,U.messages):sQ(Z.messages??[],U.messages),AQ={runId:O.runId,agent:G.name,label:B,messages:E,finishReason:U.finishReason,usage:j?BQ(Y.usage??o(),U.usage):U.usage,...U.finishReason==="awaiting-input"?{signature:uQ({runId:this.signingRunId,path:K,nestedRunId:O.runId,open:[...n(E)],input:$.input})}:{}};return J[W]=AQ,this.usage=BQ(this.usage,U.usage),{result:U,record:AQ}})(),EQ=I.then(()=>{return},()=>{return});this.nestedSettling.add(EQ);let g,L;try{({result:g,record:L}=await I)}finally{this.nestedSettling.delete(EQ)}if(this.controller.signal.aborted)throw new P;if(g.finishReason==="awaiting-input"){if(_.length===0)throw Error(`"${G.name}" ended awaiting input but asked nothing, so there is no question to escalate.`);throw this.emit({type:"tool-call",messageId:Q,part:$,resent:!0}),new q({pending:_,path:K,nested:L})}return{runId:L.runId,agent:G.name,messages:L.messages,finishReason:g.finishReason,usage:L.usage??o(),output:g.output??tQ(L.messages),nested:L}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),G=[];if($.length>0){let Z=new Set,W=new Set,J=new Map;for(let Y of Q?.toolResults??[]){let H=`${(Y.path??[]).join("/")}#${Y.toolCallId}`;if(W.has(H))continue;W.add(H);let X=(z)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:z,toolCallId:Y.toolCallId,retryable:!1}}),V=rQ(Y.path,this.pathPrefix);if(V===null){X(`The answer for "${Y.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(V.length>0){let z=V[0],j=$.find((O)=>O.call.toolCallId===z);if(!j){X(`No pending tool call with id "${z}" to deliver a nested answer to.`);continue}let F=this.parkedBelow(j.call,V,Y.toolCallId);if(F.ok===!1){let O=`The answer for "${Y.toolCallId}" is addressed under "${z}", which`;X(F.reason==="unparked"?`${O} has no sub-agent run waiting on that question.`:F.reason==="expired"?`${O} parked a sub-agent run that has since expired. Ask again.`:`${O} carries a record of a parked sub-agent run the server did not sign.`);continue}let D=J.get(z);if(!D){if(!dQ(F.signature)){X(`The answer for "${Y.toolCallId}" is addressed under "${z}", which has already been re-entered on that record. Ask again.`);continue}D=[],J.set(z,D),Z.add(z)}D.push(Y);continue}let B=$.find((z)=>z.call.toolCallId===Y.toolCallId);if(!B){X(`No pending tool call with id "${Y.toolCallId}".`);continue}let K=await this.resolveAnswer(B,Y,G);if(K===null)continue;if(Z.add(Y.toolCallId),K!=="open")this.attachToHistory(B,K)}for(let[Y,H]of J){let X=$.find((B)=>B.call.toolCallId===Y),V=await this.reenter(X,H,G);if(V)this.attachToHistory(X,V)}for(let Y of $){if(Z.has(Y.call.toolCallId))continue;this.attachToHistory(Y,{type:"tool-result",toolCallId:Y.call.toolCallId,name:Y.call.name,status:"denied",cause:"refused"})}await this.reportAmended()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let Z={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((W)=>({type:"file",fileId:W.fileId,name:W.name,mimeType:W.mimeType}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(Z),this.produced.push(Z),await this.report(Z)}return G}parkedBelow(Q,$,G){let Z=$.length>1?$[1]:G,W=[...this.pathPrefix,Q.toolCallId],J=(Q.nested??[]).find((H)=>H.finishReason==="awaiting-input"&&n(H.messages).has(Z));if(!J)return{ok:!1,reason:"unparked"};if(typeof J.signature!=="string")return{ok:!1,reason:"unsigned"};let Y=cQ(J.signature,{path:W,nestedRunId:J.runId,open:[...n(J.messages)],input:Q.input});if(Y.ok===!1)return{ok:!1,reason:Y.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:J.signature}}async reenter(Q,$,G){let Z=String(Q.call.name),W=this.config.registry.get(Z);if(!W||!W.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${Z}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let J=W.tool.inputSchema.safeParse(Q.call.input);if(J.ok===!1)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${Z}": ${J.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let Y=this.amendCall(Q);Y.input=J.value;try{return await l(this.executeTool(W,Q.message.id,Y,J.value,0,{answers:$}),this.controller.signal)}catch(H){if(H instanceof q)return G.push(...H.pending),null;throw H}}amendCall(Q){let $=this.amend(Q.message),G=$.content.indexOf(Q.call),Z={...Q.call,nested:(Q.call.nested??[]).map((W)=>({...W}))};if(G>=0)$.content[G]=Z;return this.unreported.add($),Z}openCalls(){let Q=new Set;for(let G of this.history)for(let Z of G.content)if(Z.type==="tool-result")Q.add(Z.toolCallId);let $=[];for(let G of this.history)for(let Z of G.content)if(Z.type==="tool-call"&&!Q.has(Z.toolCallId))$.push({message:G,call:Z});return $}async resolveAnswer(Q,$,G){let Z=Q.call,W=String(Z.name),J=this.config.registry.get(W),Y=(B)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:B,toolCallId:Z.toolCallId,retryable:!1}}),null};if(!J)return Y(`The tool "${W}" no longer exists, so its answer cannot be checked.`);let H=eQ(J.tool);if(!H)return Y(`"${W}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return Y(`The answer for "${W}" carried no signature.`);let X=d($.signature);if(!X)return Y(`The signature for "${W}" is malformed.`);let V=yQ($.signature,{...this.claimsFor(Z.toolCallId,W,H,Z.input),runId:X.runId});if(V.ok===!1)return Y(V.reason==="expired"?`The approval for "${W}" has expired. Ask again.`:`The answer for "${W}" does not match the call the server made.`);if(!pQ($.signature))return Y(`The answer for "${W}" has already been used. Ask again.`);if("approve"in $){if(H!=="approval")return Y(`"${W}" is answered by the client, not approved.`);if($.approve===!0){let B=this.amendCall(Q);try{return await l(this.executeTool(J,Q.message.id,B,B.input,0),this.controller.signal)}catch(K){if(K instanceof q)return G.push(...K.pending),"open";throw K}}return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(H==="approval")return Y(`"${W}" is approved, not answered: the server produces its result.`);let B=J.tool.outputSchema,K=B?B.safeParse($.output):{ok:!0,value:$.output};if(K.ok===!1)return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${W}" did not match its output schema: ${K.errors.join(", ")}`,toolCallId:Z.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:K.value}}return Y(`The answer for "${W}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let G=this.amend(Q.message);G.content.push($),this.unreported.add(G),this.emit({type:"tool-result",messageId:G.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let G={...Q,content:[...Q.content]},Z=this.history.indexOf(Q);if(Z>=0)this.history[Z]=G;return this.produced.push(G),this.amended.set(Q.id,G),G}async reportAmended(){let Q=[...this.unreported];this.unreported.clear();for(let $ of Q)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.reportAmended();let Q=this.current;if(Q){let $=new Set(Q.content.filter((G)=>G.type==="tool-result").map((G)=>G.toolCallId));for(let G of[...Q.content]){if(G.type!=="tool-call"||$.has(G.toolCallId))continue;delete G.partial,this.addResult(Q,{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function eQ(Q){if(Q.answeredBy==="client")return Q.inputSchema===zQ?"question":"client";return Q.requiresApproval?"approval":null}function Q2(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function i2(Q){if(Q.length>0)Q[0];return Q}function l2(Q,$,G){let Z=Q.content[Q.content.length-1];if(Z&&Z.type===$){Z.text=(Z.text??"")+G;return}Q.content.push($==="text"?{type:"text",text:G}:{type:"reasoning",text:G})}function o2(Q,$,G){let Z=Q.content[Q.content.length-1];if(Z&&Z.type==="reasoning"&&Z.id===$){Z.text=(Z.text??"")+G;return}Q.content.push($?{type:"reasoning",id:$,text:G}:{type:"reasoning",text:G})}class t extends Error{status;body;requestId;constructor(Q,$,G){super(`Provider request failed with status ${Q}: ${n2($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=G}}class a extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function n2(Q){let $=W2(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function W2(Q){if(!Q||typeof Q!=="object")return null;let $=Q,Z=$.error&&typeof $.error==="object"?$.error:Q;if(typeof Z.message!=="string"&&typeof Z.code!=="string"&&typeof Z.type!=="string")return null;let W=Z.innererror?.code??Z.code;return{message:Z.message,type:Z.type,code:W,param:Z.param}}function T(Q){if(Q instanceof a)return{code:"provider_error",message:Q.message,retryable:!0};if(r2(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof t)return s2(Q.status,W2(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 s2(Q,$,G){let Z=$?.message??G,W=($?.code??"").toLowerCase(),J=($?.type??"").toLowerCase(),Y=`${W} ${J} ${Z}`.toLowerCase();if(Q===429){let H=W==="insufficient_quota"||Y.includes("quota");return{code:"rate_limited",message:Z,retryable:!H}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:Z,retryable:!0};if(t2(Y))return{code:"context_length_exceeded",message:Z,retryable:!1};if(a2(Y))return{code:"content_filtered",message:Z,retryable:!1};if($?.param?.startsWith("tools")||Y.includes("invalid schema for function"))return{code:"invalid_tool_input",message:Z,retryable:!1};return{code:"provider_error",message:Z,retryable:!1}}function t2(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function a2(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function r2(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var e2=500,Y2=20000;function Q5(Q,$){if(!Q)return;let G=Q.trim();if(/^\d+(\.\d+)?$/.test(G))return Math.max(0,Number(G)*1000);let Z=Date.parse(G);if(Number.isNaN(Z))return;return Math.max(0,Z-$)}function J2(Q,$){let G=Math.min(Y2,e2*2**Q);return Math.round(G*(0.5+$()*0.5))}function $5(Q){return Q===429||Q===408||Q===409||Q>=500}function G5(Q,$){return $5(Q)&&T($).retryable}function X2(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function Z5(Q,$){return new Promise((G,Z)=>{let W=setTimeout(G,Q);$?.addEventListener("abort",()=>{clearTimeout(W),Z(X2($))},{once:!0})})}async function jQ(Q,$,G){let Z=G.fetchImpl??((B,K)=>fetch(B,K)),W=G.sleep??Z5,J=G.random??Math.random,Y=G.now??Date.now,H=Math.max(0,G.maxRetries),X=async(B)=>{let K=G.signal;if(!K)return await W(B);K.throwIfAborted();let z;try{await Promise.race([W(B,K),new Promise((j,F)=>{z=()=>F(X2(K)),K.addEventListener("abort",z,{once:!0})})])}finally{if(z)K.removeEventListener("abort",z)}},V;for(let B=0;B<=H;B++){G.signal?.throwIfAborted();let K=new AbortController,z=()=>K.abort(G.signal?.reason);G.signal?.addEventListener("abort",z,{once:!0});let j=!1,F=G.timeoutMs>0?setTimeout(()=>{j=!0,K.abort()},G.timeoutMs):void 0,D;try{D=await Z(Q,{...$,signal:K.signal})}catch(I){if(F!==void 0)clearTimeout(F);if(G.signal?.removeEventListener("abort",z),G.signal?.aborted)throw I;if(V=j?new a(G.timeoutMs):I,B===H)throw V;await X(J2(B,J));continue}if(F!==void 0)clearTimeout(F);if(D.ok)return D;G.signal?.removeEventListener("abort",z);let O=await W5(D),_=new t(D.status,O,D.headers.get("x-request-id")??void 0);if(B===H||!G5(D.status,_))throw _;let y=Q5(D.headers.get("retry-after"),Y());await X(y===void 0?J2(B,J):Math.min(y,Y2)),V=_}throw V??Error("Provider request failed with no response.")}async function W5(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}async function*J5(Q){let $="",G="",Z=[],W,J=()=>{if(Z.length===0&&!G)return null;let X={event:G,data:Z.join(`
16
+ `),id:W};return G="",Z=[],W=void 0,X.data?X:null},Y=(X)=>{let V=X.endsWith("\r")?X.slice(0,-1):X;if(V==="")return J();if(V.startsWith(":"))return null;let B=V.indexOf(":"),K=B===-1?V:V.slice(0,B),z=B===-1?"":V.slice(B+1);if(z.startsWith(" "))z=z.slice(1);if(K==="event")G=z;else if(K==="data")Z.push(z);else if(K==="id")W=z;return null};for await(let X of Q){$+=X;let V=$.indexOf(`
17
+ `);while(V!==-1){let B=$.slice(0,V);$=$.slice(V+1);let K=Y(B);if(K)yield K;V=$.indexOf(`
18
+ `)}}if($.length>0){let X=Y($);if(X)yield X}let H=J();if(H)yield H}async function*H2(Q,$={}){let G=new Map,Z=new Set,W=!1;for await(let J of J5(Q)){if(J.data==="[DONE]")break;let Y;try{Y=JSON.parse(J.data)}catch{continue}switch(typeof Y.type==="string"?Y.type:J.event){case"response.output_text.delta":{let X=String(Y.delta??"");if(!X)break;yield $.structuredOutput?{type:"output-delta",delta:X}:{type:"text-delta",delta:X};break}case"response.reasoning_summary_text.delta":case"response.reasoning_text.delta":{let X=String(Y.delta??"");if(!X)break;yield{type:"reasoning-delta",delta:X,id:Y.item_id};break}case"response.output_item.added":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let V=String(X.id??Y.item_id??X.call_id??"");G.set(V,{callId:String(X.call_id??V),name:String(X.name??""),namespace:typeof X.namespace==="string"&&X.namespace?X.namespace:void 0,done:!1})}break}case"response.function_call_arguments.delta":{let X=G.get(String(Y.item_id??""));if(!X)break;let V=String(Y.delta??"");if(!V)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:V,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(Y.item_id??""),V=G.get(X);if(!V)break;V.done=!0,yield{type:"tool-call",toolCallId:V.callId,name:V.name,args:String(Y.arguments??""),...V.namespace?{namespace:V.namespace}:{}};break}case"response.output_item.done":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let V=String(X.id??Y.item_id??X.call_id??""),B=G.get(V);if(B?.done)break;let K=(typeof X.namespace==="string"?X.namespace:"")||B?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??V),name:String(X.name??B?.name??""),args:String(X.arguments??""),...K?{namespace:K}:{}},B)B.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let V=Y5(X);if(V.loaded.length===0&&V.namespaces.length===0)break;let B=String(X.tool_search_call_id??X.id??"");if(Z.has(B))break;Z.add(B),yield{type:"tool-search",...V}}break}case"response.refusal.done":{yield{type:"error",error:{code:"content_filtered",message:String(Y.refusal??"The model refused to answer."),retryable:!1}};break}case"response.completed":{W=!0,yield{type:"finish",reason:"stop",usage:FQ(Y.response?.usage)};break}case"response.incomplete":{W=!0;let X=FQ(Y.response?.usage),V=Y.response?.incomplete_details?.reason;if(V==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:X5(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:V==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{W=!0;let X=Y.response?.error??Y.error??Y;yield{type:"error",error:H5(X)},yield{type:"finish",reason:"error",usage:FQ(Y.response?.usage)};break}}if(W)return}if(!W)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:x()}}function Y5(Q){let $=[],G=[];return V2(Q.results??Q.tools??Q.loaded??Q.output,$,G,0),{loaded:OQ($),namespaces:OQ(G)}}function V2(Q,$,G,Z){if(!Array.isArray(Q)||Z>4)return;for(let W of Q){if(typeof W==="string"){$.push(W);continue}if(!W||typeof W!=="object")continue;let J=W,Y=typeof J.name==="string"?J.name:typeof J.tool_name==="string"?J.tool_name:"",H=J.tools??J.functions;if(Array.isArray(H)){if(Y)G.push(Y);V2(H,$,G,Z+1);continue}if(Y)$.push(Y)}}function OQ(Q){return Q.filter(($,G)=>Q.indexOf($)===G)}function X5(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let G=[];for(let Z of Q){if(!Z||typeof Z!=="object")continue;let W=Z,J=W.content_filter_results;if(!J||typeof J!=="object")continue;for(let[Y,H]of Object.entries(J))if(H&&typeof H==="object"&&H.filtered===!0)G.push(`${Y} (${String(W.source_type??"unknown")})`)}return G.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${OQ(G).join(", ")}.`}function H5(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",G=String(Q?.code??"").toLowerCase();if(G==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(G==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(G.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function x(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function FQ(Q){if(!Q)return x();let $=Number(Q.input_tokens??0),G=Number(Q.output_tokens??0),Z={inputTokens:$,outputTokens:G,totalTokens:Number(Q.total_tokens??$+G)},W=Q.output_tokens_details?.reasoning_tokens;if(typeof W==="number")Z.reasoningTokens=W;let J=Q.input_tokens_details?.cached_tokens;if(typeof J==="number")Z.cachedInputTokens=J;return Z}async function*B2(Q){if(!Q)return;let $=Q.getReader(),G=new TextDecoder;try{while(!0){let{done:W,value:J}=await $.read();if(W)break;if(J)yield G.decode(J,{stream:!0})}let Z=G.decode();if(Z)yield Z}finally{$.releaseLock()}}async function*NQ(Q,$,G){let Z;try{Z=await jQ(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:G.signal,fetchImpl:Q.fetchImpl})}catch(W){let J=T(W);if(J.code!=="aborted")yield{type:"error",error:J};yield{type:"finish",reason:J.code==="aborted"?"aborted":"error",usage:x()};return}try{yield*H2(B2(Z.body),{structuredOutput:G.structuredOutput})}catch(W){let J=T(W);if(J.code==="aborted"){yield{type:"finish",reason:"aborted",usage:x()};return}yield{type:"error",error:J},yield{type:"finish",reason:"error",usage:x()}}}async function CQ(Q,$){let G=new FormData;G.set("purpose","user_data"),G.set("file",$);let W=await(await jQ(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:G},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!W?.id)throw Error("The provider accepted the upload but returned no file id.");return W.id}function _Q(Q){let $=V5(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let G=B5($);if(G?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:G.major>1,toolSearch:K2(G)};if(G?.kind==="gpt")return{reasoning:G.major>=5,structuredOutput:G.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:G.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:K2(G)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function K2(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function V5(Q){return Q.trim().toLowerCase()}function B5(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let G=/^o(\d+)(?:[-.]|$)/.exec(Q);if(G?.[1])return{kind:"o",major:Number(G[1]),minor:0};return null}function LQ(Q,$){let{capabilities:G}=$,Z={model:$.model,input:K5(Q.messages,G),stream:!0};if(Q.systemPrompt)Z.instructions=Q.systemPrompt;let W=F5(Q.tools,G);if(W.length>0){if(Z.tools=W,!G.parallelToolCalls)Z.parallel_tool_calls=!1}if(Q.output)Z.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:!0}};if(Q.reasoning&&G.reasoning)Z.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")Z.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")Z.max_output_tokens=Q.maxOutputTokens;return Z}function K5(Q,$){let G=[];for(let Z of Q){let W=Z.role,J=[],Y=()=>{if(J.length===0)return;G.push({type:"message",role:W,content:J}),J=[]};for(let H of Z.content??[])switch(H.type){case"text":{if(!H.text)break;J.push(z2(W,H.text));break}case"output":{if(H.partial)break;J.push(z2(W,JSON.stringify(H.value)));break}case"file":{if(!$.fileInput||W==="assistant")break;J.push({type:"input_file",file_id:H.fileId});break}case"reasoning":{Y();let X=U5(H);if(X)G.push(X);break}case"tool-call":{if(H.partial)break;Y(),G.push({type:"function_call",call_id:H.toolCallId,name:String(H.name),arguments:JSON.stringify(H.input??{})});break}case"tool-result":{Y(),G.push({type:"function_call_output",call_id:H.toolCallId,output:j5(H)});break}}Y()}return D5(G)}var z5="No result was recorded for this tool call. Assume it did not complete.";function D5(Q){let $=new Set,G=new Set,Z=[];for(let J of Q){if(J.type==="function_call"){let Y=String(J.call_id);if($.has(Y))continue;$.add(Y)}else if(J.type==="function_call_output"){let Y=String(J.call_id);if(!$.has(Y)||G.has(Y))continue;G.add(Y)}Z.push(J)}if(G.size===$.size)return Z;let W=[];for(let J of Z){if(W.push(J),J.type!=="function_call")continue;let Y=String(J.call_id);if(G.has(Y))continue;G.add(Y),W.push({type:"function_call_output",call_id:Y,output:z5})}return W}function z2(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function U5(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function j5(Q){if(Q.status==="ok")return typeof Q.output==="string"?Q.output:JSON.stringify(Q.output??null);if(Q.status==="denied"){let $=Q.reason?` Reason given: ${Q.reason}`:"";if(Q.cause==="stopped")return`The run was stopped before this tool call could complete, so it did not run.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function D2(Q){return Array.isArray(Q.tools)}function F5(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let W=[];for(let J of Q)if(D2(J))for(let Y of J.tools)W.push(r(Y,!1));else W.push(r(J,!1));return W}let G=[],Z=!1;for(let W of Q)if(D2(W)){let J=W.tools.map((Y)=>{if(Y.deferred)Z=!0;return r(Y,!0)});G.push({type:"namespace",name:W.name,description:W.description,tools:J})}else{if(W.deferred)Z=!0;G.push(r(W,!0))}if(Z)G.push({type:"tool_search"});return G}function r(Q,$){let G={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)G.defer_loading=!0;return G}var j2=120000,F2=2;function S(Q){return typeof process>"u"?void 0:process.env?.[Q]}class e{static models(){return[]}normalizeError(Q){return T(Q)}}var O2=["gpt-5.5","gpt-5.4","gpt-5.4-mini","gpt-5.4-nano","gpt-5.2","gpt-5.1","gpt-5","gpt-5-mini","gpt-5-nano","gpt-4.1","gpt-4.1-mini","gpt-4.1-nano","gpt-4o","gpt-4o-mini","o4-mini","o3","o3-mini"];class MQ extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=_Q(Q),this.config=$}static model(Q,$){return new MQ(Q,$)}static models(){return O2}stream(Q){let $=LQ(Q,{model:this.model,capabilities:this.capabilities});return NQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return CQ(this.endpoint(),Q)}baseURL(){return(this.config.baseURL??S("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,"")}endpoint(){let Q=this.baseURL(),$=this.config;return{responsesUrl:`${Q}/responses`,filesUrl:`${Q}/files`,headers:async()=>{let G=$.apiKey??S("OPENAI_API_KEY");return{...G?{authorization:`Bearer ${G}`}:{},...$.headers}},timeoutMs:$.timeoutMs??j2,maxRetries:$.maxRetries??F2}}}var O5="preview";function U2(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function N5(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}class qQ extends e{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=_Q(Q),this.config=$}static model(Q,$){return new qQ(Q,$)}static models(){return O2}stream(Q){let $=LQ(Q,{model:this.deployment(),capabilities:this.capabilities});return NQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return CQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}base(){let Q=this.config,$=Q.baseURL??Q.endpoint??S("AZURE_OPENAI_ENDPOINT");if($)return U2($);let G=Q.resourceName??S("AZURE_OPENAI_RESOURCE_NAME")??S("AZURE_RESOURCE_NAME");return G?U2(`https://${G.trim()}.cognitiveservices.azure.com`):""}endpoint(){let Q=this.config,$=this.base(),G=Q.apiVersion??S("AZURE_OPENAI_API_VERSION")??O5,Z=N5(G),W=`?api-version=${encodeURIComponent(G)}`;return{responsesUrl:`${$}${Z}/responses${W}`,filesUrl:`${$}${Z}/files${W}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??S("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??j2,maxRetries:Q.maxRetries??F2}}}class k extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,G){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${G}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=G}}class f extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class QQ{ttlMs;maxFrames;runs=new Map;byThread=new Map;byClientRun=new Map;constructor(Q={}){this.ttlMs=Q.ttlMs??60000,this.maxFrames=Q.maxFrames??4096}register(Q,$={}){let G={run:Q,threadId:$.threadId,clientRunId:$.clientRunId,frames:[],lastSeq:-1,lostBefore:0,ended:!1,evictAt:null,wake:new Set,version:0};if(this.runs.set(Q.runId,G),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);this.pump(G,$)}findByClientRunId(Q){let $=this.byClientRun.get(Q);return $&&this.runs.has($)?$:null}async find(Q){let $=this.byThread.get(Q.threadId);if(!$)return null;let G=this.runs.get($);if(!G)return null;return{runId:$,seq:G.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let G=this.runs.get(Q);if(!G)throw new f(Q);if($!==void 0&&$<G.lostBefore)throw new k(Q,$,G.lostBefore);let Z=G.frames[0]?.seq;return this.drain(G,Q,$??Z??G.lastSeq+1)}clear(){for(let Q of this.runs.values()){if(Q.evictAt)clearTimeout(Q.evictAt);Q.ended=!0,this.notify(Q)}this.runs.clear(),this.byThread.clear(),this.byClientRun.clear()}get size(){return this.runs.size}async pump(Q,$){let G=Promise.resolve();try{for await(let Z of Q.run.frames()){if(Q.frames.push(Z),Q.lastSeq=Z.seq,Q.frames.length>this.maxFrames){let J=Q.frames.shift();if(J)Q.lostBefore=J.seq+1}this.notify(Q);let W=$.onEvent;if(W)G=G.then(()=>W(Z.event)).catch((J)=>{$.onInternalError?.(J)})}}catch(Z){$.onInternalError?.(Z)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await G}}async*drain(Q,$,G){let Z=G;while(!0){let W=Q.version;for(;;){if(Z<Q.lostBefore)throw new k($,Z,Q.lostBefore);let J=Q.frames,Y=J[0]?.seq;if(Y===void 0)break;let H=Math.max(0,Z-Y);if(H>=J.length)break;let X=J[H];yield X,Z=X.seq+1}if(Q.ended&&Z>Q.lastSeq)return;await this.wait(Q,W)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((G)=>Q.wake.add(G))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let G of $)G()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let G=Q.run.runId;if(this.runs.delete(G),Q.threadId&&this.byThread.get(Q.threadId)===G)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===G)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var PQ=new QQ;class $Q{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 G=this.threads.get(Q);if(!G){if(!this.clientOwnedIds)throw Error(`Thread ${Q} does not exist here, or has expired.`);G={messages:[],touchedAt:Date.now()},this.threads.set(Q,G)}for(let Z of $){let W=G.messages.findIndex((J)=>J.id===Z.id);if(W===-1)G.messages.push(Z);else G.messages[W]=Z}G.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[$,G]of this.threads)if(Q-G.touchedAt>this.ttlMs)this.threads.delete($)}}var TQ=new $Q;var C5=C2,GQ=new Map,N2=new WeakMap,ZQ=new Map;class _2 extends C5{static kind="agent-controller";store=TQ;liveRuns=PQ;instructions(Q){}async stream(Q=new v){let $=await SQ(Q);if($.error)return RQ($);let G=$.body,Z=typeof G.threadId==="string"?G.threadId:void 0,W=L5(G),J=typeof G.clientRunId==="string"?G.clientRunId:void 0,Y=J?{cancelled:!1}:null;if(Y)ZQ.set(J,Y);let H=async()=>{let X;if(Z){let z=await this.store.loadThread(Z);if(!z)return R(404,{code:"thread_not_found",message:`Thread ${Z} does not exist here, or has expired.`});X=z}else X=Array.isArray(G.messages)?G.messages:[];let V=await this.instructions(Q)||void 0;if(Y?.cancelled)return R(409,{code:"stopped",message:"The turn was stopped before it started."});let B=this.agent.stream({messages:X,turn:W,req:Q,threadId:Z,instructions:V}),K={req:Q,runId:B.runId,threadId:Z};return this.liveRuns.register(B,{threadId:Z,clientRunId:J,onEvent:(z)=>this.dispatchEvent(z,K),onInternalError:(z)=>this.reportHookFailure(z)}),N2.set(B,this.persistRun(B,K)),B.toResponse()};try{return Z?await this.withThread(Z,H):await H()}finally{if(Y&&ZQ.get(J)===Y)ZQ.delete(J)}}async withThread(Q,$){let G=GQ.get(Q)??Promise.resolve(),Z,W=new Promise((Y)=>{Z=Y}),J=G.then(()=>W);GQ.set(Q,J),await G;try{let Y=await this.liveRuns.find({threadId:Q}),H=Y?this.liveRuns.get(Y.runId):null;if(H)H.stop({reason:"superseded by a later turn on this thread"}),await N2.get(H);return await $()}finally{if(Z(),GQ.get(Q)===J)GQ.delete(Q)}}async attach(Q=new v){let $=await SQ(Q);if($.error)return RQ($);let G=$.body,Z=typeof G.threadId==="string"?G.threadId:q5(Q,"threadId");if(!Z)return R(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});let W=await this.liveRuns.find({threadId:Z});if(!W)return R(404,{code:"no_live_run",message:`No run in progress for thread ${Z} in this process.`});let J=typeof G.runId==="string"?G.runId:void 0,Y=J&&J!==W.runId?void 0:M5(Q,G);try{return oQ(this.liveRuns.replay(W.runId,Y))}catch(H){if(H instanceof k)return R(410,{code:H.code,message:H.message,oldestSeq:H.oldest});if(H instanceof f)return R(404,{code:H.code,message:H.message});throw H}}async stop(Q=new v){let $=await SQ(Q);if($.error)return RQ($);let G=$.body,Z=typeof G.runId==="string"?G.runId:void 0;if(!Z&&typeof G.clientRunId==="string"){if(Z=this.liveRuns.findByClientRunId(G.clientRunId)??void 0,!Z){let J=ZQ.get(G.clientRunId);if(J)return J.cancelled=!0,{stopped:!0}}}if(!Z&&typeof G.threadId==="string")Z=(await this.liveRuns.find({threadId:G.threadId}))?.runId;let W=Z?this.liveRuns.get(Z):null;if(!W)return{stopped:!1};return W.stop({reason:typeof G.reason==="string"?G.reason:void 0}),{stopped:!0}}async upload(Q=new v){let G=(await Q.rawRequest.formData()).get("file");if(!(G instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");return{fileId:await this.agent.provider.upload(G)}}onMessage(Q,$){}onToolCall(Q,$){}onAwaitingInput(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(Q.error,$);return;default:return}}async persistRun(Q,$){let G;try{G=await Q.result()}catch(W){this.safely(()=>this.onError({code:"unknown",message:W instanceof Error?W.message:String(W),retryable:!1},$));return}let Z=G.messages;if($.threadId&&Z.length>0)try{await this.store.appendMessages($.threadId,Z)}catch(W){this.reportHookFailure(W)}this.notifyRun(G,Z,$)}async notifyRun(Q,$,G){for(let Z of $)await this.safely(()=>this.onMessage(Z,G));await this.safely(()=>this.onStreamComplete(Q,G))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}async function SQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!_5($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let G;try{G=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!G.trim())return{body:{}};let Z;try{Z=JSON.parse(G)}catch{return{body:{},error:"The request body is not valid JSON."}}if(Z===null||typeof Z!=="object"||Array.isArray(Z))return{body:{},error:"The request body must be a JSON object."};return{body:Z}}function _5(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function RQ(Q){return R(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function L5(Q){let $=Q.turn&&typeof Q.turn==="object"?Q.turn:Q,G={};if(typeof $.text==="string")G.text=$.text;if(Array.isArray($.files))G.files=$.files;if(Array.isArray($.toolResults))G.toolResults=$.toolResults;return Object.keys(G).length>0?G:void 0}function M5(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let Z=Math.floor($.cursor);if(Z>=0)return Z+1;return}let G=Q?.rawRequest?.headers?.get("Last-Event-ID");if(G){let Z=Number.parseInt(G,10);if(Number.isFinite(Z))return Math.max(0,Z+1)}return}function q5(Q,$){let G=Q?.search?.get($);return typeof G==="string"?G:void 0}function R(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}export{R2 as s,PQ as liveRuns,TQ as defaultAgentStore,s as ToolNamespace,DQ as Skill,b as SKILLS_NAMESPACE,q as PendingEscalation,MQ as OpenAIProvider,QQ as MemoryLiveRuns,$Q as MemoryAgentStore,f as LiveRunNotFoundError,k as FrameCursorEvictedError,qQ as AzureOpenAIProvider,h as AgentTool,e as AgentProvider,_2 as AgentController,UQ as Agent};
19
+
20
+ //# debugId=906EB9538B9BB7D764756E2164756E21