gemi 0.75.0 → 0.77.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 (188) hide show
  1. package/dist/ai/AgentController.d.ts +47 -0
  2. package/dist/ai/AgentController.d.ts.map +1 -1
  3. package/dist/ai/index.js +10 -10
  4. package/dist/ai/index.js.map +7 -5
  5. package/dist/ai/providers/request.d.ts.map +1 -1
  6. package/dist/ai/store/TurnJournal.d.ts +97 -0
  7. package/dist/ai/store/TurnJournal.d.ts.map +1 -0
  8. package/dist/ai/types.d.ts +29 -3
  9. package/dist/ai/types.d.ts.map +1 -1
  10. package/dist/app/index.js +1 -1
  11. package/dist/broadcasting/index.js +1 -1
  12. package/dist/bun/plugin.js +1 -1
  13. package/dist/bun/preload.js +1 -1
  14. package/dist/{chunk-fy2f8sq8.js → chunk-0472aphj.js} +2 -2
  15. package/dist/{chunk-fy2f8sq8.js.map → chunk-0472aphj.js.map} +1 -1
  16. package/dist/{chunk-bm97dwbp.js → chunk-0da5t7vs.js} +2 -2
  17. package/dist/{chunk-bm97dwbp.js.map → chunk-0da5t7vs.js.map} +1 -1
  18. package/dist/{chunk-17q5kheg.js → chunk-0pqsp84p.js} +2 -2
  19. package/dist/{chunk-17q5kheg.js.map → chunk-0pqsp84p.js.map} +1 -1
  20. package/dist/{chunk-8ef9n5pk.js → chunk-1712rv0r.js} +2 -2
  21. package/dist/{chunk-8ef9n5pk.js.map → chunk-1712rv0r.js.map} +1 -1
  22. package/dist/{chunk-9gn3x603.js → chunk-1ap69pez.js} +1 -1
  23. package/dist/{chunk-a1n0thja.js → chunk-1qwkhbc4.js} +2 -2
  24. package/dist/{chunk-a1n0thja.js.map → chunk-1qwkhbc4.js.map} +1 -1
  25. package/dist/{chunk-qn7rr4bw.js → chunk-27pnn95c.js} +2 -2
  26. package/dist/{chunk-qn7rr4bw.js.map → chunk-27pnn95c.js.map} +1 -1
  27. package/dist/{chunk-q60vevbt.js → chunk-34s3tfgk.js} +3 -3
  28. package/dist/{chunk-q60vevbt.js.map → chunk-34s3tfgk.js.map} +1 -1
  29. package/dist/{chunk-9h0cz1f0.js → chunk-3hfwbp2m.js} +2 -2
  30. package/dist/{chunk-9h0cz1f0.js.map → chunk-3hfwbp2m.js.map} +1 -1
  31. package/dist/{chunk-3dd2gwrj.js → chunk-3jyz4378.js} +2 -2
  32. package/dist/{chunk-3dd2gwrj.js.map → chunk-3jyz4378.js.map} +1 -1
  33. package/dist/{chunk-t20b1xn4.js → chunk-443yr2km.js} +3 -3
  34. package/dist/{chunk-t20b1xn4.js.map → chunk-443yr2km.js.map} +1 -1
  35. package/dist/{chunk-xrd9xx3c.js → chunk-4h7z32zp.js} +3 -3
  36. package/dist/{chunk-xrd9xx3c.js.map → chunk-4h7z32zp.js.map} +1 -1
  37. package/dist/{chunk-3nxkn558.js → chunk-5ddn8mfj.js} +2 -2
  38. package/dist/{chunk-3nxkn558.js.map → chunk-5ddn8mfj.js.map} +1 -1
  39. package/dist/{chunk-pxfw8dg1.js → chunk-6h5gvcs8.js} +2 -2
  40. package/dist/{chunk-pxfw8dg1.js.map → chunk-6h5gvcs8.js.map} +1 -1
  41. package/dist/{chunk-7e4rhaqs.js → chunk-7yhsy039.js} +2 -2
  42. package/dist/{chunk-7e4rhaqs.js.map → chunk-7yhsy039.js.map} +1 -1
  43. package/dist/{chunk-zat41156.js → chunk-989rzqd6.js} +3 -3
  44. package/dist/{chunk-zat41156.js.map → chunk-989rzqd6.js.map} +1 -1
  45. package/dist/{chunk-hny56r47.js → chunk-9z3y20ms.js} +2 -2
  46. package/dist/{chunk-hny56r47.js.map → chunk-9z3y20ms.js.map} +1 -1
  47. package/dist/{chunk-yqb9cpkx.js → chunk-axxbkm30.js} +2 -2
  48. package/dist/{chunk-yqb9cpkx.js.map → chunk-axxbkm30.js.map} +1 -1
  49. package/dist/{chunk-mc7nbgct.js → chunk-b941c34r.js} +2 -2
  50. package/dist/{chunk-mc7nbgct.js.map → chunk-b941c34r.js.map} +1 -1
  51. package/dist/{chunk-62pzr6vf.js → chunk-bdfdjnht.js} +3 -3
  52. package/dist/{chunk-62pzr6vf.js.map → chunk-bdfdjnht.js.map} +1 -1
  53. package/dist/chunk-cr9f0s09.js +5 -0
  54. package/dist/{chunk-krjkgg9v.js.map → chunk-cr9f0s09.js.map} +1 -1
  55. package/dist/{chunk-0yfgptrq.js → chunk-dgqqv3pb.js} +2 -2
  56. package/dist/{chunk-0yfgptrq.js.map → chunk-dgqqv3pb.js.map} +1 -1
  57. package/dist/{chunk-j9r5w8xf.js → chunk-dmdmt3gw.js} +2 -2
  58. package/dist/{chunk-j9r5w8xf.js.map → chunk-dmdmt3gw.js.map} +1 -1
  59. package/dist/chunk-e8z3nyd5.js +19 -0
  60. package/dist/{chunk-ytt205yt.js.map → chunk-e8z3nyd5.js.map} +8 -7
  61. package/dist/{chunk-8rqdeyhv.js → chunk-e97kq9tn.js} +2 -2
  62. package/dist/{chunk-8rqdeyhv.js.map → chunk-e97kq9tn.js.map} +1 -1
  63. package/dist/{chunk-evbvpfv6.js → chunk-eekg7k6d.js} +1 -1
  64. package/dist/{chunk-26rqzgsr.js → chunk-ezae18wm.js} +2 -2
  65. package/dist/{chunk-26rqzgsr.js.map → chunk-ezae18wm.js.map} +1 -1
  66. package/dist/{chunk-ppscsvv8.js → chunk-f2hkhw76.js} +2 -2
  67. package/dist/{chunk-ppscsvv8.js.map → chunk-f2hkhw76.js.map} +1 -1
  68. package/dist/{chunk-d6dz2706.js → chunk-fd0n8sav.js} +2 -2
  69. package/dist/{chunk-1x8gzkpq.js.map → chunk-fd0n8sav.js.map} +1 -1
  70. package/dist/{chunk-3sdrj0ma.js → chunk-fmhkn266.js} +2 -2
  71. package/dist/{chunk-3sdrj0ma.js.map → chunk-fmhkn266.js.map} +1 -1
  72. package/dist/{chunk-9ecgk1c5.js → chunk-fms4fcd1.js} +2 -2
  73. package/dist/{chunk-9ecgk1c5.js.map → chunk-fms4fcd1.js.map} +1 -1
  74. package/dist/{chunk-f90k29w1.js → chunk-fvn78g6k.js} +2 -2
  75. package/dist/{chunk-f90k29w1.js.map → chunk-fvn78g6k.js.map} +1 -1
  76. package/dist/{chunk-8ypzxfvx.js → chunk-gzs2y282.js} +2 -2
  77. package/dist/{chunk-8ypzxfvx.js.map → chunk-gzs2y282.js.map} +1 -1
  78. package/dist/{chunk-gpys09rg.js → chunk-j1w19cec.js} +3 -3
  79. package/dist/{chunk-gpys09rg.js.map → chunk-j1w19cec.js.map} +1 -1
  80. package/dist/{chunk-8jgj7vdp.js → chunk-j8nbjpkg.js} +2 -2
  81. package/dist/{chunk-8jgj7vdp.js.map → chunk-j8nbjpkg.js.map} +1 -1
  82. package/dist/{chunk-achgw308.js → chunk-jcq0tbdv.js} +2 -2
  83. package/dist/{chunk-achgw308.js.map → chunk-jcq0tbdv.js.map} +1 -1
  84. package/dist/{chunk-9sqw5bjy.js → chunk-m2bmwre5.js} +2 -2
  85. package/dist/{chunk-9sqw5bjy.js.map → chunk-m2bmwre5.js.map} +1 -1
  86. package/dist/{chunk-pp9c3f5m.js → chunk-mmhf39tr.js} +2 -2
  87. package/dist/{chunk-pp9c3f5m.js.map → chunk-mmhf39tr.js.map} +1 -1
  88. package/dist/{chunk-15gc8m24.js → chunk-n03frt02.js} +2 -2
  89. package/dist/{chunk-15gc8m24.js.map → chunk-n03frt02.js.map} +1 -1
  90. package/dist/{chunk-wtwkzgec.js → chunk-njh95es7.js} +2 -2
  91. package/dist/{chunk-wtwkzgec.js.map → chunk-njh95es7.js.map} +1 -1
  92. package/dist/{chunk-ngq4n2b3.js → chunk-q0nqypca.js} +2 -2
  93. package/dist/{chunk-ngq4n2b3.js.map → chunk-q0nqypca.js.map} +1 -1
  94. package/dist/{chunk-jpej3172.js → chunk-q623tx9p.js} +2 -2
  95. package/dist/{chunk-jpej3172.js.map → chunk-q623tx9p.js.map} +1 -1
  96. package/dist/{chunk-dz7b35tn.js → chunk-qgvg10ad.js} +3 -3
  97. package/dist/{chunk-dz7b35tn.js.map → chunk-qgvg10ad.js.map} +1 -1
  98. package/dist/{chunk-9p5vwn4d.js → chunk-qjgfrsw7.js} +2 -2
  99. package/dist/{chunk-9p5vwn4d.js.map → chunk-qjgfrsw7.js.map} +1 -1
  100. package/dist/{chunk-371tt28q.js → chunk-rkx6qhwg.js} +4 -4
  101. package/dist/{chunk-371tt28q.js.map → chunk-rkx6qhwg.js.map} +1 -1
  102. package/dist/{chunk-1k0gv92y.js → chunk-rv9k5bqn.js} +2 -2
  103. package/dist/{chunk-1k0gv92y.js.map → chunk-rv9k5bqn.js.map} +1 -1
  104. package/dist/{chunk-407t1q1d.js → chunk-s7hv9qgp.js} +2 -2
  105. package/dist/{chunk-407t1q1d.js.map → chunk-s7hv9qgp.js.map} +1 -1
  106. package/dist/{chunk-wbxmwzdb.js → chunk-sbqy6r29.js} +1 -1
  107. package/dist/{chunk-a82m12q4.js → chunk-sp4wwg7s.js} +3 -3
  108. package/dist/{chunk-a82m12q4.js.map → chunk-sp4wwg7s.js.map} +1 -1
  109. package/dist/{chunk-3eejq348.js → chunk-sqvw7rv2.js} +3 -3
  110. package/dist/{chunk-3eejq348.js.map → chunk-sqvw7rv2.js.map} +1 -1
  111. package/dist/{chunk-1yr8qejy.js → chunk-ss7ymqfm.js} +2 -2
  112. package/dist/{chunk-1yr8qejy.js.map → chunk-ss7ymqfm.js.map} +1 -1
  113. package/dist/{chunk-cr2wpeh5.js → chunk-sww4kgk4.js} +2 -2
  114. package/dist/{chunk-cr2wpeh5.js.map → chunk-sww4kgk4.js.map} +1 -1
  115. package/dist/{chunk-4z5qqq1t.js → chunk-tnt0ybj9.js} +2 -2
  116. package/dist/{chunk-4z5qqq1t.js.map → chunk-tnt0ybj9.js.map} +1 -1
  117. package/dist/{chunk-pjcdekm1.js → chunk-tpdsfr2k.js} +2 -2
  118. package/dist/{chunk-pjcdekm1.js.map → chunk-tpdsfr2k.js.map} +1 -1
  119. package/dist/{chunk-ra1ccnd5.js → chunk-vr84mhmq.js} +2 -2
  120. package/dist/{chunk-ra1ccnd5.js.map → chunk-vr84mhmq.js.map} +1 -1
  121. package/dist/{chunk-y3hmzww0.js → chunk-waax3j1k.js} +2 -2
  122. package/dist/{chunk-y3hmzww0.js.map → chunk-waax3j1k.js.map} +1 -1
  123. package/dist/{chunk-1x8gzkpq.js → chunk-xzp2ptj5.js} +2 -2
  124. package/dist/{chunk-d6dz2706.js.map → chunk-xzp2ptj5.js.map} +1 -1
  125. package/dist/{chunk-ywf0kz71.js → chunk-yaz93haz.js} +2 -2
  126. package/dist/{chunk-ywf0kz71.js.map → chunk-yaz93haz.js.map} +1 -1
  127. package/dist/{chunk-1rnzaqpm.js → chunk-yernnzqs.js} +2 -2
  128. package/dist/{chunk-1rnzaqpm.js.map → chunk-yernnzqs.js.map} +1 -1
  129. package/dist/{chunk-a4xxmmct.js → chunk-zjg31baf.js} +2 -2
  130. package/dist/{chunk-a4xxmmct.js.map → chunk-zjg31baf.js.map} +1 -1
  131. package/dist/{chunk-14pybfjk.js → chunk-zkty5j42.js} +2 -2
  132. package/dist/{chunk-14pybfjk.js.map → chunk-zkty5j42.js.map} +1 -1
  133. package/dist/{chunk-g2hwd2ts.js → chunk-zzh52t0y.js} +2 -2
  134. package/dist/{chunk-g2hwd2ts.js.map → chunk-zzh52t0y.js.map} +1 -1
  135. package/dist/client/MutationError.d.ts +16 -1
  136. package/dist/client/MutationError.d.ts.map +1 -1
  137. package/dist/client/index.js +94 -76
  138. package/dist/client/index.js.map +1 -1
  139. package/dist/client/useMutation.d.ts +1 -1
  140. package/dist/client/useMutation.d.ts.map +1 -1
  141. package/dist/config/index.js +1 -1
  142. package/dist/console/run.js +2 -2
  143. package/dist/console/run.js.map +1 -1
  144. package/dist/container/index.js +2 -2
  145. package/dist/container/index.js.map +1 -1
  146. package/dist/database/index.js +2 -2
  147. package/dist/database/index.js.map +1 -1
  148. package/dist/email/index.js +2 -2
  149. package/dist/email/index.js.map +1 -1
  150. package/dist/facades/index.js +2 -2
  151. package/dist/facades/index.js.map +1 -1
  152. package/dist/foundation/index.js +2 -2
  153. package/dist/foundation/index.js.map +1 -1
  154. package/dist/http/ApiRouter.d.ts +3 -2
  155. package/dist/http/ApiRouter.d.ts.map +1 -1
  156. package/dist/http/HttpResponse.d.ts +83 -0
  157. package/dist/http/HttpResponse.d.ts.map +1 -0
  158. package/dist/http/ViewRouter.d.ts.map +1 -1
  159. package/dist/http/index.d.ts +1 -0
  160. package/dist/http/index.d.ts.map +1 -1
  161. package/dist/http/index.js +2 -2
  162. package/dist/http/index.js.map +1 -1
  163. package/dist/i18n/dictionaryRuntime.js +2 -2
  164. package/dist/i18n/dictionaryRuntime.js.map +1 -1
  165. package/dist/i18n/index.js +2 -2
  166. package/dist/i18n/index.js.map +1 -1
  167. package/dist/kernel/index.js +2 -2
  168. package/dist/kernel/index.js.map +1 -1
  169. package/dist/orm/index.js +2 -2
  170. package/dist/orm/index.js.map +1 -1
  171. package/dist/server/index.js +2 -2
  172. package/dist/server/index.js.map +1 -1
  173. package/dist/services/index.js +2 -2
  174. package/dist/services/index.js.map +1 -1
  175. package/dist/services/queue/queueDriverContract.d.ts +6 -2
  176. package/dist/services/queue/queueDriverContract.d.ts.map +1 -1
  177. package/dist/services/queue/work.js +2 -2
  178. package/dist/services/queue/work.js.map +1 -1
  179. package/dist/services/router/ApiRouteDispatcher.d.ts.map +1 -1
  180. package/dist/services/router/serverQueryFetcher.d.ts.map +1 -1
  181. package/dist/support/index.js +2 -2
  182. package/dist/support/index.js.map +1 -1
  183. package/package.json +1 -1
  184. package/dist/chunk-krjkgg9v.js +0 -5
  185. package/dist/chunk-ytt205yt.js +0 -19
  186. /package/dist/{chunk-9gn3x603.js.map → chunk-1ap69pez.js.map} +0 -0
  187. /package/dist/{chunk-evbvpfv6.js.map → chunk-eekg7k6d.js.map} +0 -0
  188. /package/dist/{chunk-wbxmwzdb.js.map → chunk-sbqy6r29.js.map} +0 -0
@@ -54,6 +54,13 @@ export interface AgentStore {
54
54
  * lookup already but still needs an insert-or-update rather than a plain
55
55
  * insert, which would fail on the key; a store that is a list has to look
56
56
  * before it pushes.
57
+ *
58
+ * It is also called while a turn runs, not only when it ends (#617): with the
59
+ * user's message as the run starts, with the assistant message in progress
60
+ * (no `finishReason`, the run's id in `runId`) as it opens and at each tool
61
+ * call and result, and with each message again once it is finished. The
62
+ * same message arrives several times, and the last write is the one to
63
+ * keep. Calls for one run never overlap: each waits for the one before.
57
64
  */
58
65
  appendMessages(threadId: string, messages: AgentMessage[]): Promise<void>;
59
66
  }
@@ -579,6 +586,46 @@ Body extends object = Record<string, unknown>> extends ControllerBase {
579
586
  */
580
587
  protected reportHookFailure(error: unknown): void;
581
588
  private dispatchEvent;
589
+ /**
590
+ * The thread as a client should see it: the store's history, with any
591
+ * assistant message a dead run left unfinished marked `interrupted` (#617).
592
+ *
593
+ * For the app's own route that hands a thread to `useChat` (or a native
594
+ * session) as its initial messages. A message whose run is still going here
595
+ * is left as it is, still being written, so the client attaches to it. `null`
596
+ * for a thread the store does not have, as `loadThread` answers.
597
+ *
598
+ * It does not write: the next turn on the thread settles the same messages
599
+ * the same way and stores them then, under the thread's lock.
600
+ */
601
+ readThread(threadId: string): Promise<AgentMessage[] | null>;
602
+ /**
603
+ * Whether the run that was writing a message is still going, so the message
604
+ * is in progress rather than interrupted.
605
+ *
606
+ * The default asks this process's `liveRuns`, which is the whole answer on a
607
+ * single instance: a run lives in the process that started it, and a run
608
+ * that is not there died with an earlier one. A finished run still within
609
+ * `ttlMs` counts as live, since its final write may not have landed yet.
610
+ *
611
+ * Behind several instances it is not the whole answer. A run on another
612
+ * instance is not in this map, so its message reads as interrupted here
613
+ * until that run's own writes replace it. Knowing better needs a lasting
614
+ * record of running runs (#459); override this to consult one.
615
+ */
616
+ protected isRunLive(runId: string, threadId: string): boolean | Promise<boolean>;
617
+ private settleThread;
618
+ /**
619
+ * Feeds the run's frames to its journal as they are emitted.
620
+ *
621
+ * A subscriber of its own on `run.frames()` rather than a ride on the
622
+ * `onEvent` chain: that chain waits for the app's hooks, and a slow
623
+ * `onToolCall` must not be what decides whether a tool call was stored
624
+ * before the process died. `frames()` is a read of the run's own buffer, the
625
+ * one `toResponse` already reads beside `liveRuns`, so a third reader costs a
626
+ * cursor and nothing else.
627
+ */
628
+ private follow;
582
629
  /**
583
630
  * Runs after the stream is over, whether or not anyone was still watching it.
584
631
  *
@@ -1 +1 @@
1
- {"version":3,"file":"AgentController.d.ts","sourceRoot":"","sources":["../../ai/AgentController.ts"],"names":[],"mappings":"AACA,OAAO,EAAE,UAAU,EAAE,MAAM,oBAAoB,CAAC;AAChD,OAAO,EAAE,WAAW,EAAE,MAAM,qBAAqB,CAAC;AAClD,OAAO,KAAK,EAAE,eAAe,EAAE,MAAM,wBAAwB,CAAC;AAC9D,OAAO,KAAK,EAAE,YAAY,EAAE,QAAQ,EAAE,cAAc,EAAE,QAAQ,EAAE,YAAY,EAAE,MAAM,SAAS,CAAC;AAC9F,OAAO,EAGL,KAAK,qBAAqB,EAE1B,KAAK,eAAe,EACpB,KAAK,iBAAiB,EACtB,KAAK,eAAe,EAGpB,iBAAiB,EAClB,MAAM,qBAAqB,CAAC;AAC7B,OAAO,EACL,uBAAuB,EACvB,QAAQ,IAAI,eAAe,EAC3B,oBAAoB,EACpB,cAAc,EACf,MAAM,kBAAkB,CAAC;AAC1B,OAAO,EAAE,iBAAiB,EAAE,gBAAgB,EAAE,MAAM,0BAA0B,CAAC;AAE/E,OAAO,KAAK,EACV,UAAU,EACV,YAAY,EAGZ,eAAe,EACf,UAAU,EACX,MAAM,SAAS,CAAC;AAIjB;;;;;;;;GAQG;AACH,MAAM,WAAW,UAAU;IACzB;;;;;;;;OAQG;IACH,YAAY,CAAC,MAAM,EAAE;QAAE,MAAM,CAAC,EAAE,MAAM,GAAG,MAAM,CAAA;KAAE,GAAG,OAAO,CAAC;QAAE,QAAQ,EAAE,MAAM,CAAA;KAAE,CAAC,CAAC;IAClF;;;;;;;;;;OAUG;IACH,U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AC,OAAO,CAAC,SAAS,QAAQ,GAC5C,YAAY,CAAC,YAAY,CAAC,CAAC,CAAC,CAAC,OAAO,CAAC,CAAC,OAAO,CAAC,CAAC,GAC/C,UAAU,CAAC;IACf,MAAM,EAAE,OAAO,CAAC;IAChB;;;;;;;;;OASG;IACH,IAAI,EAAE,YAAY,CAAC,CAAC,CAAC,SAAS;QAAE,CAAC,IAAI,CAAC,CAAC,EAAE,MAAM,CAAC,CAAA;KAAE,GAAG,CAAC,GAAG,MAAM,CAAC,MAAM,EAAE,OAAO,CAAC,CAAC;CAClF,CAAC"}
package/dist/ai/index.js CHANGED
@@ -1,20 +1,20 @@
1
1
  // @bun
2
- import{Gb as V$,Hb as e}from"../chunk-zbhqa2z7.js";import{Le as p6,df as g,qf as l6}from"../chunk-xrd9xx3c.js";import{tf as r}from"../chunk-8ypzxfvx.js";import"../chunk-zat41156.js";import"../chunk-bm97dwbp.js";import"../chunk-f90k29w1.js";import"../chunk-ywf0kz71.js";import"../chunk-1x8gzkpq.js";import{createHmac as n6,randomBytes as dQ,timingSafeEqual as iQ}from"crypto";var FQ="agt1",nQ=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 S(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(S).join(",")}]`;let $=Q;return`{${Object.keys($).filter((J)=>$[J]!==void 0).sort().map((J)=>`${JSON.stringify(J)}:${S($[J])}`).join(",")}}`}function o6(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function p(Q,$){return n6("sha256",Q).update(o6($)).digest()}function oQ(Q,$,Z){let J=[FQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),S(Q.input)];if(Q.path&&Q.path.length>0)J.push(S(Q.path));return J}var sQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),s6=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function tQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??nQ),W=dQ(12).toString("base64url"),Y=p(Z,oQ(Q,W,G)).toString("base64url");return[FQ,sQ(Q.runId),W,G.toString(36),Y].join(".")}function l(Q){return LQ(Q,FQ)}function LQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let J=Number.parseInt(Z[3],36);if(!Number.isFinite(J))return null;try{return{runId:s6(Z[1]),nonce:Z[2],expiresAt:J}}catch{return null}}function aQ(Q,$,Z={}){let J=m(Z.secret),G=l(Q);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,oQ($,G.nonce,G.expiresAt));if(W.length!==Y.length||!iQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var d="agn1";function rQ(Q,$,Z){return[d,Q.runId,S(Q.path),Q.nestedRunId,$,String(Z),S([...Q.open].sort()),S(Q.input)]}function eQ(Q,$={}){let Z=m($.secret),G=($.now??Date.now())+($.ttlMs??nQ),W=dQ(12).toString("base64url"),Y=p(Z,rQ(Q,W,G)).toString("base64url");return[d,sQ(Q.runId),W,G.toString(36),Y].join(".")}function Q6(Q,$,Z={}){let J=m(Z.secret),G=LQ(Q,d);if(!G)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=p(J,rQ({...$,runId:G.runId},G.nonce,G.expiresAt));if(W.length!==Y.length||!iQ(W,Y))return{ok:!1,reason:"forged"};if((Z.now??Date.now())>G.expiresAt)return{ok:!1,reason:"expired"};return{ok:!0,runId:G.runId,nonce:G.nonce,expiresAt:G.expiresAt}}var A=new Map,$6=1024;function t6(Q){for(let[$,Z]of A)if(Z<=Q)A.delete($);$6=Math.max(1024,A.size*2)}function Z6(Q,$={}){return G6(l(Q),$)}function J6(Q,$={}){return G6(LQ(Q,d),$)}function G6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(A.size>=$6)t6(Z);let J=A.get(Q.nonce);if(J!==void 0&&J>Z)return!1;return A.set(Q.nonce,Q.expiresAt),!0}class v extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class I extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function OQ(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 N="gemi_att_";function CQ(){return`${N}${crypto.randomUUID()}`}class f{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;OQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new v(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new v(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),J=(await this.readRecord(Q,$)).body,G=J instanceof Blob?J:J?await new Response(J).blob():new Blob([]);return new File([G],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=CQ(),J=$.mimeType??Q.type??"",G=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:jQ(Z,G),body:Q,contentType:J||void 0}),Y={id:Z,scopeKey:this.scope.key,objectName:W,name:G,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,Y),Y}}function jQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class i{rows=new Map;async put(Q,$){OQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){OQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var n=new i;var NQ=new TextEncoder;function W6(Q){return`id: ${Q.seq}
2
+ import{Gb as k$,Hb as QQ}from"../chunk-zbhqa2z7.js";import{Me as $9,ef as m,rf as Z9}from"../chunk-4h7z32zp.js";import{uf as e}from"../chunk-gzs2y282.js";import"../chunk-989rzqd6.js";import"../chunk-0da5t7vs.js";import"../chunk-fvn78g6k.js";import"../chunk-yaz93haz.js";import"../chunk-xzp2ptj5.js";import{createHmac as W9,randomBytes as nQ,timingSafeEqual as sQ}from"crypto";var LQ="agt1",tQ=86400000;function p(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 R(Q){if(Q===null||typeof Q!=="object")return JSON.stringify(Q)??"null";if(Array.isArray(Q))return`[${Q.map(R).join(",")}]`;let $=Q;return`{${Object.keys($).filter((G)=>$[G]!==void 0).sort().map((G)=>`${JSON.stringify(G)}:${R($[G])}`).join(",")}}`}function Y9(Q){return Q.map(($)=>`${$.length}:${$}`).join("")}function l(Q,$){return W9("sha256",Q).update(Y9($)).digest()}function rQ(Q,$,Z){let G=[LQ,Q.runId,Q.toolCallId,Q.name,Q.kind,$,String(Z),R(Q.input)];if(Q.path&&Q.path.length>0)G.push(R(Q.path));return G}var aQ=(Q)=>Buffer.from(Q,"utf8").toString("base64url"),X9=(Q)=>Buffer.from(Q,"base64url").toString("utf8");function eQ(Q,$={}){let Z=p($.secret),J=($.now??Date.now())+($.ttlMs??tQ),W=nQ(12).toString("base64url"),Y=l(Z,rQ(Q,W,J)).toString("base64url");return[LQ,aQ(Q.runId),W,J.toString(36),Y].join(".")}function d(Q){return OQ(Q,LQ)}function OQ(Q,$){let Z=Q.split(".");if(Z.length!==5||Z[0]!==$)return null;let G=Number.parseInt(Z[3],36);if(!Number.isFinite(G))return null;try{return{runId:X9(Z[1]),nonce:Z[2],expiresAt:G}}catch{return null}}function Q6(Q,$,Z={}){let G=p(Z.secret),J=d(Q);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=l(G,rQ($,J.nonce,J.expiresAt));if(W.length!==Y.length||!sQ(W,Y))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 i="agn1";function $6(Q,$,Z){return[i,Q.runId,R(Q.path),Q.nestedRunId,$,String(Z),R([...Q.open].sort()),R(Q.input)]}function Z6(Q,$={}){let Z=p($.secret),J=($.now??Date.now())+($.ttlMs??tQ),W=nQ(12).toString("base64url"),Y=l(Z,$6(Q,W,J)).toString("base64url");return[i,aQ(Q.runId),W,J.toString(36),Y].join(".")}function G6(Q,$,Z={}){let G=p(Z.secret),J=OQ(Q,i);if(!J)return{ok:!1,reason:"malformed"};let W=Buffer.from(Q.split(".")[4],"base64url"),Y=l(G,$6({...$,runId:J.runId},J.nonce,J.expiresAt));if(W.length!==Y.length||!sQ(W,Y))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 I=new Map,J6=1024;function V9(Q){for(let[$,Z]of I)if(Z<=Q)I.delete($);J6=Math.max(1024,I.size*2)}function W6(Q,$={}){return X6(d(Q),$)}function Y6(Q,$={}){return X6(OQ(Q,i),$)}function X6(Q,$){if(!Q)return!1;let Z=$.now??Date.now();if(I.size>=J6)V9(Z);let G=I.get(Q.nonce);if(G!==void 0&&G>Z)return!1;return I.set(Q.nonce,Q.expiresAt),!0}class y extends Error{id;code="attachment_not_found";constructor(Q){super(`No attachment ${Q}.`);this.id=Q;this.name="AttachmentNotFoundError"}}class w extends Error{code="invalid_attachment_scope";constructor(Q){super(Q);this.name="InvalidAttachmentScopeError"}}function NQ(Q){if(!Q||typeof Q.key!=="string"||Q.key.length===0)throw new w("An attachment scope needs a non-empty key. Return `null` from `attachmentScope()` for a request that has no subject \u2014 an empty key is a bucket every caller shares.");return Q}var C="gemi_att_";function _Q(){return`${C}${crypto.randomUUID()}`}class h{store;storage;scope;constructor(Q,$,Z){this.store=Q;this.storage=$;this.scope=Z;NQ(Z)}async get(Q){let $=await this.store.find(this.scope,Q);if(!$||$.scopeKey!==this.scope.key)throw new y(Q);return $}async read(Q){return await this.readRecord(Q,await this.get(Q))}async readRecord(Q,$){if(!$.objectName)throw new y(Q);return await this.storage.read({name:$.objectName})}async file(Q){let $=await this.get(Q),G=(await this.readRecord(Q,$)).body,J=G instanceof Blob?G:G?await new Response(G).blob():new Blob([]);return new File([J],$.name,{type:$.mimeType})}async put(Q,$={}){let Z=_Q(),G=$.mimeType??Q.type??"",J=$.name??(Q instanceof File?Q.name:Z),W=await this.storage.put({name:CQ(Z,J),body:Q,contentType:G||void 0}),Y={id:Z,scopeKey:this.scope.key,objectName:W,name:J,mimeType:G||"application/octet-stream",size:Q.size,createdAt:new Date().toISOString(),destination:$.fileId?"both":"storage",...$.fileId?{fileId:$.fileId}:{}};return await this.store.put(this.scope,Y),Y}}function CQ(Q,$){let Z=/\.([A-Za-z0-9]{1,8})$/.exec($);return`attachments/${Q}${Z?`.${Z[1].toLowerCase()}`:""}`}class o{rows=new Map;async put(Q,$){NQ(Q),this.rows.set($.id,{...$,scopeKey:Q.key})}async find(Q,$){NQ(Q);let Z=this.rows.get($);if(!Z||Z.scopeKey!==Q.key)return null;return Z}get size(){return this.rows.size}}var n=new o;var jQ=new TextEncoder;function V6(Q){return`id: ${Q.seq}
3
3
  data: ${JSON.stringify(Q.event)}
4
4
 
5
- `}var a6=5000,r6=`: keepalive
5
+ `}var K9=5000,H9=`: keepalive
6
6
 
7
- `;function _Q(Q,$=a6){let Z=null,J=!1,G=()=>{if(J)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,J)return;try{Q.enqueue(NQ.encode(r6))}catch{W();return}G()},$)},W=()=>{if(J=!0,Z!==null)clearTimeout(Z);Z=null};return G(),{touch:G,stop:W}}function e6(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function Y6(Q,$=200){let Z=Q[Symbol.asyncIterator](),J=-1,G,W=new ReadableStream({start(Y){G=_Q(Y)},async pull(Y){try{let V=await Z.next();if(V.done){G.stop(),Y.close();return}J=V.value.seq,Y.enqueue(NQ.encode(W6(V.value))),G.touch()}catch(V){let X={type:"error",error:Q9(V)};G.stop(),Y.enqueue(NQ.encode(W6({seq:J+1,event:X}))),Y.close()}},cancel(Y){G.stop(),Z.return?.(Y)}});return new Response(W,{status:$,headers:e6()})}function Q9(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class R 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 k{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 k(Q)}static ask(Q){return k.create({name:Q.name,description:Q.description,inputSchema:qQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var qQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=qQ.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 QQ{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 QQ(Q)}}class SQ{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 SQ(Q)}}var y="skills",$9="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.",L6={type:"object",properties:{},required:[],additionalProperties:!1},Z9=8,J9=3;class RQ{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??Z9,this.maxDepth=Q.maxDepth??J9,this.reasoning=Q.reasoning;let{registry:$,providerTools:Z}=G9(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:$,providerTools:Z,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature}}static create(Q){return new RQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature};return new C6($,Q)}}function X6(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:e(Q.tool.inputSchema),deferred:Q.deferred}}function G9(Q,$){let Z=new Map,J=[],G=(W)=>{if(Z.has(W.tool.name))throw Error(`Two tools are named "${W.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(W.tool.name,W)};for(let W of Q){if(W instanceof QQ){if(W.name===y)throw Error(`"${y}" 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 V=[];for(let X of W.tools){let K={tool:X,namespace:W.name,deferred:W.deferred||X.deferred};G(K),V.push(X6(K))}J.push({name:W.name,description:W.description,tools:V});continue}let Y={tool:W,deferred:W.deferred};G(Y),J.push(X6(Y))}if($.length>0){let W=[];for(let Y of $){let V=W9(Y);G({tool:V,namespace:y,deferred:!1}),W.push({name:Y.name,description:Y.description,parameters:L6,strict:!0,deferred:!1})}J.push({name:y,description:$9,tools:W})}return{registry:Z,providerTools:J}}function W9(Q){return k.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>L6,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let J of Q.files??[])Z.push(`--- ${J} ---
8
- ${await Y9(J)}`);return Z.join(`
7
+ `;function PQ(Q,$=K9){let Z=null,G=!1,J=()=>{if(G)return;if(Z!==null)clearTimeout(Z);Z=setTimeout(()=>{if(Z=null,G)return;try{Q.enqueue(jQ.encode(H9))}catch{W();return}J()},$)},W=()=>{if(G=!0,Z!==null)clearTimeout(Z);Z=null};return J(),{touch:J,stop:W}}function B9(){return{"Content-Type":"text/event-stream","Cache-Control":"no-store, no-transform",Connection:"keep-alive","X-Accel-Buffering":"no"}}function K6(Q,$=200){let Z=Q[Symbol.asyncIterator](),G=-1,J,W=new ReadableStream({start(Y){J=PQ(Y)},async pull(Y){try{let V=await Z.next();if(V.done){J.stop(),Y.close();return}G=V.value.seq,Y.enqueue(jQ.encode(V6(V.value))),J.touch()}catch(V){let X={type:"error",error:D9(V)};J.stop(),Y.enqueue(jQ.encode(V6({seq:G+1,event:X}))),Y.close()}},cancel(Y){J.stop(),Z.return?.(Y)}});return new Response(W,{status:$,headers:B9()})}function D9(Q){return{code:"unknown",message:Q instanceof Error?Q.message:String(Q),retryable:!1}}class T 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 E{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 E(Q)}static ask(Q){return E.create({name:Q.name,description:Q.description,inputSchema:SQ,outputSchema:Q.outputSchema,answeredBy:"client"})}}var SQ={toJSONSchema:()=>({type:"object",properties:{question:{type:"string",description:"What to ask the user"}},required:["question"],additionalProperties:!1}),parse(Q){let $=SQ.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 $Q{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 $Q(Q)}}class RQ{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 RQ(Q)}}var u="skills",U9="Instructions this agent can load on demand. Load the relevant one before acting in the area it covers.",_6={type:"object",properties:{},required:[],additionalProperties:!1},z9=8,F9=3;class TQ{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??z9,this.maxDepth=Q.maxDepth??F9,this.reasoning=Q.reasoning;let{registry:$,providerTools:Z}=L9(this.tools,this.skills);this.config={name:this.name,instructions:this.instructions,provider:this.provider,registry:$,providerTools:Z,output:Q.output,maxSteps:this.maxSteps,maxDepth:this.maxDepth,reasoning:this.reasoning,maxOutputTokens:Q.maxOutputTokens,temperature:Q.temperature}}static create(Q){return new TQ(Q)}stream(Q){let $={...this.config,provider:Q.provider??this.config.provider,maxSteps:Q.maxSteps??this.config.maxSteps,reasoning:Q.reasoning??this.config.reasoning,maxOutputTokens:Q.maxOutputTokens??this.config.maxOutputTokens,temperature:Q.temperature??this.config.temperature};return new j6($,Q)}}function H6(Q){return{name:Q.tool.name,description:Q.tool.description,parameters:Q.tool.inputSchema.toJSONSchema(),strict:QQ(Q.tool.inputSchema),deferred:Q.deferred}}function L9(Q,$){let Z=new Map,G=[],J=(W)=>{if(Z.has(W.tool.name))throw Error(`Two tools are named "${W.tool.name}". Tool names are global within an agent \u2014 the client discriminates a tool part by name alone.`);Z.set(W.tool.name,W)};for(let W of Q){if(W instanceof $Q){if(W.name===u)throw Error(`"${u}" 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 V=[];for(let X of W.tools){let K={tool:X,namespace:W.name,deferred:W.deferred||X.deferred};J(K),V.push(H6(K))}G.push({name:W.name,description:W.description,tools:V});continue}let Y={tool:W,deferred:W.deferred};J(Y),G.push(H6(Y))}if($.length>0){let W=[];for(let Y of $){let V=O9(Y);J({tool:V,namespace:u,deferred:!1}),W.push({name:Y.name,description:Y.description,parameters:_6,strict:!0,deferred:!1})}G.push({name:u,description:U9,tools:W})}return{registry:Z,providerTools:G}}function O9(Q){return E.create({name:Q.name,description:Q.description,inputSchema:{toJSONSchema:()=>_6,parse:()=>({}),safeParse:()=>({ok:!0,value:{}})},execute:async()=>{let Z=[typeof Q.instructions==="function"?await Q.instructions():Q.instructions];for(let G of Q.files??[])Z.push(`--- ${G} ---
8
+ ${await N9(G)}`);return Z.join(`
9
9
 
10
- `)}})}async function Y9(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}class T extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function o(Q,$){if($.aborted)return Promise.reject(new T);return new Promise((Z,J)=>{let G=()=>J(new T);$.addEventListener("abort",G,{once:!0}),Q.then(Z,J).finally(()=>$.removeEventListener("abort",G))})}function s(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function t(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 X9(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function PQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,J=!1;for(let Y of Q){if(Z){if(J)J=!1;else if(Y==="\\")J=!0;else if(Y==='"')Z=!1;continue}if(Y==='"')Z=!0;else if(Y==="{")$.push("}");else if(Y==="[")$.push("]");else if(Y==="}"||Y==="]")$.pop()}let G=Q;if(Z)G+='"';G=G.replace(/[,:]\s*$/,"");let W=$.reverse().join("");try{return JSON.parse(G+W)}catch{try{return JSON.parse(G.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function V6(Q,$){let Z=[...Q],J=new Map(Z.map((G,W)=>[G.id,W]));for(let G of $){let W=J.get(G.id);if(W===void 0)J.set(G.id,Z.length),Z.push(G);else Z[W]=G}return Z}function a(Q){let $=new Set;for(let J of Q)for(let G of J.content)if(G.type==="tool-result")$.add(G.toolCallId);let Z=new Set;for(let J of Q)for(let G of J.content)if(G.type==="tool-call"&&!$.has(G.toolCallId))Z.add(G.toolCallId);return Z}function K6(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let J=Z.length-1;J>=0;J--){let G=Z[J];if(G.type==="output"&&G.partial!==!0)return G.value}}return}function H6(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function O6(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function V9(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${O6($)}`:null}function B6(Q){let $=new Set;for(let Z of Q)for(let J of Z.content){if(J.type!=="tool-call")continue;for(let G of J.attachments??[])if("shown"in G&&G.shown)$.add(G.shown.messageId)}return $}var U6=1;function K9(Q,$,Z){let J=Z.mimeType||$.type||"";if(J&&Q.attachment.mimeType!==J)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(J)} on the replay`;let G=Boolean(Z.showModel);if(G!==Boolean(Q.shown))return G?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function H9(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${H6(Q.agent,Q.label)} on the turn that escalated and is ${H6($.name,Z.label)} on the replay`;let J=V9(Z),G=Q.messages[0],W=G?`${G.role}:${O6(G)}`:null;if(J!==null&&W!==null&&J!==W)return`was started with ${JSON.stringify(W)} on the turn that escalated and with ${JSON.stringify(J)} on the replay`;return null}function D6(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let J=0;J<$.length;J++)if(Z[J]!==$[J])return null;return Z.slice($.length)}class MQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let J=Z.length;J<Q;J++)Z[J]=this.fill();Z[Q]=$}}}}class C6{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=s();finishReason="stop";output;stopReason;settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});this.settled=this.execute(),r.getStore()?.waitUntil(this.settled)}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),Z=new TextEncoder,J=!1,G,W=new ReadableStream({start:async(Y)=>{G=_Q(Y);try{for await(let V of $){if(J)break;Y.enqueue(Z.encode(`id: ${V.seq}
10
+ `)}})}async function N9(Q){try{return await Bun.file(Q).text()}catch($){return`(could not be read: ${$.message})`}}class k extends Error{constructor(){super("The run was stopped");this.name="RunAborted"}}function s(Q,$){if($.aborted)return Promise.reject(new k);return new Promise((Z,G)=>{let J=()=>G(new k);$.addEventListener("abort",J,{once:!0}),Q.then(Z,G).finally(()=>$.removeEventListener("abort",J))})}function t(){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 _9(Q){return typeof Q==="object"&&Q!==null&&typeof Q.next==="function"&&Symbol.asyncIterator in Q}function MQ(Q){if(!Q.trim())return{};try{return JSON.parse(Q)}catch{}let $=[],Z=!1,G=!1;for(let Y of Q){if(Z){if(G)G=!1;else if(Y==="\\")G=!0;else if(Y==='"')Z=!1;continue}if(Y==='"')Z=!0;else if(Y==="{")$.push("}");else if(Y==="[")$.push("]");else if(Y==="}"||Y==="]")$.pop()}let J=Q;if(Z)J+='"';J=J.replace(/[,:]\s*$/,"");let W=$.reverse().join("");try{return JSON.parse(J+W)}catch{try{return JSON.parse(J.replace(/,?\s*"[^"]*"\s*$/,"")+W)}catch{return{}}}}function B6(Q,$){let Z=[...Q],G=new Map(Z.map((J,W)=>[J.id,W]));for(let J of $){let W=G.get(J.id);if(W===void 0)G.set(J.id,Z.length),Z.push(J);else Z[W]=J}return Z}function a(Q){let $=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-result")$.add(J.toolCallId);let Z=new Set;for(let G of Q)for(let J of G.content)if(J.type==="tool-call"&&!$.has(J.toolCallId))Z.add(J.toolCallId);return Z}function D6(Q){for(let $=Q.length-1;$>=0;$--){let Z=Q[$].content;for(let G=Z.length-1;G>=0;G--){let J=Z[G];if(J.type==="output"&&J.partial!==!0)return J.value}}return}function U6(Q,$){return $===void 0?`"${Q}"`:`"${Q}" labelled "${$}"`}function C6(Q){return Q.content.map(($)=>$.type==="text"?$.text:`<${$.type}>`).join("")}function C9(Q){if(Q.prompt!==void 0)return`user:${Q.prompt}`;let $=Q.messages?.[0];return $?`${$.role}:${C6($)}`:null}function z6(Q){let $=new Set;for(let Z of Q)for(let G of Z.content){if(G.type!=="tool-call")continue;for(let J of G.attachments??[])if("shown"in J&&J.shown)$.add(J.shown.messageId)}return $}var F6=1;function j9(Q,$,Z){let G=Z.mimeType||$.type||"";if(G&&Q.attachment.mimeType!==G)return`was ${JSON.stringify(Q.attachment.mimeType)} on the turn that escalated and is ${JSON.stringify(G)} on the replay`;let J=Boolean(Z.showModel);if(J!==Boolean(Q.shown))return J?"was stored without showModel on the turn that escalated and asks for showModel on the replay":"was stored with showModel on the turn that escalated and asks for a plain put on the replay";return null}function P9(Q,$,Z){if(Q.agent!==$.name||Q.label!==Z.label)return`was ${U6(Q.agent,Q.label)} on the turn that escalated and is ${U6($.name,Z.label)} on the replay`;let G=C9(Z),J=Q.messages[0],W=J?`${J.role}:${C6(J)}`:null;if(G!==null&&W!==null&&G!==W)return`was started with ${JSON.stringify(W)} on the turn that escalated and with ${JSON.stringify(G)} on the replay`;return null}function L6(Q,$){let Z=Q??[];if(Z.length<$.length)return null;for(let G=0;G<$.length;G++)if(Z[G]!==$[G])return null;return Z.slice($.length)}class qQ{read;create;fill;index=0;replayable;constructor(Q,$,Z){this.read=Q;this.create=$;this.fill=Z;this.replayable=Q()?.length??0}next(){let Q=this.index++;return{at:Q,recorded:Q<this.replayable?this.read()?.[Q]:void 0,write:($)=>{let Z=this.read()??this.create();if(this.fill)for(let G=Z.length;G<Q;G++)Z[G]=this.fill();Z[Q]=$}}}}class j6{runId;config;params;context;controller=new AbortController;buffer=[];waiters=new Set;seq=0;ended=!1;history=[];produced=[];current=null;outputTruncated=!1;amended=new Map;unreported=new Set;usage=t();finishReason="stop";output;stopReason;settled;depth;maxDepth;chain;signingRunId;pathPrefix;onPending;nestedSettling=new Set;shownQueue=new Map;constructor(Q,$){this.config=Q,this.params=$,this.context=$.context??{},this.runId=$.runId??`run_${crypto.randomUUID()}`,this.history=[...$.messages];let Z=$.nesting;if(this.depth=Z?.depth??0,this.maxDepth=Z?.maxDepth??Q.maxDepth,this.chain=Z?.chain??[Q.name],this.signingRunId=Z?.signingRunId??this.runId,this.pathPrefix=Z?.signingPath??[],this.onPending=Z?.onPending??"escalate",$.signal)if($.signal.aborted)this.controller.abort();else $.signal.addEventListener("abort",()=>this.stop(),{once:!0});this.settled=this.execute(),e.getStore()?.waitUntil(this.settled)}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),Z=new TextEncoder,G=!1,J,W=new ReadableStream({start:async(Y)=>{J=PQ(Y);try{for await(let V of $){if(G)break;Y.enqueue(Z.encode(`id: ${V.seq}
11
11
  data: ${JSON.stringify(V.event)}
12
12
 
13
- `)),G.touch()}}catch{}G.stop();try{Y.close()}catch{}},cancel:()=>{J=!0,G.stop()}});return new Response(W,{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 T||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 Z=this.startMessage(),J=await this.runStep(Z);if(J.error){this.emit({type:"error",error:J.error}),await this.finalizeMessage("error"),this.finishReason="error";return}let G=Z.content.filter((Y)=>Y.type==="tool-call");if(G.length===0){this.finishReason=J.reason,await this.finalizeMessage(J.reason);return}let W=await this.runTools(Z,G,$);if(W.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:W});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(J.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;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let J of $.content)if(J.type==="text"||J.type==="reasoning"){if(typeof J.text==="string")J.text=B9(J.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,J={reason:"stop"},G=new Map,W="",V=Z.stream({messages:this.historyForProvider(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(),strict:e(this.config.output)}:void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let K=await o(Promise.resolve(V.next()),$);if(K.done)break;let H=K.value;switch(H.type){case"text-delta":{U9(Q,"text",H.delta),this.emit({type:"text-delta",messageId:Q.id,delta:H.delta});break}case"reasoning-delta":{D9(Q,H.id,H.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:H.delta,id:H.id});break}case"output-delta":{W+=H.delta,this.emit({type:"output-delta",messageId:Q.id,delta:H.delta,snapshot:PQ(W)});break}case"tool-search":{this.emit({type:"tool-search",loaded:H.loaded});break}case"tool-call-delta":{let B=G.get(H.toolCallId)??{name:H.name,args:""};B.args+=H.argsDelta,B.name=H.name||B.name,G.set(H.toolCallId,B),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:H.toolCallId,name:B.name,input:PQ(B.args),partial:!0}});break}case"tool-call":{G.delete(H.toolCallId);let B={type:"tool-call",toolCallId:H.toolCallId,name:H.name,input:F6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B});break}case"finish":{if(this.usage=t(this.usage,H.usage),!J.error)J={reason:H.reason};break}case"error":{J={reason:"error",error:H.error};break}}}for(let[K,H]of G){let B={type:"tool-call",toolCallId:K,name:H.name,input:F6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B})}let X=J.reason==="length";if(X)this.outputTruncated=!0;if(this.config.output&&W&&!J.error&&!X){let K=this.config.output.safeParse(PQ(W));if(K.ok===!0)this.output=K.value,Q.content.push({type:"output",value:K.value});else this.emit({type:"error",error:{code:"unknown",message:`The model's structured answer did not match the output schema: ${K.errors.join(", ")}`,retryable:!0}})}return J}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
13
+ `)),J.touch()}}catch{}J.stop();try{Y.close()}catch{}},cancel:()=>{G=!0,J.stop()}});return new Response(W,{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 k||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 Z=this.startMessage(),G=await this.runStep(Z);if(G.error){this.emit({type:"error",error:G.error}),await this.finalizeMessage("error"),this.finishReason="error";return}let J=Z.content.filter((Y)=>Y.type==="tool-call");if(J.length===0){this.finishReason=G.reason,await this.finalizeMessage(G.reason);return}let W=await this.runTools(Z,J,$);if(W.length>0){this.finishReason="awaiting-input",await this.finalizeMessage("awaiting-input"),this.emit({type:"awaiting-input",runId:this.runId,pending:W});return}if($===Q){this.finishReason="max-steps",await this.finalizeMessage("max-steps");return}await this.finalizeMessage(G.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;let Z=this.outputTruncated;if(this.outputTruncated=!1,$.finishReason=Q,Z)$.outputTruncated=!0;for(let G of $.content)if(G.type==="text"||G.type==="reasoning"){if(typeof G.text==="string")G.text=M9(G.text)}this.emit({type:"message-end",messageId:$.id,finishReason:Q,...Z?{outputTruncated:!0}:{}}),await this.report($),await this.reportDeferred()}async report(Q){if(!this.params.onMessage)return;try{await this.params.onMessage(Q)}catch{}}async runStep(Q){let $=this.controller.signal,Z=this.config.provider,G={reason:"stop"},J=new Map,W="",V=Z.stream({messages:this.historyForProvider(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(),strict:QQ(this.config.output)}:void 0,reasoning:this.config.reasoning,maxOutputTokens:this.config.maxOutputTokens,temperature:this.config.temperature,signal:$})[Symbol.asyncIterator]();for(;;){let K=await s(Promise.resolve(V.next()),$);if(K.done)break;let H=K.value;switch(H.type){case"text-delta":{q9(Q,"text",H.delta),this.emit({type:"text-delta",messageId:Q.id,delta:H.delta});break}case"reasoning-delta":{S9(Q,H.id,H.delta),this.emit({type:"reasoning-delta",messageId:Q.id,delta:H.delta,id:H.id});break}case"output-delta":{W+=H.delta,this.emit({type:"output-delta",messageId:Q.id,delta:H.delta,snapshot:MQ(W)});break}case"tool-search":{this.emit({type:"tool-search",loaded:H.loaded});break}case"tool-call-delta":{let B=J.get(H.toolCallId)??{name:H.name,args:""};B.args+=H.argsDelta,B.name=H.name||B.name,J.set(H.toolCallId,B),this.emit({type:"tool-call",messageId:Q.id,part:{type:"tool-call",toolCallId:H.toolCallId,name:B.name,input:MQ(B.args),partial:!0}});break}case"tool-call":{J.delete(H.toolCallId);let B={type:"tool-call",toolCallId:H.toolCallId,name:H.name,input:N6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B});break}case"finish":{if(this.usage=r(this.usage,H.usage),!G.error)G={reason:H.reason};break}case"error":{G={reason:"error",error:H.error};break}}}for(let[K,H]of J){let B={type:"tool-call",toolCallId:K,name:H.name,input:N6(H.args)};Q.content.push(B),this.emit({type:"tool-call",messageId:Q.id,part:B})}let X=G.reason==="length";if(X)this.outputTruncated=!0;if(this.config.output&&W&&!G.error&&!X){let K=this.config.output.safeParse(MQ(W));if(K.ok===!0)this.output=K.value,Q.content.push({type:"output",value:K.value});else this.emit({type:"error",error:{code:"unknown",message:`The model's structured answer did not match the output schema: ${K.errors.join(", ")}`,retryable:!0}})}return G}async systemPrompt(){let Q=[this.config.instructions,this.params.instructions].filter(($)=>Boolean($&&$.trim()));return Q.length>0?Q.join(`
14
14
 
15
- `):void 0}async runTools(Q,$,Z){let J=[],G=[];for(let W of $){let Y=this.config.registry.get(String(W.name));if(!Y){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(W.name)}".`,toolCallId:W.toolCallId,retryable:!0}});continue}let V=Y.tool.inputSchema.safeParse(W.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(W.name)}": ${V.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=V.value;let X=z6(Y.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));continue}J.push({toolCallId:W.toolCallId,name:W.name,input:V.value,kind:X,signature:tQ(this.claimsFor(W.toolCallId,String(W.name),X,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}G.push(this.executeTool(Y,Q.id,W,V.value,Z).then(async(K)=>{this.addResult(Q,K),await this.settleShown(W.toolCallId)}).catch((K)=>{if(K instanceof R){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));return}J.push(...K.pending);return}}))}return await o(Promise.all(G).then(()=>{return}),this.controller.signal),J}claimsFor(Q,$,Z,J){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:J,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,$,Z,J,G,W){let Y=this.toolFiles(Z),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:G,depth:this.depth,resumed:W!==void 0,attachments:Y.attachments,generateImage:Y.generateImage,editImage:Y.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,W)};try{let X=Q.tool.execute(J,V),K;if(X9(X)){let H=await X.next();while(!H.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:H.value}),H=await X.next();K=H.value}else K=await X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:K}}catch(X){if(X instanceof T||this.controller.signal.aborted)throw new T;if(X instanceof R)throw X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:X instanceof Error?X.message:String(X),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let J=new MQ(()=>$.nested,()=>$.nested=[]);return async(G,W={})=>{let{at:Y,recorded:V,write:X}=J.next();if(V){let K=H9(V,G,W);if(K)throw Error(`Nested run ${Y} 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(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??s(),output:K6(V.messages),nested:V}}return this.runNested(Q,$,G,W,X,V,Z?.answers??[])}}async runNested(Q,$,Z,J,G,W,Y){let V=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let K=J.label,H=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":J.onPending??"escalate",U=W!==void 0,L=U?a(W.messages):new Set,D=U?Y.filter((O)=>{let E=D6(O.path,H);if(E===null)return!1;return L.has(E.length>0?E[0]:O.toolCallId)}):[],z=Z.stream({messages:U?W.messages:J.messages??[],turn:U?{toolResults:D}:J.prompt?{text:J.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:this.controller.signal,threadId:this.params.threadId,instructions:J.instructions,maxOutputTokens:J.maxOutputTokens,temperature:J.temperature,runId:U?W.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:H,onPending:B}}),F=[],P=(async()=>{for await(let O of z){if(O.type==="awaiting-input")F=O.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:z.runId,agent:Z.name,label:K,event:O})}})(),M=(async()=>{let O=await z.result();await P;let E=U?V6(W.messages,O.messages):V6(J.messages??[],O.messages),lQ={runId:z.runId,agent:Z.name,label:K,messages:E,finishReason:O.finishReason,usage:U?t(W.usage??s(),O.usage):O.usage,...O.finishReason==="awaiting-input"?{signature:eQ({runId:this.signingRunId,path:H,nestedRunId:z.runId,open:[...a(E)],input:$.input})}:{}};return G(lQ),this.usage=t(this.usage,O.usage),{result:O,record:lQ}})(),C=M.then(()=>{return},()=>{return});this.nestedSettling.add(C);let c,q;try{({result:c,record:q}=await M)}finally{this.nestedSettling.delete(C)}if(this.controller.signal.aborted)throw new T;if(c.finishReason==="awaiting-input"){if(F.length===0)throw Error(`"${Z.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 R({pending:F,path:H,nested:q})}return{runId:q.runId,agent:Z.name,messages:q.messages,finishReason:c.finishReason,usage:q.usage??s(),output:c.output??K6(q.messages),nested:q}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q){let $=this.params.attachments??null,Z=new MQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),J=()=>{if(!$)throw new I("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $},G=async(X,K,H)=>{let B=J(),U=K.mimeType||X.type||"",L=K.name??(X instanceof File?X.name:"attachment"),D;if(K.showModel){let F=this.config.provider;if(!F.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${F.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);D=await F.upload(new File([X],L,{type:U||void 0}))}return{attachment:await B.put(X,{name:L,mimeType:U,fileId:D}),...H?{generated:H}:{},...D?{shown:{fileId:D,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},W=(X,K,H)=>{let B=X.generated?"image":"put";if(B===K)return;throw Error(`Attachment ${H} of "${String(Q.name)}" was ${B==="image"?"a generated image":"a stored file"} on the first attempt and is ${K==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},Y=async(X,K,H)=>{let{at:B,recorded:U,write:L}=Z.next();if(U&&"attachment"in U){if(W(U,"image",B),U.shown)this.queueShown(Q.toolCallId,U);return{attachment:U.attachment,size:U.generated.size,mimeType:U.attachment.mimeType,usage:U.generated.usage}}let D=await H();this.usage=t(this.usage,D.usage);let z=D.mimeType==="image/jpeg"?"jpg":"png",F=await G(D.image,{name:K.name??`${X.name}.${z}`,mimeType:D.mimeType,...K.showModel?{showModel:!0}:{}},{size:D.size,usage:D.usage});if(L(F),F.shown)this.queueShown(Q.toolCallId,F);return{attachment:F.attachment,size:D.size,mimeType:D.mimeType,usage:D.usage}},V=async(X)=>typeof X==="string"?await J().file(X):X;return{generateImage:(X,K)=>Y(X,K,()=>X.generate({...K,signal:this.controller.signal})),editImage:(X,K)=>Y(X,K,async()=>{let{images:H,mask:B,...U}=K;return await X.edit({...U,images:await Promise.all(H.map(V)),...B?{mask:await V(B)}:{},signal:this.controller.signal})}),attachments:{get:(X)=>J().get(X),read:(X)=>J().read(X),file:(X)=>J().file(X),put:async(X,K={})=>{let{at:H,recorded:B,write:U}=Z.next();if(B&&"attachment"in B){W(B,"put",H);let D=K9(B,X,K);if(D)throw Error(`Attachment ${H} of "${String(Q.name)}" ${D}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let L=await G(X,K);if(U(L),L.shown)this.queueShown(Q.toolCallId,L);return L.attachment}}}}toolTurn(Q){let $=this.history.findIndex((W)=>W.id===Q),Z=B6(this.history),J;for(let W=$-1;W>=0;W--){let Y=this.history[W];if(Y.role!=="user"||Z.has(Y.id))continue;J=Y;break}let G=[];for(let W of J?.content??[]){if(W.type!=="file")continue;let Y=W.attachmentId;if(typeof Y!=="string"||!Y.startsWith(N))continue;if(!G.includes(Y))G.push(Y)}return Object.freeze({attachments:Object.freeze(G)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let J=this.shownQueue.get(Q)??[];if(J.some((G)=>G.id===Z.messageId))return;J.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,J)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((J)=>J.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((W)=>W!==Q),Z=B6($),J=[];for(let W of $){if(!Z.has(W.id))continue;for(let Y of W.content)if(Y.type==="file")J.push(Y)}if(J.length<=U6)return $;let G=new Set(J.slice(0,J.length-U6));return $.map((W)=>{if(!W.content.some((Y)=>Y.type==="file"&&G.has(Y)))return W;return{...W,content:W.content.map((Y)=>Y.type==="file"&&G.has(Y)?{type:"text",text:`[A ${Y.mimeType||"file"} produced by a tool (attachment ${Y.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:Y)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let J=new Set,G=new Set,W=new Map;for(let Y of Q?.toolResults??[]){let V=`${(Y.path??[]).join("/")}#${Y.toolCallId}`;if(G.has(V))continue;G.add(V);let X=(U)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:U,toolCallId:Y.toolCallId,retryable:!1}}),K=D6(Y.path,this.pathPrefix);if(K===null){X(`The answer for "${Y.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(K.length>0){let U=K[0],L=$.find((F)=>F.call.toolCallId===U);if(!L){X(`No pending tool call with id "${U}" to deliver a nested answer to.`);continue}let D=this.parkedBelow(L.call,K,Y.toolCallId);if(D.ok===!1){let F=`The answer for "${Y.toolCallId}" is addressed under "${U}", which`;X(D.reason==="unparked"?`${F} has no sub-agent run waiting on that question.`:D.reason==="expired"?`${F} parked a sub-agent run that has since expired. Ask again.`:`${F} carries a record of a parked sub-agent run the server did not sign.`);continue}let z=W.get(U);if(!z){if(!J6(D.signature)){X(`The answer for "${Y.toolCallId}" is addressed under "${U}", which has already been re-entered on that record. Ask again.`);continue}z=[],W.set(U,z),J.add(U)}z.push(Y);continue}let H=$.find((U)=>U.call.toolCallId===Y.toolCallId);if(!H){X(`No pending tool call with id "${Y.toolCallId}".`);continue}let B=await this.resolveAnswer(H,Y,Z);if(B===null)continue;if(J.add(Y.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(Y.toolCallId)}for(let[Y,V]of W){let X=$.find((H)=>H.call.toolCallId===Y),K=await this.reenter(X,V,Z);if(K)this.attachToHistory(X,K),await this.settleShown(Y)}for(let Y of $){if(J.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.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let J={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((G)=>({type:"file",...G.fileId?{fileId:G.fileId}:{},name:G.name,mimeType:G.mimeType,...G.attachmentId?{attachmentId:G.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(J),this.produced.push(J),await this.report(J)}return Z}parkedBelow(Q,$,Z){let J=$.length>1?$[1]:Z,G=[...this.pathPrefix,Q.toolCallId],W=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&a(V.messages).has(J));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let Y=Q6(W.signature,{path:G,nestedRunId:W.runId,open:[...a(W.messages)],input:Q.input});if(Y.ok===!1)return{ok:!1,reason:Y.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:W.signature}}async reenter(Q,$,Z){let J=String(Q.call.name),G=this.config.registry.get(J);if(!G||!G.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${J}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let W=G.tool.inputSchema.safeParse(Q.call.input);if(W.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 "${J}": ${W.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let Y=this.amendCall(Q);Y.input=W.value;try{return await o(this.executeTool(G,Q.message.id,Y,W.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof R)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),J={...Q.call,nested:(Q.call.nested??[]).map((G)=>({...G})),...Q.call.attachments?{attachments:Q.call.attachments.map((G)=>({...G}))}:{}};if(Z>=0)$.content[Z]=J;return this.unreported.add($),J}openCalls(){let Q=new Set;for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-result")Q.add(J.toolCallId);let $=[];for(let Z of this.history)for(let J of Z.content)if(J.type==="tool-call"&&!Q.has(J.toolCallId))$.push({message:Z,call:J});return $}async resolveAnswer(Q,$,Z){let J=Q.call,G=String(J.name),W=this.config.registry.get(G),Y=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:J.toolCallId,retryable:!1}}),null};if(!W)return Y(`The tool "${G}" no longer exists, so its answer cannot be checked.`);let V=z6(W.tool);if(!V)return Y(`"${G}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return Y(`The answer for "${G}" carried no signature.`);let X=l($.signature);if(!X)return Y(`The signature for "${G}" is malformed.`);let K=aQ($.signature,{...this.claimsFor(J.toolCallId,G,V,J.input),runId:X.runId});if(K.ok===!1)return Y(K.reason==="expired"?`The approval for "${G}" has expired. Ask again.`:`The answer for "${G}" does not match the call the server made.`);if(!Z6($.signature))return Y(`The answer for "${G}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return Y(`"${G}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await o(this.executeTool(W,Q.message.id,H,H.input,0),this.controller.signal)}catch(B){if(B instanceof R)return Z.push(...B.pending),"open";throw B}}return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return Y(`"${G}" is approved, not answered: the server produces its result.`);let H=W.tool.outputSchema,B=H?H.safeParse($.output):{ok:!0,value:$.output};if(B.ok===!1)return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${G}" did not match its output schema: ${B.errors.join(", ")}`,toolCallId:J.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:J.toolCallId,name:J.name,status:"ok",output:B.value}}return Y(`The answer for "${G}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},J=this.history.indexOf(Q);if(J>=0)this.history[J]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){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.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function z6(Q){if(Q.answeredBy==="client")return Q.inputSchema===qQ?"question":"client";return Q.requiresApproval?"approval":null}function F6(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function B9(Q){if(Q.length>0)Q[0];return Q}function U9(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 D9(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 z9(Q,$){return Q.descriptors($).map((Z)=>k.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(J,G)=>{let W=r.getStore()?.req;if(!W)throw Error(`"${Z.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:W},Z.name,J,G)}}))}function F9(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),J=Number($[2]);if(Z%16!==0||J%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/J,J/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function j6(Q,$){if(Q.size!==void 0)try{F9(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function N6(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",J=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${J}`,{type:Z})}class TQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...J}=Q;j6(J,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=J}static create(Q){return new TQ(Q)}async generate(Q){let $=this.merge(Q);return _6(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return _6(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,J)=>N6(Z,`image-${J}`)),...Q.mask?{mask:N6(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return j6($,`ImageModel "${this.name}"`),$}}function _6(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function x(Q){return typeof process>"u"?void 0:process.env?.[Q]}var L9="preview";function P6(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function O9(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function $Q(Q,$={}){return{base:(Q.baseURL??x("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let J=Q.apiKey??x("OPENAI_API_KEY");return{...J?{authorization:`Bearer ${J}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function C9(Q){let $=Q.baseURL??Q.endpoint??x("AZURE_OPENAI_ENDPOINT");if($)return P6($);let Z=Q.resourceName??x("AZURE_OPENAI_RESOURCE_NAME")??x("AZURE_RESOURCE_NAME");return Z?P6(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function ZQ(Q,$={}){let Z=Q.apiVersion??x("AZURE_OPENAI_API_VERSION")??L9;return{base:`${C9(Q)}${O9(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let J=Q.apiKey??x("AZURE_OPENAI_API_KEY");return{...J?{"api-key":J}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}class JQ extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${j9($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class GQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function j9(Q){let $=M6(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function M6(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 G=J.innererror?.code??J.code;return{message:J.message,type:J.type,code:G,param:J.param}}function j(Q){if(Q instanceof GQ)return{code:"provider_error",message:Q.message,retryable:!0};if(M9(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof JQ)return N9(Q.status,M6(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 N9(Q,$,Z){let J=$?.message??Z,G=($?.code??"").toLowerCase(),W=($?.type??"").toLowerCase(),Y=`${G} ${W} ${J}`.toLowerCase();if(Q===429){let V=G==="insufficient_quota"||Y.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(_9(Y))return{code:"context_length_exceeded",message:J,retryable:!1};if(P9(Y))return{code:"content_filtered",message:J,retryable:!1};if($?.param?.startsWith("tools")||Y.includes("invalid schema for function"))return{code:"invalid_tool_input",message:J,retryable:!1};return{code:"provider_error",message:J,retryable:!1}}function _9(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function P9(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function M9(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var q9=500,S6=20000;function S9(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let J=Date.parse(Z);if(Number.isNaN(J))return;return Math.max(0,J-$)}function q6(Q,$){let Z=Math.min(S6,q9*2**Q);return Math.round(Z*(0.5+$()*0.5))}function R9(Q){return Q===429||Q===408||Q===409||Q>=500}function T9(Q,$){return R9(Q)&&j($).retryable}function R6(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function k9(Q,$){return new Promise((Z,J)=>{let G=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(G),J(R6($))},{once:!0})})}async function h(Q,$,Z){let J=Z.fetchImpl??((H,B)=>fetch(H,B)),G=Z.sleep??k9,W=Z.random??Math.random,Y=Z.now??Date.now,V=Math.max(0,Z.maxRetries),X=async(H)=>{let B=Z.signal;if(!B)return await G(H);B.throwIfAborted();let U;try{await Promise.race([G(H,B),new Promise((L,D)=>{U=()=>D(R6(B)),B.addEventListener("abort",U,{once:!0})})])}finally{if(U)B.removeEventListener("abort",U)}},K;for(let H=0;H<=V;H++){Z.signal?.throwIfAborted();let B=new AbortController,U=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",U,{once:!0});let L=!1,D=Z.timeoutMs>0?setTimeout(()=>{L=!0,B.abort()},Z.timeoutMs):void 0,z;try{z=await J(Q,{...$,signal:B.signal})}catch(C){if(D!==void 0)clearTimeout(D);if(Z.signal?.removeEventListener("abort",U),Z.signal?.aborted)throw C;if(K=L?new GQ(Z.timeoutMs):C,L&&Z.retryTimeouts===!1)throw K;if(H===V)throw K;await X(q6(H,W));continue}if(D!==void 0)clearTimeout(D);if(z.ok)return z;Z.signal?.removeEventListener("abort",U);let F=await x9(z),P=new JQ(z.status,F,z.headers.get("x-request-id")??void 0);if(H===V||!T9(z.status,P))throw P;let M=S9(z.headers.get("retry-after"),Y());await X(M===void 0?q6(H,W):Math.min(M,S6)),K=P}throw K??Error("Provider request failed with no response.")}async function x9(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var kQ=300000;function xQ(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class WQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var E9={png:"image/png",jpeg:"image/jpeg"};function A9(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},G=Q?.input_tokens_details?.image_tokens;if(typeof G==="number")J.imageInputTokens=G;let W=Q?.output_tokens_details?.image_tokens;if(typeof W==="number")J.imageOutputTokens=W;return J}function I9(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let J=0;J<$.length;J++)Z[J]=$.charCodeAt(J);return Z}function b9(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new WQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let J=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:I9(Z),mimeType:E9[J]??`image/${J}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:A9(Q.usage)}}async function T6(Q,$,Z,J){let G;try{G=await h(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:J.signal,fetchImpl:Z.fetchImpl})}catch(W){if(J.signal?.aborted)throw W;throw new WQ(j(W),{cause:W})}return b9(await G.json())}async function k6(Q,$,Z={}){return await T6(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function x6(Q,$,Z={}){return await T6(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class YQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await k6(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,J]of Object.entries(this.body(Q)))if(J!==void 0)$.set(Z,String(J));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await x6(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return j(Q)}}var E6=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class EQ extends YQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new EQ(Q,$)}static models(){return E6}endpoint(){return xQ($Q(this.config,{timeoutMs:kQ}))}}class AQ extends YQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new AQ(Q,$)}static models(){return E6}modelName(){return this.config.deployment??this.model}endpoint(){return xQ(ZQ(this.config,{timeoutMs:kQ}))}}async function*w9(Q){let $="",Z="",J=[],G,W=()=>{if(J.length===0&&!Z)return null;let X={event:Z,data:J.join(`
16
- `),id:G};return Z="",J=[],G=void 0,X.data?X:null},Y=(X)=>{let K=X.endsWith("\r")?X.slice(0,-1):X;if(K==="")return W();if(K.startsWith(":"))return null;let H=K.indexOf(":"),B=H===-1?K:K.slice(0,H),U=H===-1?"":K.slice(H+1);if(U.startsWith(" "))U=U.slice(1);if(B==="event")Z=U;else if(B==="data")J.push(U);else if(B==="id")G=U;return null};for await(let X of Q){$+=X;let K=$.indexOf(`
15
+ `):void 0}async runTools(Q,$,Z){let G=[],J=[];for(let W of $){let Y=this.config.registry.get(String(W.name));if(!Y){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"tool_error",message:`There is no tool named "${String(W.name)}".`,toolCallId:W.toolCallId,retryable:!0}});continue}let V=Y.tool.inputSchema.safeParse(W.input);if(V.ok===!1){this.addResult(Q,{type:"tool-result",toolCallId:W.toolCallId,name:W.name,status:"error",error:{code:"invalid_tool_input",message:`Invalid arguments for "${String(W.name)}": ${V.errors.join(", ")}`,toolCallId:W.toolCallId,retryable:!0}});continue}W.input=V.value;let X=O6(Y.tool);if(X){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));continue}G.push({toolCallId:W.toolCallId,name:W.name,input:V.value,kind:X,signature:eQ(this.claimsFor(W.toolCallId,String(W.name),X,V.value)),...this.pathPrefix.length>0?{path:[...this.pathPrefix]}:{}});continue}J.push(this.executeTool(Y,Q.id,W,V.value,Z).then(async(K)=>{this.addResult(Q,K),await this.settleShown(W.toolCallId)}).catch((K)=>{if(K instanceof T){if(this.onPending==="deny"){this.addResult(Q,this.deniedByPolicy(W));return}G.push(...K.pending);return}}))}return await s(Promise.all(J).then(()=>{return}),this.controller.signal),G}claimsFor(Q,$,Z,G){return{runId:this.signingRunId,toolCallId:Q,name:$,kind:Z,input:G,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,$,Z,G,J,W){let Y=this.toolFiles(Z),V={context:this.context,body:this.params.body??{},runId:this.runId,threadId:this.params.threadId,toolCallId:Z.toolCallId,signal:this.controller.signal,step:J,depth:this.depth,resumed:W!==void 0,attachments:Y.attachments,generateImage:Y.generateImage,editImage:Y.editImage,turn:this.toolTurn($),runAgent:this.nestedRunner($,Z,W)};try{let X=Q.tool.execute(G,V),K;if(_9(X)){let H=await X.next();while(!H.done)this.emit({type:"tool-progress",toolCallId:Z.toolCallId,data:H.value}),H=await X.next();K=H.value}else K=await X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"ok",output:K}}catch(X){if(X instanceof k||this.controller.signal.aborted)throw new k;if(X instanceof T)throw X;return{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"error",error:{code:"tool_error",message:X instanceof Error?X.message:String(X),toolCallId:Z.toolCallId,retryable:!0}}}}nestedRunner(Q,$,Z){let G=new qQ(()=>$.nested,()=>$.nested=[]);return async(J,W={})=>{let{at:Y,recorded:V,write:X}=G.next();if(V){let K=P9(V,J,W);if(K)throw Error(`Nested run ${Y} 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(V.finishReason!=="awaiting-input")return{runId:V.runId,agent:V.agent,messages:V.messages,finishReason:V.finishReason??"stop",usage:V.usage??t(),output:D6(V.messages),nested:V}}return this.runNested(Q,$,J,W,X,V,Z?.answers??[])}}async runNested(Q,$,Z,G,J,W,Y){let V=[...this.chain,Z.name];if(this.chain.includes(Z.name))throw Error(`"${Z.name}" is already running further up this chain: ${V.join(" -> ")}. An agent cannot run itself, directly or through another agent.`);let X=this.depth+1;if(X>this.maxDepth)throw Error(`Nested agent runs are ${this.maxDepth} deep at most and this one would be ${X}: ${V.join(" -> ")}. Raise maxDepth on the agent at the root of the run if the tree is meant to be this deep.`);let K=G.label,H=[...this.pathPrefix,$.toolCallId],B=this.onPending==="deny"?"deny":G.onPending??"escalate",D=W!==void 0,L=D?a(W.messages):new Set,U=D?Y.filter((N)=>{let b=L6(N.path,H);if(b===null)return!1;return L.has(b.length>0?b[0]:N.toolCallId)}):[],z=Z.stream({messages:D?W.messages:G.messages??[],turn:D?{toolResults:U}:G.prompt?{text:G.prompt}:void 0,context:this.context,attachments:this.params.attachments,body:this.params.body,signal:this.controller.signal,threadId:this.params.threadId,instructions:G.instructions,maxOutputTokens:G.maxOutputTokens,temperature:G.temperature,runId:D?W.runId:void 0,nesting:{depth:X,maxDepth:this.maxDepth,chain:V,signingRunId:this.signingRunId,signingPath:H,onPending:B}}),F=[],P=(async()=>{for await(let N of z){if(N.type==="awaiting-input")F=N.pending;this.emit({type:"nested-event",toolCallId:$.toolCallId,runId:z.runId,agent:Z.name,label:K,event:N})}})(),M=(async()=>{let N=await z.result();await P;let b=D?B6(W.messages,N.messages):B6(G.messages??[],N.messages),oQ={runId:z.runId,agent:Z.name,label:K,messages:b,finishReason:N.finishReason,usage:D?r(W.usage??t(),N.usage):N.usage,...N.finishReason==="awaiting-input"?{signature:Z6({runId:this.signingRunId,path:H,nestedRunId:z.runId,open:[...a(b)],input:$.input})}:{}};return J(oQ),this.usage=r(this.usage,N.usage),{result:N,record:oQ}})(),q=M.then(()=>{return},()=>{return});this.nestedSettling.add(q);let O,S;try{({result:O,record:S}=await M)}finally{this.nestedSettling.delete(q)}if(this.controller.signal.aborted)throw new k;if(O.finishReason==="awaiting-input"){if(F.length===0)throw Error(`"${Z.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 T({pending:F,path:H,nested:S})}return{runId:S.runId,agent:Z.name,messages:S.messages,finishReason:O.finishReason,usage:S.usage??t(),output:O.output??D6(S.messages),nested:S}}addResult(Q,$){Q.content.push($),this.emit({type:"tool-result",messageId:Q.id,part:$})}toolFiles(Q){let $=this.params.attachments??null,Z=new qQ(()=>Q.attachments,()=>Q.attachments=[],()=>({failed:!0})),G=()=>{if(!$)throw new w("This request has no attachment scope, so a tool cannot store or read files on it. `attachmentScope()` returned null \u2014 put the chat route behind authentication, send a `threadId`, or override `attachmentScope()` on the controller.");return $},J=async(X,K,H)=>{let B=G(),D=K.mimeType||X.type||"",L=K.name??(X instanceof File?X.name:"attachment"),U;if(K.showModel){let F=this.config.provider;if(!F.capabilities.fileInput)throw Error(`"${String(Q.name)}" asked to show a file to ${F.model}, which does not accept file input. Drop \`showModel\` for this provider, or run this agent on a model that takes files \u2014 \`capabilities.fileInput\` is what says which do.`);U=await F.upload(new File([X],L,{type:D||void 0}))}return{attachment:await B.put(X,{name:L,mimeType:D,fileId:U}),...H?{generated:H}:{},...U?{shown:{fileId:U,messageId:`msg_${crypto.randomUUID()}`,createdAt:new Date().toISOString()}}:{}}},W=(X,K,H)=>{let B=X.generated?"image":"put";if(B===K)return;throw Error(`Attachment ${H} of "${String(Q.name)}" was ${B==="image"?"a generated image":"a stored file"} on the first attempt and is ${K==="image"?"a generated image":"a stored file"} now. ctx.attachments.put, ctx.generateImage and ctx.editImage share one memo indexed by call order within a tool call, so the sequence has to be the same every time this tool runs. Branch on ctx.resumed if it cannot be.`)},Y=async(X,K,H)=>{let{at:B,recorded:D,write:L}=Z.next();if(D&&"attachment"in D){if(W(D,"image",B),D.shown)this.queueShown(Q.toolCallId,D);return{attachment:D.attachment,size:D.generated.size,mimeType:D.attachment.mimeType,usage:D.generated.usage}}let U=await H();this.usage=r(this.usage,U.usage);let z=U.mimeType==="image/jpeg"?"jpg":"png",F=await J(U.image,{name:K.name??`${X.name}.${z}`,mimeType:U.mimeType,...K.showModel?{showModel:!0}:{}},{size:U.size,usage:U.usage});if(L(F),F.shown)this.queueShown(Q.toolCallId,F);return{attachment:F.attachment,size:U.size,mimeType:U.mimeType,usage:U.usage}},V=async(X)=>typeof X==="string"?await G().file(X):X;return{generateImage:(X,K)=>Y(X,K,()=>X.generate({...K,signal:this.controller.signal})),editImage:(X,K)=>Y(X,K,async()=>{let{images:H,mask:B,...D}=K;return await X.edit({...D,images:await Promise.all(H.map(V)),...B?{mask:await V(B)}:{},signal:this.controller.signal})}),attachments:{get:(X)=>G().get(X),read:(X)=>G().read(X),file:(X)=>G().file(X),put:async(X,K={})=>{let{at:H,recorded:B,write:D}=Z.next();if(B&&"attachment"in B){W(B,"put",H);let U=j9(B,X,K);if(U)throw Error(`Attachment ${H} of "${String(Q.name)}" ${U}. `+"ctx.attachments.put is memoized by call index within a tool call, so a body whose put calls depend on a condition that changed between turns cannot be replayed \u2014 the model would be shown a file under an id that names different bytes. "+"Make the sequence of put calls the same every time this tool runs, or branch on ctx.resumed.");if(B.shown)this.queueShown(Q.toolCallId,B);return B.attachment}let L=await J(X,K);if(D(L),L.shown)this.queueShown(Q.toolCallId,L);return L.attachment}}}}toolTurn(Q){let $=this.history.findIndex((W)=>W.id===Q),Z=z6(this.history),G;for(let W=$-1;W>=0;W--){let Y=this.history[W];if(Y.role!=="user"||Z.has(Y.id))continue;G=Y;break}let J=[];for(let W of G?.content??[]){if(W.type!=="file")continue;let Y=W.attachmentId;if(typeof Y!=="string"||!Y.startsWith(C))continue;if(!J.includes(Y))J.push(Y)}return Object.freeze({attachments:Object.freeze(J)})}queueShown(Q,$){let Z=$.shown;if(!Z)return;let G=this.shownQueue.get(Q)??[];if(G.some((J)=>J.id===Z.messageId))return;G.push({id:Z.messageId,role:"user",content:[{type:"file",fileId:Z.fileId,name:$.attachment.name,mimeType:$.attachment.mimeType,attachmentId:$.attachment.id}],createdAt:Z.createdAt,finishReason:"stop"}),this.shownQueue.set(Q,G)}async settleShown(Q){let $=this.shownQueue.get(Q);if(!$||$.length===0)return;if(this.shownQueue.delete(Q),this.ended||this.controller.signal.aborted)return;for(let Z of $){if(this.history.some((G)=>G.id===Z.id))continue;this.history.push(Z),this.produced.push(Z),this.emit({type:"message",message:Z}),this.unreported.add(Z)}}historyForProvider(Q){let $=this.history.filter((W)=>W!==Q),Z=z6($),G=[];for(let W of $){if(!Z.has(W.id))continue;for(let Y of W.content)if(Y.type==="file")G.push(Y)}if(G.length<=F6)return $;let J=new Set(G.slice(0,G.length-F6));return $.map((W)=>{if(!W.content.some((Y)=>Y.type==="file"&&J.has(Y)))return W;return{...W,content:W.content.map((Y)=>Y.type==="file"&&J.has(Y)?{type:"text",text:`[A ${Y.mimeType||"file"} produced by a tool (attachment ${Y.attachmentId}) was attached here and has been dropped from this request: only the most recent tool-produced file is kept attached, to keep the context bounded. Call the tool again if you need to look at it.]`}:Y)}})}async ingestTurn(){let Q=this.params.turn,$=this.openCalls(),Z=[];if($.length>0){let G=new Set,J=new Set,W=new Map;for(let Y of Q?.toolResults??[]){let V=`${(Y.path??[]).join("/")}#${Y.toolCallId}`;if(J.has(V))continue;J.add(V);let X=(D)=>this.emit({type:"error",error:{code:"invalid_tool_result",message:D,toolCallId:Y.toolCallId,retryable:!1}}),K=L6(Y.path,this.pathPrefix);if(K===null){X(`The answer for "${Y.toolCallId}" is addressed to a tool call this run is not inside.`);continue}if(K.length>0){let D=K[0],L=$.find((F)=>F.call.toolCallId===D);if(!L){X(`No pending tool call with id "${D}" to deliver a nested answer to.`);continue}let U=this.parkedBelow(L.call,K,Y.toolCallId);if(U.ok===!1){let F=`The answer for "${Y.toolCallId}" is addressed under "${D}", which`;X(U.reason==="unparked"?`${F} has no sub-agent run waiting on that question.`:U.reason==="expired"?`${F} parked a sub-agent run that has since expired. Ask again.`:`${F} carries a record of a parked sub-agent run the server did not sign.`);continue}let z=W.get(D);if(!z){if(!Y6(U.signature)){X(`The answer for "${Y.toolCallId}" is addressed under "${D}", which has already been re-entered on that record. Ask again.`);continue}z=[],W.set(D,z),G.add(D)}z.push(Y);continue}let H=$.find((D)=>D.call.toolCallId===Y.toolCallId);if(!H){X(`No pending tool call with id "${Y.toolCallId}".`);continue}let B=await this.resolveAnswer(H,Y,Z);if(B===null)continue;if(G.add(Y.toolCallId),B!=="open")this.attachToHistory(H,B),await this.settleShown(Y.toolCallId)}for(let[Y,V]of W){let X=$.find((H)=>H.call.toolCallId===Y),K=await this.reenter(X,V,Z);if(K)this.attachToHistory(X,K),await this.settleShown(Y)}for(let Y of $){if(G.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.reportDeferred()}if(Q&&(Q.text||Q.files&&Q.files.length>0)){let G={id:`msg_${crypto.randomUUID()}`,role:"user",content:[...Q.text?[{type:"text",text:Q.text}]:[],...(Q.files??[]).map((J)=>({type:"file",...J.fileId?{fileId:J.fileId}:{},name:J.name,mimeType:J.mimeType,...J.attachmentId?{attachmentId:J.attachmentId}:{}}))],createdAt:new Date().toISOString(),finishReason:"stop"};this.history.push(G),this.produced.push(G),await this.report(G)}return Z}parkedBelow(Q,$,Z){let G=$.length>1?$[1]:Z,J=[...this.pathPrefix,Q.toolCallId],W=(Q.nested??[]).find((V)=>V.finishReason==="awaiting-input"&&a(V.messages).has(G));if(!W)return{ok:!1,reason:"unparked"};if(typeof W.signature!=="string")return{ok:!1,reason:"unsigned"};let Y=G6(W.signature,{path:J,nestedRunId:W.runId,open:[...a(W.messages)],input:Q.input});if(Y.ok===!1)return{ok:!1,reason:Y.reason==="expired"?"expired":"unsigned"};return{ok:!0,signature:W.signature}}async reenter(Q,$,Z){let G=String(Q.call.name),J=this.config.registry.get(G);if(!J||!J.tool.execute)return{type:"tool-result",toolCallId:Q.call.toolCallId,name:Q.call.name,status:"error",error:{code:"invalid_tool_result",message:`The tool "${G}" no longer exists, so the sub-agent's question cannot be delivered.`,toolCallId:Q.call.toolCallId,retryable:!1}};let W=J.tool.inputSchema.safeParse(Q.call.input);if(W.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 "${G}": ${W.errors.join(", ")}`,toolCallId:Q.call.toolCallId,retryable:!0}};let Y=this.amendCall(Q);Y.input=W.value;try{return await s(this.executeTool(J,Q.message.id,Y,W.value,0,{answers:$}),this.controller.signal)}catch(V){if(V instanceof T)return Z.push(...V.pending),null;throw V}}amendCall(Q){let $=this.amend(Q.message),Z=$.content.indexOf(Q.call),G={...Q.call,nested:(Q.call.nested??[]).map((J)=>({...J})),...Q.call.attachments?{attachments:Q.call.attachments.map((J)=>({...J}))}:{}};if(Z>=0)$.content[Z]=G;return this.unreported.add($),G}openCalls(){let Q=new Set;for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-result")Q.add(G.toolCallId);let $=[];for(let Z of this.history)for(let G of Z.content)if(G.type==="tool-call"&&!Q.has(G.toolCallId))$.push({message:Z,call:G});return $}async resolveAnswer(Q,$,Z){let G=Q.call,J=String(G.name),W=this.config.registry.get(J),Y=(H)=>{return this.emit({type:"error",error:{code:"invalid_tool_result",message:H,toolCallId:G.toolCallId,retryable:!1}}),null};if(!W)return Y(`The tool "${J}" no longer exists, so its answer cannot be checked.`);let V=O6(W.tool);if(!V)return Y(`"${J}" is a server tool with no pending question.`);if(typeof $.signature!=="string"||$.signature.length===0)return Y(`The answer for "${J}" carried no signature.`);let X=d($.signature);if(!X)return Y(`The signature for "${J}" is malformed.`);let K=Q6($.signature,{...this.claimsFor(G.toolCallId,J,V,G.input),runId:X.runId});if(K.ok===!1)return Y(K.reason==="expired"?`The approval for "${J}" has expired. Ask again.`:`The answer for "${J}" does not match the call the server made.`);if(!W6($.signature))return Y(`The answer for "${J}" has already been used. Ask again.`);if("approve"in $){if(V!=="approval")return Y(`"${J}" is answered by the client, not approved.`);if($.approve===!0){let H=this.amendCall(Q);try{return await s(this.executeTool(W,Q.message.id,H,H.input,0),this.controller.signal)}catch(B){if(B instanceof T)return Z.push(...B.pending),"open";throw B}}return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"denied",cause:"refused",reason:$.reason}}if("output"in $){if(V==="approval")return Y(`"${J}" is approved, not answered: the server produces its result.`);let H=W.tool.outputSchema,B=H?H.safeParse($.output):{ok:!0,value:$.output};if(B.ok===!1)return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"error",error:{code:"invalid_tool_result",message:`The answer for "${J}" did not match its output schema: ${B.errors.join(", ")}`,toolCallId:G.toolCallId,retryable:!0}};return{type:"tool-result",toolCallId:G.toolCallId,name:G.name,status:"ok",output:B.value}}return Y(`The answer for "${J}" carried neither an approval nor an output.`)}attachToHistory(Q,$){let Z=this.amend(Q.message);Z.content.push($),this.unreported.add(Z),this.emit({type:"tool-result",messageId:Z.id,part:$})}amend(Q){let $=this.amended.get(Q.id);if($)return $;let Z={...Q,content:[...Q.content]},G=this.history.indexOf(Q);if(G>=0)this.history[G]=Z;return this.produced.push(Z),this.amended.set(Q.id,Z),Z}async reportDeferred(){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.reportDeferred();let Q=this.current;if(Q){let $=new Set(Q.content.filter((Z)=>Z.type==="tool-result").map((Z)=>Z.toolCallId));for(let Z of[...Q.content]){if(Z.type!=="tool-call"||$.has(Z.toolCallId))continue;delete Z.partial,this.addResult(Q,{type:"tool-result",toolCallId:Z.toolCallId,name:Z.name,status:"denied",cause:"stopped",reason:this.stopReason})}}this.finishReason="aborted",await this.finalizeMessage("aborted")}}function O6(Q){if(Q.answeredBy==="client")return Q.inputSchema===SQ?"question":"client";return Q.requiresApproval?"approval":null}function N6(Q){if(!Q||!Q.trim())return{};try{return JSON.parse(Q)}catch{return Q}}function M9(Q){if(Q.length>0)Q[0];return Q}function q9(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type===$){G.text=(G.text??"")+Z;return}Q.content.push($==="text"?{type:"text",text:Z}:{type:"reasoning",text:Z})}function S9(Q,$,Z){let G=Q.content[Q.content.length-1];if(G&&G.type==="reasoning"&&G.id===$){G.text=(G.text??"")+Z;return}Q.content.push($?{type:"reasoning",id:$,text:Z}:{type:"reasoning",text:Z})}function R9(Q,$){return Q.descriptors($).map((Z)=>E.create({name:Z.name,description:Z.description,inputSchema:Z.inputSchema,requiresApproval:Z.requiresApproval,execute:(G,J)=>{let W=e.getStore()?.req;if(!W)throw Error(`"${Z.name}" calls an api route as the user who started this run, and this run was not started inside a request. Run it from an AgentController, or give this agent tools that do not go through the MCP registry.`);return Q.execute({kind:"local",req:W},Z.name,G,J)}}))}function T9(Q){if(Q==="auto")return;let $=/^(\d+)x(\d+)$/.exec(Q);if(!$)throw Error(`An image size is "WIDTHxHEIGHT" or "auto"; got ${JSON.stringify(Q)}.`);let Z=Number($[1]),G=Number($[2]);if(Z%16!==0||G%16!==0)throw Error(`Image size ${Q} is not supported: width and height must both be divisible by 16.`);if(Math.max(Z/G,G/Z)>3)throw Error(`Image size ${Q} is not supported: the maximum aspect ratio is 3:1, either way up.`)}function P6(Q,$){if(Q.size!==void 0)try{T9(Q.size)}catch(Z){throw Error(`${$}: ${Z.message}`)}if(Q.background==="transparent"&&Q.format==="jpeg")throw Error(`${$}: a transparent background needs "png"; JPEG has no alpha channel.`);if(Q.compression!==void 0){let Z=Q.compression;if(!Number.isInteger(Z)||Z<0||Z>100)throw Error(`${$}: compression is an integer from 0 to 100; got ${Z}.`)}}function M6(Q,$){if(Q instanceof File)return Q;let Z=Q.type||"image/png",G=Z==="image/jpeg"?"jpg":Z.split("/")[1]??"png";return new File([Q],`${$}.${G}`,{type:Z})}class kQ{name;provider;settings;constructor(Q){let{name:$,provider:Z,...G}=Q;P6(G,`ImageModel "${$}"`),this.name=$,this.provider=Z,this.settings=G}static create(Q){return new kQ(Q)}async generate(Q){let $=this.merge(Q);return q6(await this.provider.generate({prompt:Q.prompt,...$,signal:Q.signal}))}async edit(Q){let $=this.merge(Q);return q6(await this.provider.edit({prompt:Q.prompt,...$,images:Q.images.map((Z,G)=>M6(Z,`image-${G}`)),...Q.mask?{mask:M6(Q.mask,"mask")}:{},signal:Q.signal}))}merge(Q){let $={...this.settings,...Q.size!==void 0?{size:Q.size}:{},...Q.quality!==void 0?{quality:Q.quality}:{},...Q.background!==void 0?{background:Q.background}:{},...Q.format!==void 0?{format:Q.format}:{},...Q.compression!==void 0?{compression:Q.compression}:{}};return P6($,`ImageModel "${this.name}"`),$}}function q6(Q){return{image:new Blob([Q.bytes],{type:Q.mimeType}),mimeType:Q.mimeType,size:Q.size,usage:Q.usage}}function A(Q){return typeof process>"u"?void 0:process.env?.[Q]}var k9="preview";function S6(Q){let $=Q.trim().replace(/\/+$/,"");if(!$)return"";return`${$.replace(/\/openai(?:\/v1)?$/i,"")}/openai`}function E9(Q){return/^\d{4}-\d{2}-\d{2}/.test(Q)?"":"/v1"}function ZQ(Q,$={}){return{base:(Q.baseURL??A("OPENAI_BASE_URL")??"https://api.openai.com/v1").replace(/\/+$/,""),query:"",headers:async()=>{let G=Q.apiKey??A("OPENAI_API_KEY");return{...G?{authorization:`Bearer ${G}`}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}function A9(Q){let $=Q.baseURL??Q.endpoint??A("AZURE_OPENAI_ENDPOINT");if($)return S6($);let Z=Q.resourceName??A("AZURE_OPENAI_RESOURCE_NAME")??A("AZURE_RESOURCE_NAME");return Z?S6(`https://${Z.trim()}.cognitiveservices.azure.com`):""}function GQ(Q,$={}){let Z=Q.apiVersion??A("AZURE_OPENAI_API_VERSION")??k9;return{base:`${A9(Q)}${E9(Z)}`,query:`?api-version=${encodeURIComponent(Z)}`,headers:async()=>{if(Q.getToken)return{authorization:`Bearer ${await Q.getToken()}`,...Q.headers};let G=Q.apiKey??A("AZURE_OPENAI_API_KEY");return{...G?{"api-key":G}:{},...Q.headers}},timeoutMs:Q.timeoutMs??$.timeoutMs??120000,maxRetries:Q.maxRetries??2}}class JQ extends Error{status;body;requestId;constructor(Q,$,Z){super(`Provider request failed with status ${Q}: ${x9($)}`);this.name="ProviderHttpError",this.status=Q,this.body=$,this.requestId=Z}}class WQ extends Error{timeoutMs;constructor(Q){super(`Provider request timed out after ${Q}ms`);this.name="ProviderTimeoutError",this.timeoutMs=Q}}function x9(Q){let $=R6(Q);if($?.message)return $.message;if(typeof Q==="string")return Q.slice(0,500);return"no error body"}function R6(Q){if(!Q||typeof Q!=="object")return null;let $=Q,G=$.error&&typeof $.error==="object"?$.error:Q;if(typeof G.message!=="string"&&typeof G.code!=="string"&&typeof G.type!=="string")return null;let J=G.innererror?.code??G.code;return{message:G.message,type:G.type,code:J,param:G.param}}function _(Q){if(Q instanceof WQ)return{code:"provider_error",message:Q.message,retryable:!0};if(f9(Q))return{code:"aborted",message:"The request was aborted.",retryable:!1};if(Q instanceof JQ)return b9(Q.status,R6(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 b9(Q,$,Z){let G=$?.message??Z,J=($?.code??"").toLowerCase(),W=($?.type??"").toLowerCase(),Y=`${J} ${W} ${G}`.toLowerCase();if(Q===429){let V=J==="insufficient_quota"||Y.includes("quota");return{code:"rate_limited",message:G,retryable:!V}}if(Q>=500||Q===408||Q===409)return{code:"provider_error",message:G,retryable:!0};if(I9(Y))return{code:"context_length_exceeded",message:G,retryable:!1};if(w9(Y))return{code:"content_filtered",message:G,retryable:!1};if($?.param?.startsWith("tools")||Y.includes("invalid schema for function"))return{code:"invalid_tool_input",message:G,retryable:!1};return{code:"provider_error",message:G,retryable:!1}}function I9(Q){return Q.includes("context_length_exceeded")||Q.includes("maximum context length")||Q.includes("context window")||Q.includes("reduce the length")}function w9(Q){return Q.includes("content_filter")||Q.includes("content_policy_violation")||Q.includes("responsibleaipolicyviolation")||Q.includes("content management policy")}function f9(Q){if(!Q||typeof Q!=="object")return!1;let $=Q;return $.name==="AbortError"||$.code==="ABORT_ERR"}var v9=500,k6=20000;function y9(Q,$){if(!Q)return;let Z=Q.trim();if(/^\d+(\.\d+)?$/.test(Z))return Math.max(0,Number(Z)*1000);let G=Date.parse(Z);if(Number.isNaN(G))return;return Math.max(0,G-$)}function T6(Q,$){let Z=Math.min(k6,v9*2**Q);return Math.round(Z*(0.5+$()*0.5))}function h9(Q){return Q===429||Q===408||Q===409||Q>=500}function u9(Q,$){return h9(Q)&&_($).retryable}function E6(Q){return Q.reason??new DOMException("The operation was aborted.","AbortError")}function g9(Q,$){return new Promise((Z,G)=>{let J=setTimeout(Z,Q);$?.addEventListener("abort",()=>{clearTimeout(J),G(E6($))},{once:!0})})}async function g(Q,$,Z){let G=Z.fetchImpl??((H,B)=>fetch(H,B)),J=Z.sleep??g9,W=Z.random??Math.random,Y=Z.now??Date.now,V=Math.max(0,Z.maxRetries),X=async(H)=>{let B=Z.signal;if(!B)return await J(H);B.throwIfAborted();let D;try{await Promise.race([J(H,B),new Promise((L,U)=>{D=()=>U(E6(B)),B.addEventListener("abort",D,{once:!0})})])}finally{if(D)B.removeEventListener("abort",D)}},K;for(let H=0;H<=V;H++){Z.signal?.throwIfAborted();let B=new AbortController,D=()=>B.abort(Z.signal?.reason);Z.signal?.addEventListener("abort",D,{once:!0});let L=!1,U=Z.timeoutMs>0?setTimeout(()=>{L=!0,B.abort()},Z.timeoutMs):void 0,z;try{z=await G(Q,{...$,signal:B.signal})}catch(q){if(U!==void 0)clearTimeout(U);if(Z.signal?.removeEventListener("abort",D),Z.signal?.aborted)throw q;if(K=L?new WQ(Z.timeoutMs):q,L&&Z.retryTimeouts===!1)throw K;if(H===V)throw K;await X(T6(H,W));continue}if(U!==void 0)clearTimeout(U);if(z.ok)return z;Z.signal?.removeEventListener("abort",D);let F=await c9(z),P=new JQ(z.status,F,z.headers.get("x-request-id")??void 0);if(H===V||!u9(z.status,P))throw P;let M=y9(z.headers.get("retry-after"),Y());await X(M===void 0?T6(H,W):Math.min(M,k6)),K=P}throw K??Error("Provider request failed with no response.")}async function c9(Q){let $;try{$=await Q.text()}catch{return null}try{return JSON.parse($)}catch{return $}}var EQ=300000;function AQ(Q){return{generationsUrl:`${Q.base}/images/generations${Q.query}`,editsUrl:`${Q.base}/images/edits${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}class YQ extends Error{code;retryable;constructor(Q,$={}){super(Q.message,$);this.name="ImageRequestError",this.code=Q.code,this.retryable=Q.retryable}}var m9={png:"image/png",jpeg:"image/jpeg"};function p9(Q){let $=Number(Q?.input_tokens??0),Z=Number(Q?.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q?.total_tokens??$+Z)},J=Q?.input_tokens_details?.image_tokens;if(typeof J==="number")G.imageInputTokens=J;let W=Q?.output_tokens_details?.image_tokens;if(typeof W==="number")G.imageOutputTokens=W;return G}function l9(Q){let $=atob(Q),Z=new Uint8Array($.length);for(let G=0;G<$.length;G++)Z[G]=$.charCodeAt(G);return Z}function d9(Q){let Z=Q?.data?.[0]?.b64_json;if(typeof Z!=="string"||Z.length===0)throw new YQ({code:"provider_error",message:"The provider answered an image call with no base64 image data.",retryable:!1});let G=typeof Q.output_format==="string"?Q.output_format:"png";return{bytes:l9(Z),mimeType:m9[G]??`image/${G}`,size:typeof Q.size==="string"?Q.size:"",...typeof Q.background==="string"?{background:Q.background}:{},usage:p9(Q.usage)}}async function A6(Q,$,Z,G){let J;try{J=await g(Q,$,{maxRetries:Z.maxRetries,timeoutMs:Z.timeoutMs,retryTimeouts:!1,signal:G.signal,fetchImpl:Z.fetchImpl})}catch(W){if(G.signal?.aborted)throw W;throw new YQ(_(W),{cause:W})}return d9(await J.json())}async function x6(Q,$,Z={}){return await A6(Q.generationsUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},Q,Z)}async function b6(Q,$,Z={}){return await A6(Q.editsUrl,{method:"POST",headers:await Q.headers(),body:$},Q,Z)}class XQ{static models(){return[]}modelName(){return this.model}async generate(Q){return await x6(this.endpoint(),this.body(Q),{signal:Q.signal})}async edit(Q){let $=new FormData;for(let[Z,G]of Object.entries(this.body(Q)))if(G!==void 0)$.set(Z,String(G));for(let Z of Q.images)$.append("image[]",Z,Z.name);if(Q.mask)$.set("mask",Q.mask,Q.mask.name);return await b6(this.endpoint(),$,{signal:Q.signal})}body(Q){return{model:this.modelName(),prompt:Q.prompt,...Q.size?{size:Q.size}:{},...Q.quality?{quality:Q.quality}:{},...Q.background?{background:Q.background}:{},...Q.format?{output_format:Q.format}:{},...Q.compression!==void 0?{output_compression:Q.compression}:{}}}normalizeError(Q){return _(Q)}}var I6=["gpt-image-2","gpt-image-1.5","gpt-image-1"];class xQ extends XQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new xQ(Q,$)}static models(){return I6}endpoint(){return AQ(ZQ(this.config,{timeoutMs:EQ}))}}class bQ extends XQ{model;config;constructor(Q,$={}){super();this.model=Q,this.config=$}static model(Q,$){return new bQ(Q,$)}static models(){return I6}modelName(){return this.config.deployment??this.model}endpoint(){return AQ(GQ(this.config,{timeoutMs:EQ}))}}async function*i9(Q){let $="",Z="",G=[],J,W=()=>{if(G.length===0&&!Z)return null;let X={event:Z,data:G.join(`
16
+ `),id:J};return Z="",G=[],J=void 0,X.data?X:null},Y=(X)=>{let K=X.endsWith("\r")?X.slice(0,-1):X;if(K==="")return W();if(K.startsWith(":"))return null;let H=K.indexOf(":"),B=H===-1?K:K.slice(0,H),D=H===-1?"":K.slice(H+1);if(D.startsWith(" "))D=D.slice(1);if(B==="event")Z=D;else if(B==="data")G.push(D);else if(B==="id")J=D;return null};for await(let X of Q){$+=X;let K=$.indexOf(`
17
17
  `);while(K!==-1){let H=$.slice(0,K);$=$.slice(K+1);let B=Y(H);if(B)yield B;K=$.indexOf(`
18
- `)}}if($.length>0){let X=Y($);if(X)yield X}let V=W();if(V)yield V}async function*A6(Q,$={}){let Z=new Map,J=new Set,G=!1;for await(let W of w9(Q)){if(W.data==="[DONE]")break;let Y;try{Y=JSON.parse(W.data)}catch{continue}switch(typeof Y.type==="string"?Y.type:W.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 K=String(X.id??Y.item_id??X.call_id??"");Z.set(K,{callId:String(X.call_id??K),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=Z.get(String(Y.item_id??""));if(!X)break;let K=String(Y.delta??"");if(!K)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:K,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(Y.item_id??""),K=Z.get(X);if(!K)break;K.done=!0,yield{type:"tool-call",toolCallId:K.callId,name:K.name,args:String(Y.arguments??""),...K.namespace?{namespace:K.namespace}:{}};break}case"response.output_item.done":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let K=String(X.id??Y.item_id??X.call_id??""),H=Z.get(K);if(H?.done)break;let B=(typeof X.namespace==="string"?X.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??K),name:String(X.name??H?.name??""),args:String(X.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let K=v9(X);if(K.loaded.length===0&&K.namespaces.length===0)break;let H=String(X.tool_search_call_id??X.id??"");if(J.has(H))break;J.add(H),yield{type:"tool-search",...K}}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":{G=!0,yield{type:"finish",reason:"stop",usage:IQ(Y.response?.usage)};break}case"response.incomplete":{G=!0;let X=IQ(Y.response?.usage),K=Y.response?.incomplete_details?.reason;if(K==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:f9(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:K==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{G=!0;let X=Y.response?.error??Y.error??Y;yield{type:"error",error:y9(X)},yield{type:"finish",reason:"error",usage:IQ(Y.response?.usage)};break}}if(G)return}if(!G)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:b()}}function v9(Q){let $=[],Z=[];return I6(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:bQ($),namespaces:bQ(Z)}}function I6(Q,$,Z,J){if(!Array.isArray(Q)||J>4)return;for(let G of Q){if(typeof G==="string"){$.push(G);continue}if(!G||typeof G!=="object")continue;let W=G,Y=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",V=W.tools??W.functions;if(Array.isArray(V)){if(Y)Z.push(Y);I6(V,$,Z,J+1);continue}if(Y)$.push(Y)}}function bQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function f9(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let J of Q){if(!J||typeof J!=="object")continue;let G=J,W=G.content_filter_results;if(!W||typeof W!=="object")continue;for(let[Y,V]of Object.entries(W))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${Y} (${String(G.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${bQ(Z).join(", ")}.`}function y9(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function b(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function IQ(Q){if(!Q)return b();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),J={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},G=Q.output_tokens_details?.reasoning_tokens;if(typeof G==="number")J.reasoningTokens=G;let W=Q.input_tokens_details?.cached_tokens;if(typeof W==="number")J.cachedInputTokens=W;return J}async function*b6(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:G,value:W}=await $.read();if(G)break;if(W)yield Z.decode(W,{stream:!0})}let J=Z.decode();if(J)yield J}finally{$.releaseLock()}}function wQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*vQ(Q,$,Z){let J;try{J=await h(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(G){let W=j(G);if(W.code!=="aborted")yield{type:"error",error:W};yield{type:"finish",reason:W.code==="aborted"?"aborted":"error",usage:b()};return}try{yield*A6(b6(J.body),{structuredOutput:Z.structuredOutput})}catch(G){let W=j(G);if(W.code==="aborted"){yield{type:"finish",reason:"aborted",usage:b()};return}yield{type:"error",error:W},yield{type:"finish",reason:"error",usage:b()}}}async function fQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let G=await(await h(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!G?.id)throw Error("The provider accepted the upload but returned no file id.");return G.id}function yQ(Q){let $=h9(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=u9($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:w6(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:w6(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function w6(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function h9(Q){return Q.trim().toLowerCase()}function u9(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function hQ(Q,$){let{capabilities:Z}=$,J={model:$.model,input:g9(Q.messages,Z),stream:!0};if(Q.systemPrompt)J.instructions=Q.systemPrompt;let G=s9(Q.tools,Z);if(G.length>0){if(J.tools=G,!Z.parallelToolCalls)J.parallel_tool_calls=!1}if(Q.output)J.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)J.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")J.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")J.max_output_tokens=Q.maxOutputTokens;return J}function g9(Q,$){let Z=[];for(let J of Q){let G=J.role,W=[],Y=()=>{if(W.length===0)return;Z.push({type:"message",role:G,content:W}),W=[]};for(let V of J.content??[])switch(V.type){case"text":{if(!V.text)break;W.push(XQ(G,V.text));break}case"output":{if(V.partial)break;W.push(XQ(G,JSON.stringify(V.value)));break}case"file":{if(G==="assistant")break;let X=p9(V);if(!$.fileInput){if(X)W.push(XQ(G,v6(V,!1)));break}if(V.fileId?.startsWith(N))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!X)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X)W.push(XQ(G,v6(V,!!V.fileId)));if(V.fileId)W.push(l9(V));break}case"reasoning":{Y();let X=n9(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;Y(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:o9(V)});break}}Y()}return m9(Z)}var c9="No result was recorded for this tool call. Assume it did not complete.";function m9(Q){let $=new Set,Z=new Set,J=[];for(let W of Q){if(W.type==="function_call"){let Y=String(W.call_id);if($.has(Y))continue;$.add(Y)}else if(W.type==="function_call_output"){let Y=String(W.call_id);if(!$.has(Y)||Z.has(Y))continue;Z.add(Y)}J.push(W)}if(Z.size===$.size)return J;let G=[];for(let W of J){if(G.push(W),W.type!=="function_call")continue;let Y=String(W.call_id);if(Z.has(Y))continue;Z.add(Y),G.push({type:"function_call_output",call_id:Y,output:c9})}return G}function XQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function p9(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(N)?$:void 0}function v6(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let J=`attachment ${Z.join(" ")}`;return $?`[${J}]`:`[${J} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function l9(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":d9(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function d9(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&i9.has($[1])}var i9=new Set(["jpeg","jpg","png","gif","webp"]);function n9(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function o9(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 f6(Q){return Array.isArray(Q.tools)}function s9(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let G=[];for(let W of Q)if(f6(W))for(let Y of W.tools)G.push(VQ(Y,!1));else G.push(VQ(W,!1));return G}let Z=[],J=!1;for(let G of Q)if(f6(G)){let W=G.tools.map((Y)=>{if(Y.deferred)J=!0;return VQ(Y,!0)});Z.push({type:"namespace",name:G.name,description:G.description,tools:W})}else{if(G.deferred)J=!0;Z.push(VQ(G,!0))}if(J)Z.push({type:"tool_search"});return Z}function VQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class KQ{static models(){return[]}normalizeError(Q){return j(Q)}}var y6=["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 uQ extends KQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=yQ(Q),this.config=$}static model(Q,$){return new uQ(Q,$)}static models(){return y6}stream(Q){let $=hQ(Q,{model:this.model,capabilities:this.capabilities});return vQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return fQ(this.endpoint(),Q)}endpoint(){return wQ($Q(this.config))}}class gQ extends KQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=yQ(Q),this.config=$}static model(Q,$){return new gQ(Q,$)}static models(){return y6}stream(Q){let $=hQ(Q,{model:this.deployment(),capabilities:this.capabilities});return vQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return fQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return wQ(ZQ(this.config))}}class w extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class u extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class HQ{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 Z={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,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}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 Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new u(Q);if($!==void 0&&$<Z.lostBefore)throw new w(Q,$,Z.lostBefore);let J=Z.frames[0]?.seq;return this.drain(Z,Q,$??J??Z.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 Z=Promise.resolve();try{for await(let J of Q.run.frames()){if(Q.frames.push(J),Q.lastSeq=J.seq,Q.frames.length>this.maxFrames){let W=Q.frames.shift();if(W)Q.lostBefore=W.seq+1}this.notify(Q);let G=$.onEvent;if(G)Z=Z.then(()=>G(J.event)).catch((W)=>h6($,W))}}catch(J){h6($,J)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let J=Z;while(!0){let G=Q.version;for(;;){if(J<Q.lostBefore)throw new w($,J,Q.lostBefore);let W=Q.frames,Y=W[0]?.seq;if(Y===void 0)break;let V=Math.max(0,J-Y);if(V>=W.length)break;let X=W[V];yield X,J=X.seq+1}if(Q.ended&&J>Q.lastSeq)return;await this.wait(Q,G)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var cQ=new HQ;function h6(Q,$){try{Q.onInternalError?.($)}catch{}}class BQ{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 G=Z.messages.findIndex((W)=>W.id===J.id);if(G===-1)Z.messages.push(J);else Z.messages[G]=J}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 mQ=new BQ;var t9=p6,UQ=new Map,u6=new WeakMap,DQ=new Map;class d6 extends t9{static kind="agent-controller";store=mQ;liveRuns=cQ;attachments=n;attachmentStorage=l6;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new g){let $=await pQ(Q);if($.error)return zQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:void 0,G=Q$(Z);if(G.error)return zQ({body:{},error:G.error});let W=G.turn,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!J)return _(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=Y?{cancelled:!1}:null;if(V)DQ.set(Y,V);let X=async()=>{let K;if(J){let C=await this.store.loadThread(J);if(!C)return _(404,{code:"thread_not_found",message:`Thread ${J} does not exist here, or has expired.`});K=C}else K=Array.isArray(Z.messages)?Z.messages:[];let H=r9(Z),B=await this.instructions(Q,{body:H})||void 0,U=await this.context(Q,{body:H}),L=await this.attachmentsFor(Q,J);if(V?.cancelled)return c6();let D=this.agent.stream({messages:K,turn:W,threadId:J,instructions:B,context:U,attachments:L,body:H}),z={req:Q,runId:D.runId,threadId:J},F=this.liveRuns.register(D,{threadId:J,clientRunId:Y,onEvent:(C)=>this.dispatchEvent(C,z),onInternalError:(C)=>this.reportHookFailure(C)}),{stored:P,hooks:M}=this.persistRun(D,z,F);return u6.set(D,P),Q.ctx?.()?.waitUntil(M),D.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:J}),V?.cancelled)return c6();return J?await this.withThread(J,X):await X()}finally{if(V&&DQ.get(Y)===V)DQ.delete(Y)}}async withThread(Q,$){let Z=UQ.get(Q)??Promise.resolve(),J,G=new Promise((Y)=>{J=Y}),W=Z.then(()=>G);UQ.set(Q,W),await Z;try{let Y=await this.liveRuns.find({threadId:Q}),V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await u6.get(V);return await $()}finally{if(J(),UQ.get(Q)===W)UQ.delete(Q)}}async attach(Q=new g){let $=await pQ(Q);if($.error)return zQ($);let Z=$.body,J=typeof Z.threadId==="string"?Z.threadId:J$(Q,"threadId");if(!J)return _(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 G=await this.liveRuns.find({threadId:J});if(!G)return _(404,{code:"no_live_run",message:`No run in progress for thread ${J} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,Y=W&&W!==G.runId?void 0:Z$(Q,Z);try{return Y6(this.liveRuns.replay(G.runId,Y))}catch(V){if(V instanceof w)return _(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof u)return _(404,{code:V.code,message:V.message});throw V}}async stop(Q=new g){let $=await pQ(Q);if($.error)return zQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let J=typeof Z.runId==="string"?Z.runId:void 0;if(!J&&typeof Z.clientRunId==="string"){if(J=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!J){let W=DQ.get(Z.clientRunId);if(W)return W.cancelled=!0,{stopped:!0}}}if(!J&&typeof Z.threadId==="string")J=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let G=J?this.liveRuns.get(J):null;if(!G)return{stopped:!1};return G.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,J=Z?.id??Z?.publicId;if(J!==void 0&&J!==null&&String(J)!=="")return{key:`user:${String(J)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new f(this.attachments,this.attachmentStorage,Z)}async upload(Q=new g){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",G=Z.type||"application/octet-stream",W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0});let Y=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,V=await this.attachmentDestination(Z,Q),X=G$(V,$.get("destination")),K=await this.attachmentScope(Q,Y),H=X!=="provider"&&!K;if(H){if(X==="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()`.');W$()}if(X==="provider"||!K){let F={fileId:await this.agent.provider.upload(Z),name:J,mimeType:G,size:Z.size,destination:"provider"};if(H)F.downgraded="no_scope";return F}let B=CQ(),U=await this.attachmentStorage.put({name:jQ(B,J),body:Z,contentType:G}),L=X==="both"?await this.agent.provider.upload(Z):void 0,D={id:B,scopeKey:K.key,fileId:L,objectName:U,name:J,mimeType:G,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(K,D),{fileId:L,attachmentId:B,name:J,mimeType:G,size:Z.size,destination:X}}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}}persistRun(Q,$,Z){let J=Promise.resolve(),G=(async()=>{let Y;try{Y=await Q.result()}catch(X){J=this.safely(()=>this.onError({code:"unknown",message:X instanceof Error?X.message:String(X),retryable:!1},$));return}let V=Y.messages;if($.threadId&&V.length>0)try{await this.store.appendMessages($.threadId,V)}catch(X){this.reportHookFailure(X)}J=this.notifyRun(Y,V,$)})(),W=G.then(()=>X$(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:G,hooks:W}}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 g6=["turn","clientRunId","threadId","messages"],a9=["text","files","toolResults"];function r9(Q){let $=i6(Q)?g6:[...g6,...a9],Z={};for(let[J,G]of Object.entries(Q)){if($.includes(J))continue;Object.defineProperty(Z,J,{value:G,writable:!0,enumerable:!0,configurable:!0})}return Z}async function pQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!e9($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let J;try{J=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(J===null||typeof J!=="object"||Array.isArray(J))return{body:{},error:"The request body must be a JSON object."};return{body:J}}function e9(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function zQ(Q){return _(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function i6(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function Q$(Q){let $=i6(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let J=$$($.files);if(typeof J==="string")return{error:J};Z.files=J}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function $$(Q){let $=[];for(let[Z,J]of Q.entries()){let G=`turn.files[${Z}]`;if(!J||typeof J!=="object"||Array.isArray(J))return`${G} must be an object.`;let W={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=J[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${G}.${H} must be a string.`;W[H]=B}let{fileId:Y,attachmentId:V,name:X,mimeType:K}=W;if(Y?.startsWith(N))return`${G}.fileId holds a gemi attachment id (${Y}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(N))return`${G}.attachmentId is not a gemi attachment id: it must start with "${N}".`;if(!Y&&!V)return`${G} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...Y?{fileId:Y}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...K!==void 0?{mimeType:K}:{}})}return $}function Z$(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 J$(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function c6(){return _(409,{code:"stopped",message:"The turn was stopped before it started."})}function _(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function G$(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 m6=!1;function W$(){if(m6)return;m6=!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 Y$=2147483647;function X$(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=Y$))return Z;let J,G=new Promise((W)=>{J=setTimeout(W,$)});return Promise.race([Z,G]).finally(()=>clearTimeout(J))}export{z9 as toAgentTools,e as supportsStrict,V$ as s,cQ as liveRuns,n as defaultAttachmentStore,mQ as defaultAgentStore,QQ as ToolNamespace,SQ as Skill,f as ScopedAttachments,y as SKILLS_NAMESPACE,R as PendingEscalation,uQ as OpenAIProvider,EQ as OpenAIImageProvider,HQ as MemoryLiveRuns,i as MemoryAttachmentStore,BQ as MemoryAgentStore,u as LiveRunNotFoundError,I as InvalidAttachmentScopeError,WQ as ImageRequestError,YQ as ImageProvider,TQ as ImageModel,w as FrameCursorEvictedError,gQ as AzureOpenAIProvider,AQ as AzureOpenAIImageProvider,v as AttachmentNotFoundError,k as AgentTool,KQ as AgentProvider,d6 as AgentController,RQ as Agent};
18
+ `)}}if($.length>0){let X=Y($);if(X)yield X}let V=W();if(V)yield V}async function*w6(Q,$={}){let Z=new Map,G=new Set,J=!1;for await(let W of i9(Q)){if(W.data==="[DONE]")break;let Y;try{Y=JSON.parse(W.data)}catch{continue}switch(typeof Y.type==="string"?Y.type:W.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 K=String(X.id??Y.item_id??X.call_id??"");Z.set(K,{callId:String(X.call_id??K),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=Z.get(String(Y.item_id??""));if(!X)break;let K=String(Y.delta??"");if(!K)break;yield{type:"tool-call-delta",toolCallId:X.callId,name:X.name,argsDelta:K,...X.namespace?{namespace:X.namespace}:{}};break}case"response.function_call_arguments.done":{let X=String(Y.item_id??""),K=Z.get(X);if(!K)break;K.done=!0,yield{type:"tool-call",toolCallId:K.callId,name:K.name,args:String(Y.arguments??""),...K.namespace?{namespace:K.namespace}:{}};break}case"response.output_item.done":{let X=Y.item;if(!X)break;if(X.type==="function_call"){let K=String(X.id??Y.item_id??X.call_id??""),H=Z.get(K);if(H?.done)break;let B=(typeof X.namespace==="string"?X.namespace:"")||H?.namespace;if(yield{type:"tool-call",toolCallId:String(X.call_id??K),name:String(X.name??H?.name??""),args:String(X.arguments??""),...B?{namespace:B}:{}},H)H.done=!0;break}if(X.type==="tool_search_call"||X.type==="tool_search_output"){let K=o9(X);if(K.loaded.length===0&&K.namespaces.length===0)break;let H=String(X.tool_search_call_id??X.id??"");if(G.has(H))break;G.add(H),yield{type:"tool-search",...K}}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":{J=!0,yield{type:"finish",reason:"stop",usage:IQ(Y.response?.usage)};break}case"response.incomplete":{J=!0;let X=IQ(Y.response?.usage),K=Y.response?.incomplete_details?.reason;if(K==="content_filter"){yield{type:"error",error:{code:"content_filtered",message:n9(Y.response?.content_filters),retryable:!1}},yield{type:"finish",reason:"error",usage:X};break}yield{type:"finish",reason:K==="max_output_tokens"?"length":"stop",usage:X};break}case"response.failed":case"error":{J=!0;let X=Y.response?.error??Y.error??Y;yield{type:"error",error:s9(X)},yield{type:"finish",reason:"error",usage:IQ(Y.response?.usage)};break}}if(J)return}if(!J)yield{type:"error",error:{code:"provider_error",message:"The provider stream ended without a terminal event.",retryable:!0}},yield{type:"finish",reason:"error",usage:f()}}function o9(Q){let $=[],Z=[];return f6(Q.results??Q.tools??Q.loaded??Q.output,$,Z,0),{loaded:wQ($),namespaces:wQ(Z)}}function f6(Q,$,Z,G){if(!Array.isArray(Q)||G>4)return;for(let J of Q){if(typeof J==="string"){$.push(J);continue}if(!J||typeof J!=="object")continue;let W=J,Y=typeof W.name==="string"?W.name:typeof W.tool_name==="string"?W.tool_name:"",V=W.tools??W.functions;if(Array.isArray(V)){if(Y)Z.push(Y);f6(V,$,Z,G+1);continue}if(Y)$.push(Y)}}function wQ(Q){return Q.filter(($,Z)=>Q.indexOf($)===Z)}function n9(Q){if(!Array.isArray(Q))return"The provider's content filter blocked this request.";let Z=[];for(let G of Q){if(!G||typeof G!=="object")continue;let J=G,W=J.content_filter_results;if(!W||typeof W!=="object")continue;for(let[Y,V]of Object.entries(W))if(V&&typeof V==="object"&&V.filtered===!0)Z.push(`${Y} (${String(J.source_type??"unknown")})`)}return Z.length===0?"The provider's content filter blocked this request.":`The provider's content filter blocked this request. Categories: ${wQ(Z).join(", ")}.`}function s9(Q){let $=typeof Q?.message==="string"?Q.message:"The provider stream failed.",Z=String(Q?.code??"").toLowerCase();if(Z==="rate_limit_exceeded")return{code:"rate_limited",message:$,retryable:!0};if(Z==="context_length_exceeded")return{code:"context_length_exceeded",message:$,retryable:!1};if(Z.includes("content_filter"))return{code:"content_filtered",message:$,retryable:!1};return{code:"provider_error",message:$,retryable:!0}}function f(){return{inputTokens:0,outputTokens:0,totalTokens:0}}function IQ(Q){if(!Q)return f();let $=Number(Q.input_tokens??0),Z=Number(Q.output_tokens??0),G={inputTokens:$,outputTokens:Z,totalTokens:Number(Q.total_tokens??$+Z)},J=Q.output_tokens_details?.reasoning_tokens;if(typeof J==="number")G.reasoningTokens=J;let W=Q.input_tokens_details?.cached_tokens;if(typeof W==="number")G.cachedInputTokens=W;return G}async function*v6(Q){if(!Q)return;let $=Q.getReader(),Z=new TextDecoder;try{while(!0){let{done:J,value:W}=await $.read();if(J)break;if(W)yield Z.decode(W,{stream:!0})}let G=Z.decode();if(G)yield G}finally{$.releaseLock()}}function fQ(Q){return{responsesUrl:`${Q.base}/responses${Q.query}`,filesUrl:`${Q.base}/files${Q.query}`,headers:Q.headers,timeoutMs:Q.timeoutMs,maxRetries:Q.maxRetries}}async function*vQ(Q,$,Z){let G;try{G=await g(Q.responsesUrl,{method:"POST",headers:{...await Q.headers(),"content-type":"application/json"},body:JSON.stringify($)},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,signal:Z.signal,fetchImpl:Q.fetchImpl})}catch(J){let W=_(J);if(W.code!=="aborted")yield{type:"error",error:W};yield{type:"finish",reason:W.code==="aborted"?"aborted":"error",usage:f()};return}try{yield*w6(v6(G.body),{structuredOutput:Z.structuredOutput})}catch(J){let W=_(J);if(W.code==="aborted"){yield{type:"finish",reason:"aborted",usage:f()};return}yield{type:"error",error:W},yield{type:"finish",reason:"error",usage:f()}}}async function yQ(Q,$){let Z=new FormData;Z.set("purpose","user_data"),Z.set("file",$);let J=await(await g(Q.filesUrl,{method:"POST",headers:await Q.headers(),body:Z},{maxRetries:Q.maxRetries,timeoutMs:Q.timeoutMs,fetchImpl:Q.fetchImpl})).json();if(!J?.id)throw Error("The provider accepted the upload but returned no file id.");return J.id}function hQ(Q){let $=t9(Q);if($.startsWith("gpt-3.5")||$.startsWith("text-")||$.startsWith("davinci"))return{reasoning:!1,structuredOutput:!1,fileInput:!1,parallelToolCalls:!0,toolSearch:!1};let Z=r9($);if(Z?.kind==="o")return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:Z.major>1,toolSearch:y6(Z)};if(Z?.kind==="gpt")return{reasoning:Z.major>=5,structuredOutput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),fileInput:Z.major>4||$.startsWith("gpt-4o")||$.startsWith("gpt-4.1"),parallelToolCalls:!0,toolSearch:y6(Z)};return{reasoning:!0,structuredOutput:!0,fileInput:!0,parallelToolCalls:!0,toolSearch:!0}}function y6(Q){if(Q.kind==="o")return Q.major>=5;return Q.major>5||Q.major===5&&Q.minor>=2}function t9(Q){return Q.trim().toLowerCase()}function r9(Q){let $=/^gpt-(\d+)(?:\.(\d+))?/.exec(Q);if($?.[1])return{kind:"gpt",major:Number($[1]),minor:Number($[2]??0)};let Z=/^o(\d+)(?:[-.]|$)/.exec(Q);if(Z?.[1])return{kind:"o",major:Number(Z[1]),minor:0};return null}function uQ(Q,$){let{capabilities:Z}=$,G={model:$.model,input:a9(Q.messages,Z),stream:!0};if(Q.systemPrompt)G.instructions=Q.systemPrompt;let J=X$(Q.tools,Z);if(J.length>0){if(G.tools=J,!Z.parallelToolCalls)G.parallel_tool_calls=!1}if(Q.output)G.text={format:{type:"json_schema",name:Q.output.name,schema:Q.output.schema,strict:Q.output.strict}};if(Q.reasoning&&Z.reasoning)G.reasoning={effort:Q.reasoning,summary:"auto"};if(typeof Q.temperature==="number")G.temperature=Q.temperature;if(typeof Q.maxOutputTokens==="number")G.max_output_tokens=Q.maxOutputTokens;return G}function a9(Q,$){let Z=[];for(let G of Q){let J=G.role,W=[],Y=()=>{if(W.length===0)return;Z.push({type:"message",role:J,content:W}),W=[]};for(let V of G.content??[])switch(V.type){case"text":{if(!V.text)break;W.push(VQ(J,V.text));break}case"output":{if(V.partial)break;W.push(VQ(J,JSON.stringify(V.value)));break}case"file":{if(J==="assistant")break;let X=$$(V);if(!$.fileInput){if(X)W.push(VQ(J,h6(V,!1)));break}if(V.fileId?.startsWith(C))throw Error(`FilePart.fileId holds a gemi attachment id (${V.fileId}). That field is the *provider's* file id, from \`fileId\` on the upload response; the \`attachmentId\` goes in \`FilePart.attachmentId\`, is shown to the model as text, and is resolved by a tool through \`ctx.attachments\`.`);if(!V.fileId&&!X)throw Error("FilePart.fileId is empty and there is no `attachmentId` either. `fileId` is the *provider's* file id and `attachmentId` is gemi's (`gemi_att_\u2026`), both from the upload response; an upload always answers at least one, so a part with neither was built from something other than that answer.");if(X)W.push(VQ(J,h6(V,!!V.fileId)));if(V.fileId)W.push(Z$(V));break}case"reasoning":{Y();let X=W$(V);if(X)Z.push(X);break}case"tool-call":{if(V.partial)break;Y(),Z.push({type:"function_call",call_id:V.toolCallId,name:String(V.name),arguments:JSON.stringify(V.input??{})});break}case"tool-result":{Y(),Z.push({type:"function_call_output",call_id:V.toolCallId,output:Y$(V)});break}}Y()}return Q$(Z)}var e9="No result was recorded for this tool call. Assume it did not complete.";function Q$(Q){let $=new Set,Z=new Set,G=[];for(let W of Q){if(W.type==="function_call"){let Y=String(W.call_id);if($.has(Y))continue;$.add(Y)}else if(W.type==="function_call_output"){let Y=String(W.call_id);if(!$.has(Y)||Z.has(Y))continue;Z.add(Y)}G.push(W)}if(Z.size===$.size)return G;let J=[];for(let W of G){if(J.push(W),W.type!=="function_call")continue;let Y=String(W.call_id);if(Z.has(Y))continue;Z.add(Y),J.push({type:"function_call_output",call_id:Y,output:e9})}return J}function VQ(Q,$){return{type:Q==="assistant"?"output_text":"input_text",text:$}}function $$(Q){let $=Q.attachmentId;return typeof $==="string"&&$.startsWith(C)?$:void 0}function h6(Q,$){let Z=[`id=${JSON.stringify(Q.attachmentId)}`];if(Q.name)Z.push(`name=${JSON.stringify(Q.name)}`);if(Q.mimeType)Z.push(`mimeType=${JSON.stringify(Q.mimeType)}`);let G=`attachment ${Z.join(" ")}`;return $?`[${G}]`:`[${G} \u2014 its contents are not shown to you; a tool can read the file by this id]`}function Z$(Q){let $=Q.mimeType?.trim().toLowerCase()??"";return{type:($?$.startsWith("image/")&&$!=="image/svg+xml":G$(Q.name))?"input_image":"input_file",file_id:Q.fileId}}function G$(Q){let $=/\.([a-z0-9]+)$/.exec(Q?.trim().toLowerCase()??"");return $?.[1]!==void 0&&J$.has($[1])}var J$=new Set(["jpeg","jpg","png","gif","webp"]);function W$(Q){if(!Q.id)return null;let $={type:"reasoning",id:Q.id};return $.summary=Q.text?[{type:"summary_text",text:Q.text}]:[],$}function Y$(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.${$}`;if(Q.cause==="interrupted")return`The run was interrupted (the server stopped) while this tool call was in progress, so its result was lost. It may have run in part or in full: check its effects before repeating it.${$}`;return`The user declined this tool call, so it did not run.${$}`}return`The tool call failed and produced no result. Error (${Q.error?.code??"unknown"}): ${Q.error?.message??"no message"}`}function u6(Q){return Array.isArray(Q.tools)}function X$(Q,$){if(!Q||Q.length===0)return[];if(!$.toolSearch){let J=[];for(let W of Q)if(u6(W))for(let Y of W.tools)J.push(KQ(Y,!1));else J.push(KQ(W,!1));return J}let Z=[],G=!1;for(let J of Q)if(u6(J)){let W=J.tools.map((Y)=>{if(Y.deferred)G=!0;return KQ(Y,!0)});Z.push({type:"namespace",name:J.name,description:J.description,tools:W})}else{if(J.deferred)G=!0;Z.push(KQ(J,!0))}if(G)Z.push({type:"tool_search"});return Z}function KQ(Q,$){let Z={type:"function",name:Q.name,description:Q.description,parameters:Q.parameters,strict:Q.strict};if($&&Q.deferred)Z.defer_loading=!0;return Z}class HQ{static models(){return[]}normalizeError(Q){return _(Q)}}var g6=["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 gQ extends HQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=hQ(Q),this.config=$}static model(Q,$){return new gQ(Q,$)}static models(){return g6}stream(Q){let $=uQ(Q,{model:this.model,capabilities:this.capabilities});return vQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return yQ(this.endpoint(),Q)}endpoint(){return fQ(ZQ(this.config))}}class cQ extends HQ{model;capabilities;config;constructor(Q,$={}){super();this.model=Q,this.capabilities=hQ(Q),this.config=$}static model(Q,$){return new cQ(Q,$)}static models(){return g6}stream(Q){let $=uQ(Q,{model:this.deployment(),capabilities:this.capabilities});return vQ(this.endpoint(),$,{signal:Q.signal,structuredOutput:Boolean(Q.output)})}upload(Q){return yQ(this.endpoint(),Q)}deployment(){return this.config.deployment??this.model}endpoint(){return fQ(GQ(this.config))}}class v extends Error{runId;requested;oldest;code="frame_cursor_evicted";constructor(Q,$,Z){super(`Frame ${$} of run ${Q} has been evicted; the oldest frame still buffered is ${Z}. Reload the thread instead of resuming.`);this.runId=Q;this.requested=$;this.oldest=Z}}class c extends Error{runId;code="live_run_not_found";constructor(Q){super(`No live run ${Q} in this process.`);this.runId=Q}}class BQ{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 Z={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,Z),$.threadId)this.byThread.set($.threadId,Q.runId);if($.clientRunId)this.byClientRun.set($.clientRunId,Q.runId);return this.pump(Z,$)}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 Z=this.runs.get($);if(!Z)return null;return{runId:$,seq:Z.lastSeq}}get(Q){return this.runs.get(Q)?.run??null}replay(Q,$){let Z=this.runs.get(Q);if(!Z)throw new c(Q);if($!==void 0&&$<Z.lostBefore)throw new v(Q,$,Z.lostBefore);let G=Z.frames[0]?.seq;return this.drain(Z,Q,$??G??Z.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 Z=Promise.resolve();try{for await(let G of Q.run.frames()){if(Q.frames.push(G),Q.lastSeq=G.seq,Q.frames.length>this.maxFrames){let W=Q.frames.shift();if(W)Q.lostBefore=W.seq+1}this.notify(Q);let J=$.onEvent;if(J)Z=Z.then(()=>J(G.event)).catch((W)=>c6($,W))}}catch(G){c6($,G)}finally{Q.ended=!0,this.notify(Q),this.scheduleEviction(Q),await Z}}async*drain(Q,$,Z){let G=Z;while(!0){let J=Q.version;for(;;){if(G<Q.lostBefore)throw new v($,G,Q.lostBefore);let W=Q.frames,Y=W[0]?.seq;if(Y===void 0)break;let V=Math.max(0,G-Y);if(V>=W.length)break;let X=W[V];yield X,G=X.seq+1}if(Q.ended&&G>Q.lastSeq)return;await this.wait(Q,J)}}wait(Q,$){if(Q.version!==$)return Promise.resolve();return new Promise((Z)=>Q.wake.add(Z))}notify(Q){Q.version++;let $=Array.from(Q.wake);Q.wake.clear();for(let Z of $)Z()}scheduleEviction(Q){if(Q.evictAt)return;let $=setTimeout(()=>{let Z=Q.run.runId;if(this.runs.delete(Z),Q.threadId&&this.byThread.get(Q.threadId)===Z)this.byThread.delete(Q.threadId);if(Q.clientRunId&&this.byClientRun.get(Q.clientRunId)===Z)this.byClientRun.delete(Q.clientRunId);this.notify(Q)},this.ttlMs);$.unref?.(),Q.evictAt=$}}var mQ=new BQ;function c6(Q,$){try{Q.onInternalError?.($)}catch{}}class DQ{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 G of $){let J=Z.messages.findIndex((W)=>W.id===G.id);if(J===-1)Z.messages.push(G);else Z.messages[J]=G}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 pQ=new DQ;function d6(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 i6(Q,$,Z=new Date().toISOString()){if(!($.event.type==="run-start"&&$.event.runId!==Q.cursorRunId)&&$.seq<=Q.seq)return Q;return{...o6(Q,$.event,Z),seq:$.seq}}function o6(Q,$,Z){switch($.type){case"run-start":return{...Q,runId:$.runId,cursorRunId:$.runId,threadId:$.threadId??Q.threadId,runMessageIds:[],loadedTools:[],finishReason:void 0};case"message-start":return x(Q,$.messageId,Z,(G)=>({...G,role:$.role}));case"text-delta":if(p6(Q,$.messageId))return Q;return x(Q,$.messageId,Z,(G)=>({...G,content:U$(G.content,$.delta)}));case"reasoning-delta":if(p6(Q,$.messageId))return Q;return x(Q,$.messageId,Z,(G)=>({...G,content:z$(G.content,$.delta,$.id)}));case"output-delta":return x(Q,$.messageId,Z,(G)=>({...G,content:l6(G.content,{type:"output",value:$.snapshot,partial:!0},(J)=>J.type==="output")}));case"tool-call":return x(Q,$.messageId,Z,(G)=>{let J=G.content.findIndex((B)=>B.type==="tool-call"&&B.toolCallId===$.part.toolCallId),W=J===-1?void 0:G.content[J],Y=$.part.progress??W?.progress,V=$.part.nested??W?.nested,X=$.part.attachments??W?.attachments,K={...$.part,...Y?{progress:Y}:{},...V?{nested:V}:{},...X?{attachments:X}:{}},H=G.content.slice();if(J===-1)H.push(K);else H[J]=K;return{...G,content:H}});case"tool-search":{let G=$.loaded.filter((J)=>!Q.loadedTools.includes(J));if(G.length===0)return Q;return{...Q,loadedTools:[...Q.loadedTools,...G]}}case"tool-progress":return m6(Q,$.toolCallId,(G)=>({...G,progress:[...G.progress??[],$.data]}));case"nested-event":{let G=$;return m6(Q,$.toolCallId,(J)=>{let W=J.nested??[],Y=W.findIndex((H)=>H.runId===G.runId),V=W[Y]??{runId:G.runId,agent:G.agent,messages:[]},X=H$(V,G,Z),K=Y===-1?[...W,X]:W.map((H,B)=>B===Y?X:H);return{...J,nested:K}})}case"tool-result":{let G=x(Q,$.messageId,Z,(J)=>({...J,content:l6(J.content,$.part,(W)=>W.type==="tool-result"&&W.toolCallId===$.part.toolCallId)}));return{...G,pending:G.pending.filter((J)=>J.toolCallId!==$.part.toolCallId)}}case"message":{let G=Q.messages.findIndex((Y)=>Y.id===$.message.id),J=Q.messages.slice();if(G===-1)J.push($.message);else J[G]=$.message;let W=Q.runMessageIds.includes($.message.id)?Q.runMessageIds:[...Q.runMessageIds,$.message.id];return{...Q,messages:J,runMessageIds:W}}case"awaiting-input":return{...Q,runId:$.runId,pending:[...$.pending]};case"message-end":return x(Q,$.messageId,Z,(G)=>({...G,finishReason:$.finishReason,...$.outputTruncated?{outputTruncated:!0}:{},content:$.outputTruncated||$.finishReason==="length"?G.content.filter((J)=>!(J.type==="output"&&J.partial)):G.content.map((J)=>J.type==="output"&&J.partial?{...J,partial:!1}:J)}));case"usage":{let G=D$(Q.messages,(W)=>W.role==="assistant");if(G===-1)return Q;let J=Q.messages.slice();return J[G]={...J[G],usage:$.usage},{...Q,messages:J}}case"error":return{...Q,error:$.error,pending:[]};case"run-end":return{...Q,runId:void 0,finishReason:$.finishReason,messages:n6(Q,$.finishReason)};default:return Q}}function n6(Q,$){return Q.messages.map((Z)=>Z.role==="assistant"&&Q.runMessageIds.includes(Z.id)?V$(Z,$):Z)}function V$(Q,$){let Z=Q.content.map((J)=>J.type==="tool-call"&&J.nested?.some((W)=>W.finishReason===void 0)?{...J,nested:J.nested.map((W)=>W.finishReason===void 0?K$(W,$):W)}:J);if(Q.finishReason===void 0)return{...Q,finishReason:$,content:Z};return Z.some((J,W)=>J!==Q.content[W])?{...Q,content:Z}:Q}function K$(Q,$){let Z={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((G)=>G.id),loadedTools:[]};return{...Q,finishReason:$,messages:n6(Z,$)}}function m6(Q,$,Z){for(let G=Q.messages.length-1;G>=0;G--){let J=Q.messages[G],W=J.content.findIndex((K)=>K.type==="tool-call"&&K.toolCallId===$);if(W===-1)continue;if(J.finishReason!==void 0&&!B$(Q,J,$))return Q;let Y=J.content.slice();Y[W]=Z(Y[W]);let V=Q.messages.slice();V[G]={...J,content:Y};let X=Q.runMessageIds.includes(J.id)?Q.runMessageIds:[...Q.runMessageIds,J.id];return{...Q,runMessageIds:X,messages:V}}return Q}function H$(Q,$,Z){let G={messages:Q.messages,pending:[],error:null,seq:-1,runMessageIds:Q.messages.map((W)=>W.id),loadedTools:[],finishReason:Q.finishReason},J=o6(G,$.event,Z);return{...Q,...$.label!==void 0?{label:$.label}:{},messages:J.messages,...J.finishReason!==void 0?{finishReason:J.finishReason}:{},...$.event.type==="usage"?{usage:$.event.usage}:{}}}function B$(Q,$,Z){if($.finishReason!=="awaiting-input")return!1;return!Q.messages.some((G)=>G.content.some((J)=>J.type==="tool-result"&&J.toolCallId===Z))}function p6(Q,$){let Z=Q.messages.find((G)=>G.id===$);return Z!==void 0&&Z.finishReason!==void 0}function D$(Q,$){for(let Z=Q.length-1;Z>=0;Z--)if($(Q[Z]))return Z;return-1}function x(Q,$,Z,G){let J=Q.messages.findIndex((V)=>V.id===$),W=Q.runMessageIds.includes($)?Q.runMessageIds:[...Q.runMessageIds,$];if(J===-1){let V={id:$,role:"assistant",content:[],createdAt:Z};return{...Q,runMessageIds:W,messages:[...Q.messages,G(V)]}}let Y=Q.messages.slice();return Y[J]=G(Y[J]),{...Q,runMessageIds:W,messages:Y}}function U$(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 z$(Q,$,Z){let G=Q[Q.length-1];if(G&&G.type==="reasoning"&&G.id===Z)return[...Q.slice(0,-1),{...G,text:(G.text??"")+$}];return[...Q,Z?{type:"reasoning",id:Z,text:$}:{type:"reasoning",text:$}]}function l6(Q,$,Z){let G=Q.findIndex(Z);if(G===-1)return[...Q,$];let J=Q.slice();return J[G]=$,J}class dQ{store;threadId;report;chain=Promise.resolve();done=new Set;closed=!1;state;runId;constructor(Q,$,Z,G){this.store=Q;this.threadId=$;this.report=G;this.state=d6({messages:Z})}finish(Q){if(this.closed)return;this.done.add(Q.id),this.write(()=>[lQ(Q)])}frame(Q){if(this.closed)return;let $=Q.event;if($.type==="run-start")this.runId=$.runId;switch(this.state=i6(this.state,Q),$.type){case"message":this.write(()=>[lQ($.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((G)=>G.id===Q);if(!$)return;let Z=this.runId;this.write(()=>{let G=lQ($);if(G.finishReason===void 0&&Z)G.runId=Z;return[G]})}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 lQ(Q){return structuredClone(Q)}async function s6(Q,$){let Z=[],G=null,J=Q.slice();for(let W=0;W<J.length;W++){let Y=J[W];if(Y.role!=="assistant"||Y.finishReason!==void 0)continue;if(Y.runId&&await $(Y.runId))continue;G??=new Set(Q.flatMap((K)=>K.content.flatMap((H)=>H.type==="tool-result"?[H.toolCallId]:[])));let V=Y.content.map((K)=>K.type==="tool-call"?t6(K):K);for(let K of Y.content){if(K.type!=="tool-call"||G.has(K.toolCallId))continue;let H={type:"tool-result",toolCallId:K.toolCallId,name:K.name,status:"denied",cause:"interrupted"};V.push(H)}let X={...Y,content:V,finishReason:"interrupted"};J[W]=X,Z.push(X)}return{messages:J,settled:Z}}function t6(Q){let{partial:$,...Z}=Q;if(!Z.nested?.some((G)=>G.finishReason===void 0))return Z;return{...Z,nested:Z.nested.map(F$)}}function F$(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"?t6(Z):Z)}:$)}}var L$=$9,UQ=new Map,r6=new WeakMap,zQ=new Map;class G9 extends L${static kind="agent-controller";store=pQ;liveRuns=mQ;attachments=n;attachmentStorage=Z9;hookHoldMs=30000;instructions(Q,$){}context(Q,$){return{}}requireThread=!1;authorizeRequest(Q,$){}async stream(Q=new m){let $=await iQ(Q);if($.error)return FQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:void 0,J=C$(Z);if(J.error)return FQ({body:{},error:J.error});let W=J.turn,Y=typeof Z.clientRunId==="string"?Z.clientRunId:void 0;if(this.requireThread&&!G)return j(400,{code:"thread_required",message:"This agent takes a turn only on a thread: send a threadId."});let V=Y?{cancelled:!1}:null;if(V)zQ.set(Y,V);let X=async()=>{let K;if(G){let O=await this.store.loadThread(G);if(!O)return j(404,{code:"thread_not_found",message:`Thread ${G} does not exist here, or has expired.`});K=await this.settleThread(G,O,{write:!0})}else K=Array.isArray(Z.messages)?Z.messages:[];let H=N$(Z),B=await this.instructions(Q,{body:H})||void 0,D=await this.context(Q,{body:H}),L=await this.attachmentsFor(Q,G);if(V?.cancelled)return e6();let U=G?new dQ(this.store,G,K,(O)=>this.reportHookFailure(O)):null,z=this.agent.stream({messages:K,turn:W,threadId:G,...U?{onMessage:(O)=>U.finish(O)}:{},instructions:B,context:D,attachments:L,body:H}),F={req:Q,runId:z.runId,threadId:G},P=this.liveRuns.register(z,{threadId:G,clientRunId:Y,onEvent:(O)=>this.dispatchEvent(O,F),onInternalError:(O)=>this.reportHookFailure(O)});if(U)this.follow(z,U);let{stored:M,hooks:q}=this.persistRun(z,F,P,U);return r6.set(z,M),Q.ctx?.()?.waitUntil(q),z.toResponse()};try{if(await this.authorizeRequest(Q,{route:"stream",threadId:G}),V?.cancelled)return e6();return G?await this.withThread(G,X):await X()}finally{if(V&&zQ.get(Y)===V)zQ.delete(Y)}}async withThread(Q,$){let Z=UQ.get(Q)??Promise.resolve(),G,J=new Promise((Y)=>{G=Y}),W=Z.then(()=>J);UQ.set(Q,W),await Z;try{let Y=await this.liveRuns.find({threadId:Q}),V=Y?this.liveRuns.get(Y.runId):null;if(V)V.stop({reason:"superseded by a later turn on this thread"}),await r6.get(V);return await $()}finally{if(G(),UQ.get(Q)===W)UQ.delete(Q)}}async attach(Q=new m){let $=await iQ(Q);if($.error)return FQ($);let Z=$.body,G=typeof Z.threadId==="string"?Z.threadId:M$(Q,"threadId");if(!G)return j(400,{code:"invalid_request",message:"attach needs a threadId: it is the handle that survives a refresh."});await this.authorizeRequest(Q,{route:"attach",threadId:G});let J=await this.liveRuns.find({threadId:G});if(!J)return j(404,{code:"no_live_run",message:`No run in progress for thread ${G} in this process.`});let W=typeof Z.runId==="string"?Z.runId:void 0,Y=W&&W!==J.runId?void 0:P$(Q,Z);try{return K6(this.liveRuns.replay(J.runId,Y))}catch(V){if(V instanceof v)return j(410,{code:V.code,message:V.message,oldestSeq:V.oldest});if(V instanceof c)return j(404,{code:V.code,message:V.message});throw V}}async stop(Q=new m){let $=await iQ(Q);if($.error)return FQ($);let Z=$.body;await this.authorizeRequest(Q,{route:"stop",threadId:typeof Z.threadId==="string"?Z.threadId:void 0});let G=typeof Z.runId==="string"?Z.runId:void 0;if(!G&&typeof Z.clientRunId==="string"){if(G=this.liveRuns.findByClientRunId(Z.clientRunId)??void 0,!G){let W=zQ.get(Z.clientRunId);if(W)return W.cancelled=!0,{stopped:!0}}}if(!G&&typeof Z.threadId==="string")G=(await this.liveRuns.find({threadId:Z.threadId}))?.runId;let J=G?this.liveRuns.get(G):null;if(!J)return{stopped:!1};return J.stop({reason:typeof Z.reason==="string"?Z.reason:void 0}),{stopped:!0}}attachmentScope(Q,$){let Z=Q.ctx()?.user,G=Z?.id??Z?.publicId;if(G!==void 0&&G!==null&&String(G)!=="")return{key:`user:${String(G)}`};if($)return{key:`thread:${$}`};return null}attachmentDestination(Q,$){return"both"}async attachmentsFor(Q,$){let Z=await this.attachmentScope(Q,$);if(!Z)return null;return new h(this.attachments,this.attachmentStorage,Z)}async upload(Q=new m){let $=await Q.rawRequest.formData(),Z=$.get("file");if(!(Z instanceof Blob))throw Error("upload expects a multipart body with a `file` field.");let G=Z instanceof File&&Z.name?Z.name:"upload",J=Z.type||"application/octet-stream",W=$.get("threadId");await this.authorizeRequest(Q,{route:"upload",threadId:typeof W==="string"&&W.length>0?W:void 0});let Y=typeof W==="string"&&W.length>0&&await this.store.loadThread(W)!==null?W:void 0,V=await this.attachmentDestination(Z,Q),X=q$(V,$.get("destination")),K=await this.attachmentScope(Q,Y),H=X!=="provider"&&!K;if(H){if(X==="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()`.');S$()}if(X==="provider"||!K){let F={fileId:await this.agent.provider.upload(Z),name:G,mimeType:J,size:Z.size,destination:"provider"};if(H)F.downgraded="no_scope";return F}let B=_Q(),D=await this.attachmentStorage.put({name:CQ(B,G),body:Z,contentType:J}),L=X==="both"?await this.agent.provider.upload(Z):void 0,U={id:B,scopeKey:K.key,fileId:L,objectName:D,name:G,mimeType:J,size:Z.size,createdAt:new Date().toISOString(),destination:X};return await this.attachments.put(K,U),{fileId:L,attachmentId:B,name:G,mimeType:J,size:Z.size,destination:X}}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 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:G,settled:J}=await s6($,(W)=>this.isRunLive(W,Q));if(Z&&J.length>0)try{await this.store.appendMessages(Q,J)}catch(W){this.reportHookFailure(W)}return G}follow(Q,$){(async()=>{try{for await(let Z of Q.frames())$.frame(Z)}catch(Z){this.reportHookFailure(Z)}})()}persistRun(Q,$,Z,G=null){let J=Promise.resolve(),W=(async()=>{let V;try{V=await Q.result()}catch(K){G?.close(),await G?.settled(),J=this.safely(()=>this.onError({code:"unknown",message:K instanceof Error?K.message:String(K),retryable:!1},$));return}let X=V.messages;if(G?.close(X),await G?.settled(),$.threadId&&X.length>0)try{await this.store.appendMessages($.threadId,X)}catch(K){this.reportHookFailure(K)}J=this.notifyRun(V,X,$)})(),Y=W.then(()=>T$(Promise.all([J,Z]).then(()=>{}),this.hookHoldMs));return{stored:W,hooks:Y}}async notifyRun(Q,$,Z){for(let G of $)await this.safely(()=>this.onMessage(G,Z));await this.safely(()=>this.onStreamComplete(Q,Z))}async safely(Q){try{await Q()}catch($){this.reportHookFailure($)}}}var a6=["turn","clientRunId","threadId","messages"],O$=["text","files","toolResults"];function N$(Q){let $=J9(Q)?a6:[...a6,...O$],Z={};for(let[G,J]of Object.entries(Q)){if($.includes(G))continue;Object.defineProperty(Z,G,{value:J,writable:!0,enumerable:!0,configurable:!0})}return Z}async function iQ(Q){let $=Q?.rawRequest;if(!$||$.method==="GET"||$.method==="HEAD"||!$.body)return{body:{}};if(!_$($.headers.get("Content-Type")))return{body:{},status:415,code:"unsupported_media_type",error:"The request body must be sent as application/json."};let Z;try{Z=await $.text()}catch{return{body:{},error:"The request body could not be read."}}if(!Z.trim())return{body:{}};let G;try{G=JSON.parse(Z)}catch{return{body:{},error:"The request body is not valid JSON."}}if(G===null||typeof G!=="object"||Array.isArray(G))return{body:{},error:"The request body must be a JSON object."};return{body:G}}function _$(Q){if(typeof Q!=="string")return!1;let[$]=Q.split(";",1);return $.trim().toLowerCase()==="application/json"}function FQ(Q){return j(Q.status??400,{code:Q.code??"invalid_request",message:Q.error})}function J9(Q){return Boolean(Q.turn)&&typeof Q.turn==="object"}function C$(Q){let $=J9(Q)?Q.turn:Q,Z={};if(typeof $.text==="string")Z.text=$.text;if(Array.isArray($.files)){let G=j$($.files);if(typeof G==="string")return{error:G};Z.files=G}if(Array.isArray($.toolResults))Z.toolResults=$.toolResults;return Object.keys(Z).length>0?{turn:Z}:{}}function j$(Q){let $=[];for(let[Z,G]of Q.entries()){let J=`turn.files[${Z}]`;if(!G||typeof G!=="object"||Array.isArray(G))return`${J} must be an object.`;let W={};for(let H of["fileId","attachmentId","name","mimeType"]){let B=G[H];if(B===void 0||B===null||B==="")continue;if(typeof B!=="string")return`${J}.${H} must be a string.`;W[H]=B}let{fileId:Y,attachmentId:V,name:X,mimeType:K}=W;if(Y?.startsWith(C))return`${J}.fileId holds a gemi attachment id (${Y}). \`fileId\` is the provider's id from the upload response; put this one in \`attachmentId\`.`;if(V!==void 0&&!V.startsWith(C))return`${J}.attachmentId is not a gemi attachment id: it must start with "${C}".`;if(!Y&&!V)return`${J} has neither a \`fileId\` nor an \`attachmentId\`. Send the ids the upload response answered.`;$.push({...Y?{fileId:Y}:{},...V?{attachmentId:V}:{},...X!==void 0?{name:X}:{},...K!==void 0?{mimeType:K}:{}})}return $}function P$(Q,$){if(typeof $.from==="number"&&Number.isFinite($.from))return Math.max(0,Math.floor($.from));if(typeof $.cursor==="number"&&Number.isFinite($.cursor)){let G=Math.floor($.cursor);if(G>=0)return G+1;return}let Z=Q?.rawRequest?.headers?.get("Last-Event-ID");if(Z){let G=Number.parseInt(Z,10);if(Number.isFinite(G))return Math.max(0,G+1)}return}function M$(Q,$){let Z=Q?.search?.get($);return typeof Z==="string"?Z:void 0}function e6(){return j(409,{code:"stopped",message:"The turn was stopped before it started."})}function j(Q,$){return new Response(JSON.stringify({error:$}),{status:Q,headers:{"Content-Type":"application/json"}})}function q$(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 Q9=!1;function S$(){if(Q9)return;Q9=!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 R$=2147483647;function T$(Q,$){let Z=Q.then(()=>{},()=>{});if(!($<=R$))return Z;let G,J=new Promise((W)=>{G=setTimeout(W,$)});return Promise.race([Z,J]).finally(()=>clearTimeout(G))}export{R9 as toAgentTools,QQ as supportsStrict,k$ as s,mQ as liveRuns,n as defaultAttachmentStore,pQ as defaultAgentStore,$Q as ToolNamespace,RQ as Skill,h as ScopedAttachments,u as SKILLS_NAMESPACE,T as PendingEscalation,gQ as OpenAIProvider,xQ as OpenAIImageProvider,BQ as MemoryLiveRuns,o as MemoryAttachmentStore,DQ as MemoryAgentStore,c as LiveRunNotFoundError,w as InvalidAttachmentScopeError,YQ as ImageRequestError,XQ as ImageProvider,kQ as ImageModel,v as FrameCursorEvictedError,cQ as AzureOpenAIProvider,bQ as AzureOpenAIImageProvider,y as AttachmentNotFoundError,E as AgentTool,HQ as AgentProvider,G9 as AgentController,TQ as Agent};
19
19
 
20
- //# debugId=9C497D9DCE92F69064756E2164756E21
20
+ //# debugId=62BB5254CF11110D64756E2164756E21