dispach 0.2.3 → 0.2.13

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 (219) hide show
  1. package/README.md +46 -43
  2. package/dist/APEv2Parser-rt8hyadd.js +5 -0
  3. package/dist/{AiffParser-9hj6fpmy.js → AiffParser-gvpmtb2e.js} +3 -3
  4. package/dist/{AiffParser-9hj6fpmy.js.map → AiffParser-gvpmtb2e.js.map} +1 -1
  5. package/dist/App-18dvbyev.js +11 -0
  6. package/dist/{App-2f72vhjv.js.map → App-18dvbyev.js.map} +1 -1
  7. package/dist/AsfParser-h9zyh6cx.js +5 -0
  8. package/dist/{AsfParser-7emspn04.js.map → AsfParser-h9zyh6cx.js.map} +1 -1
  9. package/dist/ConfigEditor-444m13ta.js +6 -0
  10. package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-444m13ta.js.map} +1 -1
  11. package/dist/DsdiffParser-gxqv4gn1.js +5 -0
  12. package/dist/{DsdiffParser-dz88pnnr.js.map → DsdiffParser-gxqv4gn1.js.map} +1 -1
  13. package/dist/{DsfParser-qgh63tbs.js → DsfParser-sndt4jbk.js} +3 -3
  14. package/dist/{DsfParser-qgh63tbs.js.map → DsfParser-sndt4jbk.js.map} +1 -1
  15. package/dist/FlacParser-rmkpvf9e.js +5 -0
  16. package/dist/{KeyProbe-5anphmb7.js → KeyProbe-6t531sy6.js} +3 -3
  17. package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-6t531sy6.js.map} +1 -1
  18. package/dist/MP4Parser-87xfsck4.js +5 -0
  19. package/dist/{MP4Parser-yr7p3z12.js.map → MP4Parser-87xfsck4.js.map} +2 -2
  20. package/dist/{MatroskaParser-jkbsbsk3.js → MatroskaParser-7krspfgx.js} +3 -3
  21. package/dist/{MatroskaParser-jkbsbsk3.js.map → MatroskaParser-7krspfgx.js.map} +1 -1
  22. package/dist/{MpegParser-t93vwnew.js → MpegParser-jcs35q0h.js} +3 -3
  23. package/dist/{MpegParser-t93vwnew.js.map → MpegParser-jcs35q0h.js.map} +1 -1
  24. package/dist/MusepackParser-d4zfnzk3.js +5 -0
  25. package/dist/{MusepackParser-6e8kbh2d.js.map → MusepackParser-d4zfnzk3.js.map} +2 -2
  26. package/dist/OggParser-fbspjs7v.js +5 -0
  27. package/dist/{OggParser-ggcypmag.js.map → OggParser-fbspjs7v.js.map} +1 -1
  28. package/dist/Picker-x6aj42tc.js +5 -0
  29. package/dist/{Picker-j7txnm7w.js.map → Picker-x6aj42tc.js.map} +1 -1
  30. package/dist/SessionPicker-pngdv97x.js +5 -0
  31. package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-pngdv97x.js.map} +1 -1
  32. package/dist/SkillBrowser-3mnzkakr.js +5 -0
  33. package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-3mnzkakr.js.map} +1 -1
  34. package/dist/WavPackParser-0x9z4466.js +5 -0
  35. package/dist/{WavPackParser-jw9stzqp.js.map → WavPackParser-0x9z4466.js.map} +1 -1
  36. package/dist/WaveParser-31b6qtef.js +5 -0
  37. package/dist/{WaveParser-epmncs9w.js.map → WaveParser-31b6qtef.js.map} +1 -1
  38. package/dist/WizardApp-c42wc116.js +5 -0
  39. package/dist/{WizardApp-pgzcz9zq.js.map → WizardApp-c42wc116.js.map} +1 -1
  40. package/dist/channels-nf6d8fvx.js +31 -0
  41. package/dist/{channels-m8nambmm.js.map → channels-nf6d8fvx.js.map} +1 -1
  42. package/dist/client.d.ts +1 -1
  43. package/dist/client.js +11 -11
  44. package/dist/client.js.map +4 -4
  45. package/dist/config-sx40rg8m.js +24 -0
  46. package/dist/{config-hmgrqgf2.js.map → config-sx40rg8m.js.map} +2 -2
  47. package/dist/credential-vdbkfk65.js +19 -0
  48. package/dist/{credential-nkb2ya59.js.map → credential-vdbkfk65.js.map} +1 -1
  49. package/dist/daemon.d.ts.map +1 -1
  50. package/dist/{index-51x0n5z0.js → index-0dcpsfet.js} +4 -4
  51. package/dist/{index-51x0n5z0.js.map → index-0dcpsfet.js.map} +1 -1
  52. package/dist/{index-yw3fby4n.js → index-1h8s50d9.js} +3 -3
  53. package/dist/{index-yw3fby4n.js.map → index-1h8s50d9.js.map} +1 -1
  54. package/dist/index-1hbvhrsj.js +6 -0
  55. package/dist/{index-dzy19wtf.js.map → index-1hbvhrsj.js.map} +1 -1
  56. package/dist/index-1hfece7s.js +10 -0
  57. package/dist/{index-22fzzn7z.js.map → index-1hfece7s.js.map} +2 -2
  58. package/dist/index-2h566rtg.js +6 -0
  59. package/dist/{index-jc4kmfwa.js.map → index-2h566rtg.js.map} +1 -1
  60. package/dist/index-4g4smpkk.js +11 -0
  61. package/dist/{index-sh44ymqz.js.map → index-4g4smpkk.js.map} +1 -1
  62. package/dist/index-4gfsf9n8.js +6 -0
  63. package/dist/{index-8tmv33mr.js.map → index-4gfsf9n8.js.map} +1 -1
  64. package/dist/{index-dv9pdjy4.js → index-5ptbytze.js} +10 -10
  65. package/dist/{index-dv9pdjy4.js.map → index-5ptbytze.js.map} +1 -1
  66. package/dist/index-5s1cq8np.js +8 -0
  67. package/dist/{index-9t4dz145.js.map → index-5s1cq8np.js.map} +1 -1
  68. package/dist/{index-2zjh5zd5.js → index-659ggfbf.js} +2 -2
  69. package/dist/index-6ebppx3t.js +6 -0
  70. package/dist/{index-1x8mzvz7.js.map → index-6ebppx3t.js.map} +1 -1
  71. package/dist/index-6pym9p8h.js +9 -0
  72. package/dist/{index-38gs9anh.js.map → index-6pym9p8h.js.map} +1 -1
  73. package/dist/index-9ejax6hp.js +6 -0
  74. package/dist/{index-8edck2pr.js.map → index-9ejax6hp.js.map} +1 -1
  75. package/dist/{index-zw6wyas6.js → index-9hw9j1qg.js} +4 -4
  76. package/dist/{index-zw6wyas6.js.map → index-9hw9j1qg.js.map} +1 -1
  77. package/dist/{index-bqdkm3de.js → index-9xhresrg.js} +4 -4
  78. package/dist/{index-bqdkm3de.js.map → index-9xhresrg.js.map} +1 -1
  79. package/dist/{index-hgm2gchq.js → index-abm0zyc0.js} +12 -12
  80. package/dist/{index-hgm2gchq.js.map → index-abm0zyc0.js.map} +1 -1
  81. package/dist/index-ar5c9d2f.js +7 -0
  82. package/dist/{index-3826kf9t.js.map → index-ar5c9d2f.js.map} +1 -1
  83. package/dist/index-bhj4pmrx.js +74 -0
  84. package/dist/index-bhj4pmrx.js.map +13 -0
  85. package/dist/index-brt17yfr.js +6 -0
  86. package/dist/{index-hrwakb11.js.map → index-brt17yfr.js.map} +2 -2
  87. package/dist/index-bysnsdkd.js +6 -0
  88. package/dist/{index-nxhqf597.js.map → index-bysnsdkd.js.map} +1 -1
  89. package/dist/index-c74wx9pv.js +6 -0
  90. package/dist/{index-323jvr1g.js.map → index-c74wx9pv.js.map} +1 -1
  91. package/dist/index-cm3g4t3r.js +14 -0
  92. package/dist/{index-y7dxq4a4.js.map → index-cm3g4t3r.js.map} +2 -2
  93. package/dist/index-dzp6mc5h.js +6 -0
  94. package/dist/{index-42e29zs4.js.map → index-dzp6mc5h.js.map} +1 -1
  95. package/dist/index-fad09b8c.js +6 -0
  96. package/dist/{index-836hc2h1.js.map → index-fad09b8c.js.map} +2 -2
  97. package/dist/{index-0444sh6x.js → index-fvb2dxzn.js} +4 -4
  98. package/dist/{index-0444sh6x.js.map → index-fvb2dxzn.js.map} +1 -1
  99. package/dist/{index-2bsardvh.js → index-gpq4agva.js} +3 -3
  100. package/dist/{index-2bsardvh.js.map → index-gpq4agva.js.map} +1 -1
  101. package/dist/{index-qgsdgbk8.js → index-hcpvk5de.js} +3 -3
  102. package/dist/{index-qgsdgbk8.js.map → index-hcpvk5de.js.map} +1 -1
  103. package/dist/{index-pqw1n1pv.js → index-jv5t63tp.js} +4 -4
  104. package/dist/{index-pqw1n1pv.js.map → index-jv5t63tp.js.map} +1 -1
  105. package/dist/index-kyz4t0j0.js +126 -0
  106. package/dist/{index-ry6a4bqh.js.map → index-kyz4t0j0.js.map} +2 -2
  107. package/dist/{index-ytxbw8py.js → index-m6r2sxcw.js} +33 -33
  108. package/dist/{index-ytxbw8py.js.map → index-m6r2sxcw.js.map} +1 -1
  109. package/dist/{index-snz49ndn.js → index-mhw3d7af.js} +3 -3
  110. package/dist/{index-snz49ndn.js.map → index-mhw3d7af.js.map} +1 -1
  111. package/dist/{index-1mbdz3f7.js → index-mk7hrzq7.js} +9 -9
  112. package/dist/{index-1mbdz3f7.js.map → index-mk7hrzq7.js.map} +1 -1
  113. package/dist/index-n0hqgwad.js +6 -0
  114. package/dist/{index-xg7s813b.js.map → index-n0hqgwad.js.map} +2 -2
  115. package/dist/index-ncb840sk.js +6 -0
  116. package/dist/{index-mjfv7k5w.js.map → index-ncb840sk.js.map} +1 -1
  117. package/dist/{index-fbsrhcga.js → index-ntczmwnf.js} +4 -4
  118. package/dist/{index-fbsrhcga.js.map → index-ntczmwnf.js.map} +1 -1
  119. package/dist/{index-095hrkyr.js → index-p5gy5s7p.js} +4 -4
  120. package/dist/{index-095hrkyr.js.map → index-p5gy5s7p.js.map} +1 -1
  121. package/dist/{index-3c5jt6by.js → index-p86w0qjw.js} +3 -3
  122. package/dist/{index-3c5jt6by.js.map → index-p86w0qjw.js.map} +1 -1
  123. package/dist/index-qhh30m9p.js +6 -0
  124. package/dist/{index-nvc24414.js.map → index-qhh30m9p.js.map} +1 -1
  125. package/dist/{index-p6ya59m6.js → index-rerdsr3d.js} +4 -4
  126. package/dist/{index-p6ya59m6.js.map → index-rerdsr3d.js.map} +1 -1
  127. package/dist/{index-k8e9f466.js → index-s0mfq8t7.js} +19 -19
  128. package/dist/index-s0mfq8t7.js.map +11 -0
  129. package/dist/{index-3vzf253k.js → index-s9ybp2r1.js} +7 -7
  130. package/dist/{index-3vzf253k.js.map → index-s9ybp2r1.js.map} +1 -1
  131. package/dist/index-ss77hvwy.js +1246 -0
  132. package/dist/{index-hpvfqq6r.js.map → index-ss77hvwy.js.map} +32 -31
  133. package/dist/{index-jff5q27j.js → index-t9bnt6a1.js} +4 -4
  134. package/dist/{index-jff5q27j.js.map → index-t9bnt6a1.js.map} +1 -1
  135. package/dist/index-w2ss9hn5.js +9 -0
  136. package/dist/{index-eztfverw.js.map → index-w2ss9hn5.js.map} +1 -1
  137. package/dist/{index-pszmnhgq.js → index-w80shmpv.js} +9 -9
  138. package/dist/{index-pszmnhgq.js.map → index-w80shmpv.js.map} +1 -1
  139. package/dist/index-w8e8qxd4.js +337 -0
  140. package/dist/index-w8e8qxd4.js.map +21 -0
  141. package/dist/{index-308y9xt0.js → index-z9r4e0yq.js} +4 -4
  142. package/dist/{index-308y9xt0.js.map → index-z9r4e0yq.js.map} +1 -1
  143. package/dist/index-zj87j4j2.js +6 -0
  144. package/dist/index-zj87j4j2.js.map +10 -0
  145. package/dist/{index-m6fqx0ch.js → index-zmerx9rc.js} +6 -6
  146. package/dist/{index-m6fqx0ch.js.map → index-zmerx9rc.js.map} +1 -1
  147. package/dist/index-zqjtjs7c.js +153 -0
  148. package/dist/{index-dpcm1j62.js.map → index-zqjtjs7c.js.map} +2 -2
  149. package/dist/index.js +381 -368
  150. package/dist/index.js.map +7 -6
  151. package/dist/lib/launchd.d.ts.map +1 -1
  152. package/dist/lib/service-env.d.ts.map +1 -1
  153. package/dist/lib/templates.d.ts.map +1 -1
  154. package/dist/lib/theme.d.ts.map +1 -1
  155. package/dist/lib/watchdog.d.ts +20 -0
  156. package/dist/lib/watchdog.d.ts.map +1 -0
  157. package/dist/serve.d.ts.map +1 -1
  158. package/dist/skills.d.ts.map +1 -1
  159. package/dist/sources.d.ts.map +1 -1
  160. package/dist/web-zvf80ns1.js +14 -0
  161. package/dist/{web-gfv0mzgs.js.map → web-zvf80ns1.js.map} +1 -1
  162. package/dist/wire.js +11 -11
  163. package/dist/wire.js.map +4 -4
  164. package/dist/wrapper-5zhcdmnk.js +5 -0
  165. package/package.json +4 -4
  166. package/dist/APEv2Parser-ysjr6adv.js +0 -5
  167. package/dist/App-2f72vhjv.js +0 -11
  168. package/dist/AsfParser-7emspn04.js +0 -5
  169. package/dist/ConfigEditor-vk7vxaa6.js +0 -6
  170. package/dist/DsdiffParser-dz88pnnr.js +0 -5
  171. package/dist/FlacParser-drm5wq0p.js +0 -5
  172. package/dist/MP4Parser-yr7p3z12.js +0 -5
  173. package/dist/MusepackParser-6e8kbh2d.js +0 -5
  174. package/dist/OggParser-ggcypmag.js +0 -5
  175. package/dist/Picker-j7txnm7w.js +0 -5
  176. package/dist/SessionPicker-hpv2ncsb.js +0 -5
  177. package/dist/SkillBrowser-qc542n71.js +0 -5
  178. package/dist/WavPackParser-jw9stzqp.js +0 -5
  179. package/dist/WaveParser-epmncs9w.js +0 -5
  180. package/dist/WizardApp-pgzcz9zq.js +0 -5
  181. package/dist/channels-m8nambmm.js +0 -31
  182. package/dist/config-hmgrqgf2.js +0 -24
  183. package/dist/credential-nkb2ya59.js +0 -19
  184. package/dist/index-1x8mzvz7.js +0 -6
  185. package/dist/index-22fzzn7z.js +0 -10
  186. package/dist/index-323jvr1g.js +0 -6
  187. package/dist/index-3826kf9t.js +0 -7
  188. package/dist/index-38gs9anh.js +0 -9
  189. package/dist/index-42e29zs4.js +0 -6
  190. package/dist/index-836hc2h1.js +0 -6
  191. package/dist/index-8edck2pr.js +0 -6
  192. package/dist/index-8tmv33mr.js +0 -6
  193. package/dist/index-9t4dz145.js +0 -8
  194. package/dist/index-djeqvfms.js +0 -74
  195. package/dist/index-djeqvfms.js.map +0 -13
  196. package/dist/index-dpcm1j62.js +0 -153
  197. package/dist/index-dzy19wtf.js +0 -6
  198. package/dist/index-eztfverw.js +0 -9
  199. package/dist/index-fxpmx6cr.js +0 -308
  200. package/dist/index-fxpmx6cr.js.map +0 -21
  201. package/dist/index-hpvfqq6r.js +0 -1252
  202. package/dist/index-hrwakb11.js +0 -6
  203. package/dist/index-jc4kmfwa.js +0 -6
  204. package/dist/index-k8e9f466.js.map +0 -13
  205. package/dist/index-mjfv7k5w.js +0 -6
  206. package/dist/index-nvc24414.js +0 -6
  207. package/dist/index-nxhqf597.js +0 -6
  208. package/dist/index-qv6ktepc.js +0 -6
  209. package/dist/index-qv6ktepc.js.map +0 -10
  210. package/dist/index-ry6a4bqh.js +0 -126
  211. package/dist/index-sh44ymqz.js +0 -11
  212. package/dist/index-xg7s813b.js +0 -6
  213. package/dist/index-y7dxq4a4.js +0 -14
  214. package/dist/web-gfv0mzgs.js +0 -14
  215. package/dist/wrapper-f662ny3r.js +0 -5
  216. /package/dist/{APEv2Parser-ysjr6adv.js.map → APEv2Parser-rt8hyadd.js.map} +0 -0
  217. /package/dist/{FlacParser-drm5wq0p.js.map → FlacParser-rmkpvf9e.js.map} +0 -0
  218. /package/dist/{index-2zjh5zd5.js.map → index-659ggfbf.js.map} +0 -0
  219. /package/dist/{wrapper-f662ny3r.js.map → wrapper-5zhcdmnk.js.map} +0 -0
@@ -1,12 +1,12 @@
1
1
  #!/usr/bin/env node
2
- import{Yt,T,te,xe,Jt,fr,hr,Br,ys,qr,Vr,Qs,ms,so,Ss,ws,Ds,Wr,bs,iA,Os,Zr,PA,yr,$r,Xr,go,ei,Rs,sA,un,co,GA,Ai,_s,ks,vs,ni,Ls,Ps,Gs,Fs,Us}from"./index-djeqvfms.js";import{Ze,si,ai,Ks,Ys,n,s,R,He,E,r,pt,x,D,ft}from"./index-hpvfqq6r.js";var pn=()=>{let a={string:{unit:"characters",verb:"to have"},file:{unit:"bytes",verb:"to have"},array:{unit:"items",verb:"to have"},set:{unit:"items",verb:"to have"},map:{unit:"entries",verb:"to have"}};function e(p){return a[p]??null}let d={regex:"input",email:"email address",url:"URL",emoji:"emoji",uuid:"UUID",uuidv4:"UUIDv4",uuidv6:"UUIDv6",nanoid:"nanoid",guid:"GUID",cuid:"cuid",cuid2:"cuid2",ulid:"ULID",xid:"XID",ksuid:"KSUID",datetime:"ISO datetime",date:"ISO date",time:"ISO time",duration:"ISO duration",ipv4:"IPv4 address",ipv6:"IPv6 address",mac:"MAC address",cidrv4:"IPv4 range",cidrv6:"IPv6 range",base64:"base64-encoded string",base64url:"base64url-encoded string",json_string:"JSON string",e164:"E.164 number",jwt:"JWT",template_literal:"input"},u={nan:"NaN"};return(p)=>{switch(p.code){case"invalid_type":{let m=u[p.expected]??p.expected,b=Ks(p.input),N=u[b]??b;return`Invalid input: expected ${m}, received ${N}`}case"invalid_value":if(p.values.length===1)return`Invalid input: expected ${ai(p.values[0])}`;return`Invalid option: expected one of ${si(p.values,"|")}`;case"too_big":{let m=p.inclusive?"<=":"<",b=e(p.origin);if(b)return`Too big: expected ${p.origin??"value"} to have ${m}${p.maximum.toString()} ${b.unit??"elements"}`;return`Too big: expected ${p.origin??"value"} to be ${m}${p.maximum.toString()}`}case"too_small":{let m=p.inclusive?">=":">",b=e(p.origin);if(b)return`Too small: expected ${p.origin} to have ${m}${p.minimum.toString()} ${b.unit}`;return`Too small: expected ${p.origin} to be ${m}${p.minimum.toString()}`}case"invalid_format":{let m=p;if(m.format==="starts_with")return`Invalid string: must start with "${m.prefix}"`;if(m.format==="ends_with")return`Invalid string: must end with "${m.suffix}"`;if(m.format==="includes")return`Invalid string: must include "${m.includes}"`;if(m.format==="regex")return`Invalid string: must match pattern ${m.pattern}`;return`Invalid ${d[m.format]??p.format}`}case"not_multiple_of":return`Invalid number: must be a multiple of ${p.divisor}`;case"unrecognized_keys":return`Unrecognized key${p.keys.length>1?"s":""}: ${si(p.keys,", ")}`;case"invalid_key":return`Invalid key in ${p.origin}`;case"invalid_union":if(p.options&&Array.isArray(p.options)&&p.options.length>0)return`Invalid discriminator value. Expected ${p.options.map((b)=>`'${b}'`).join(" | ")}`;return"Invalid input";case"invalid_element":return`Invalid value in ${p.origin}`;default:return"Invalid input"}}};function Te(){return{localeError:pn()}}Ze(Te());import{existsSync as fe,mkdirSync as hn,readFileSync as Ve,rmSync as fn,statSync as mn,writeFileSync as Qe}from"node:fs";import{mkdtemp as gn,readdir as vn,readFile as Le,rm as yn}from"node:fs/promises";import{tmpdir as bn}from"node:os";import{basename as ye,dirname as be,join as Ue,relative as wn,resolve as he,sep as xn}from"node:path";import{createReadStream as Bn}from"node:fs";import{stat as Fn}from"node:fs/promises";import{Readable as at}from"node:stream";import{createGzip as Kn}from"node:zlib";function Yr(a={}){let e=a.now??(()=>new Date),d=new Map;return{approver:(p)=>new Promise((m)=>{let b={pending:{approvalId:p.approvalId,agentId:p.agentId,sessionKey:p.sessionKey,slug:p.slug,callId:p.callId,match:p.match,mutating:p.mutating,reason:p.reason,requestedAt:e().toISOString()},settle:(N)=>{d.delete(p.approvalId),m(N)}};d.set(p.approvalId,b),p.signal.addEventListener("abort",()=>b.settle(!1),{once:!0})}),pending:(p)=>[...d.values()].map((m)=>m.pending).filter((m)=>m.agentId===p).sort((m,b)=>m.requestedAt.localeCompare(b.requestedAt)),resolve:(p,m)=>{let b=d.get(p);if(b===void 0)return!1;return b.settle(m),!0},get size(){return d.size}}}function f(a,e,d={}){return new Response(JSON.stringify({error:a}),{status:e,headers:{"content-type":"application/json; charset=utf-8",...d}})}function Ye(){return f({code:"unauthorized",message:"Missing or invalid bearer token.",hint:"Send Authorization: Bearer <token>, where the token is either the value of the variable named by server.tokenEnv or an operator key from POST /v1/keys. A revoked key, an expired one and a wrong one answer the same way on purpose."},401)}function St(){return f({code:"claim_spent",message:"That claim has already been exchanged.",hint:"A claim is good for one key. Use the key it minted; if it is lost, restart with --claim to print a new one — a claim lives in the process rather than the database, so it never outlives the boot that printed it."},401)}function kn(a,e){return f({code:"capability_required",message:`This credential cannot ${e}.`,hint:`The key is scoped, and "${a}" is not among its capabilities. GET /v1/keys shows what each key may do; mint another with POST /v1/keys, or use the server token. An unscoped key has all of them.`,field:"scope.can"},403)}function Je(a,e){if(a.length!==e.length)return!1;let d=0;for(let u=0;u<a.length;u+=1)d|=a.charCodeAt(u)^e.charCodeAt(u);return d===0}function jn(a){let e=a.headers.get("authorization")??"";return e.startsWith("Bearer ")?e.slice(7):""}async function Sn(a){let e=jn(a.request);if(a.expected!==void 0&&Je(e,a.expected))return{kind:"token"};if(e!==""){let d=await a.keys.findLive(await hr(e),new Date(a.at).toISOString());if(d!==void 0)return await a.keys.touch(d.keyId,new Date(a.at).toISOString()),{kind:"key",keyId:d.keyId,label:d.label,...d.scope===void 0?{}:{scope:d.scope}};if(a.claim!==void 0&&Je(e,a.claim.token)){if(a.request.method!=="POST"||a.pathname!=="/v1/keys")return Ye();if(!a.claim.live())return St();return{kind:"claim"}}}return Ye()}var Nt="dispach.bearer";function Nn(a){let e=a.headers.get("sec-websocket-protocol");if(e===null)return;let d=e.split(",").map((p)=>p.trim()),u=d.indexOf(Nt);return u===-1?void 0:d[u+1]??""}function Tn(a,e){let d=new Headers(a.headers);return d.set("authorization",`Bearer ${e}`),new Request(a.url,{method:a.method,headers:d})}function S(a,e){return a.meta({...e})}function ie(a,e){return a.meta({description:e})}var Fe=r({id:S(n().trim().min(1),{code:"sender_invalid",hint:'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.',description:"Stable identifier for the sender. Appears on the turn row and in events."}),kind:S(D(iA,{error:(a)=>{let e=typeof a.input==="string"?a.input:void 0,d=e===void 0?void 0:Yt(e,iA);return`from.kind must be one of: ${iA.join(", ")}.${d===void 0?"":` Did you mean "${d}"?`}`}}),{code:"sender_invalid",hint:'This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".',description:'The trust boundary. "agent" fences the text as data and blocks mutating tools for the whole turn.'}),name:S(n().optional(),{code:"sender_invalid",hint:"A display name, shown beside the sender id. Omit it rather than sending an empty string.",description:"Human-readable name for the sender."})}).meta({description:"Attribution for a turn somebody other than the token-holder is sending. Omit for your own."}),En=S(pt([ft("none"),r({channel:n().min(1),to:n().min(1)})]),{code:"deliver_invalid",hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',description:'Where the reply goes. "none" leaves it on the event stream and in the store.'}),Xe=8000,Tt=r({text:S(n().trim().min(1),{code:"message_text_required",hint:'Send { "text": "..." }. An empty turn would be billed for a full prompt and produce nothing.',description:"What to say to the agent."}),sessionKey:ie(n().min(1).optional(),"Which conversation this belongs to. Defaults to `api:default`."),role:S(n().trim().min(1).optional(),{code:"model_role_unknown",hint:"Name a role declared under model: in the manifest (GET /v1/agents/:id/config lists them), or omit role to run on main. A person adds one with PATCH /config path model.<name>.",description:"A model role to run this turn on instead of main: one declared under `model:`, as a schedule names one with `role:`. This turn only; the conversation's other turns are unaffected. Refused before the turn starts when no such role is declared."}),runtimeNote:S(n().trim().min(1).max(Xe).optional(),{code:"message_note_invalid",hint:`Send runtimeNote as non-empty text of at most ${Xe} characters: the active project, today's date in the person's zone, an attachment's extracted text.`,description:"Your application's note about this message: shown to the model in its own block before the text, labelled as not written by the person, for this turn only. Kept on the turn record (`GET …/turns`), never in history. Refused when `from` is an agent."}),peerAsk:S(r({askedBy:n().trim().min(1).max(200)}).strict().optional(),{code:"message_peer_ask_invalid",hint:'Send { "peerAsk": { "askedBy": "<silo>/<agent>" } }, naming the agent that asked, or omit it.',description:"Marks this turn as another agent's ask (`docs/24-SPEC-PEER-ASK.md`): it runs without `handoff` and `ask_agent`, so it is one hop, and the agent is told who asked. It only narrows what the turn may do, so any caller may set it; the control plane's relay always does."}),images:S(E(r({path:n().optional(),data:n().optional(),mediaType:n().optional()}).strict()).optional(),{code:"message_images_invalid",hint:`Send images as [{ "path": "files/…/shot.png" }] (relative to the agent's directory), or [{ "data": "<base64>", "mediaType": "image/png" }].`,description:"Images sent with this message: PNG, JPEG, GIF or WebP, at most five, 3.75 MB each. A path inside the agent's directory, or inline base64 (within the 1 MB body limit). The model receives them on this turn; history keeps an `[image: <path>]` line."}),deliver:En.optional(),from:Fe.optional(),stream:ie(R().optional(),"Stream the turn's events inline as SSE rather than returning a handle."),chunks:ie(R().optional(),"Include per-token `model.chunk` frames. Off by default — the reader decides."),children:ie(R().optional(),"Include the events of subagents this turn runs (they carry `parentTurnId`). Off by default.")}),Et=r({content:S(n(),{code:"workspace_content_required",hint:'Send { "content": "<the whole file>" }. It replaces the file; frontmatter included.',description:"The file's new text, in full, frontmatter included."})}),Ct=r({vars:S(x(n(),S(n(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})),{code:"vars_required",hint:'Send { "vars": { "userName": "…" } }: the template variables to change. The rest keep the values the agent was made with.',description:"The template variables to change. Only files nobody has edited since they were rendered are rewritten."})}),_t=r({providers:S(E(n().min(1)).min(1).optional(),{code:"tools_refresh_providers_invalid",hint:`Name provider ids from the agent's tools.providers, e.g. { "providers": ["composio"] }, or send {} to refresh every one.`,description:"Which providers to refresh. Omit for all of them."})}),At=r({channel:S(n().min(1),{code:"delivery_channel_required",hint:`Name a channel id from the agent's manifest, e.g. { "channel": "tg", ... } — the id, not the type.`,description:"The channel id to send on."}),to:S(n().min(1),{code:"delivery_recipient_required",hint:"The channel's own address for the conversation: a Telegram chat id, a WhatsApp JID, a Slack channel id. The peer id an inbound message arrived with is always right.",description:"Who to send it to, in the channel's own addressing."}),text:S(n().trim().min(1),{code:"delivery_text_required",hint:'Send { "text": "..." }. An empty message has nothing to deliver.',description:"The exact text to send. No model turn runs."}),key:S(n().min(1),{code:"delivery_key_required",hint:"Any string unique to this send, such as your own message id. A retry with the same key is not sent or recorded twice.",description:"Idempotency key: a repeated key is accepted and does nothing."})}),Pt=r({granted:S(R(),{code:"approval_decision_required",hint:'Send { "granted": true } or { "granted": false }. There is no default: one direction would deny a call over a typo and the other would grant one, and neither is a decision anybody made.',description:"Whether the blocked tool call may proceed."})}),Cn=r({agents:E(n().min(1)).optional().meta({code:"key_scope_agents_invalid",hint:'Send { "agents": ["milo"] } — a list of agent ids. Omit it for a key that reaches every agent. An id naming no agent on this server is reported rather than silently matching nothing.',description:"Agent ids this key may reach. Absent means all of them."}),sessions:n().min(1).optional().meta({code:"key_scope_sessions_invalid",hint:'Send { "sessions": "team_42:" } — a session-key prefix, with an optional trailing "*". A prefix rather than a list, because the conversations this key will cover do not exist yet when it is minted.',description:"Session-key prefix. Absent means every session."}),can:E(D(["read","chat","write","admin","peer"])).optional().meta({code:"key_scope_can_invalid",hint:'Send { "can": ["chat", "read"] }. read (every GET), chat (send a message, answer an approval, stop a turn), write (schedules, phase, clearing a session), admin (keys, provisioning, start/stop/reload), and peer (a plugin route that asks for it — an A2A endpoint — and nothing else). Absent means all five; an empty array means none, and is honoured as written.',description:"Capabilities this key may exercise. Absent means all of them."}),participant:n().min(1).optional().meta({code:"key_scope_participant_invalid",hint:'Send { "participant": "user:018f…" } — the id this key speaks for. Every turn it starts acts for that participant: a from naming anyone else is refused, and an omitted one is filled in. Omit it for a backend that names senders itself.',description:"The participant every turn this key starts acts for. Absent: any sender."}),expiresIn:s().int().positive().optional().meta({code:"key_scope_expires_invalid",hint:'Send { "expiresIn": 3600 } — whole seconds from now, as a number. Relative rather than an absolute instant, because that would need the caller and this server to agree about the clock; the response reports the absolute expiresAt this server computed.',description:"Seconds until this key stops authenticating. Absent means never."})}),It=r({label:S(n(),{code:"key_label_required",hint:'Send { "label": "my browser" }. A label is required rather than defaulted because it is the only thing distinguishing two credentials in a listing, and "key 2" is a name nobody can act on when deciding which to revoke.',description:"How this credential is shown in a listing. Required; see `keyLabelProblem`."}),scope:Cn.optional().meta({code:"key_scope_invalid",hint:'Send { "scope": { "agents": ["milo"], "can": ["chat"] } }, or omit it entirely for a key that reaches everything — which is what every key minted before scopes existed does.',description:"Opt-in narrowing. Absent is an unscoped key."})}),$t=r({phase:S(n().min(1),{code:"phase_invalid",hint:"Send the name of a phase this agent's manifest declares. `GET /v1/agents/:id` lists them.",description:"The phase to move this session into."})}),Ot=r({keepTurns:S(s().int().min(1).optional(),{code:"compact_keep_invalid",hint:'Send { "keepTurns": 2 }, a whole number of at least 1, or omit it to keep the last 2 turns verbatim.',description:"How many of the newest turns stay verbatim. Everything before them becomes a digest and the person's requests. Default 2."})}),zt=r({recall:S(R(),{code:"recall_invalid",hint:'Send { "recall": false } to keep this conversation out of history recall, or true to put it back. Its messages are kept either way.',description:"Whether this conversation is indexed for history recall."})}),Rt=r({reason:S(n().optional(),{code:"agent_stop_invalid",hint:"A short note, recorded on the row and shown wherever the agent is reported as off.",description:"Why, for whoever reads the listing later."})}),et=r({path:S(n().min(1),{code:"config_path_unknown",hint:"GET /v1/agents/:id/config lists every field this surface may change, with what each one does.",description:"A dotted path, exactly as it appears in the manifest — `tools.pinned`, `model.main.id`."}),value:S(n().optional(),{code:"config_value_unreadable",hint:'Text, the way it is typed at a terminal: a bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#". To take a field out, send { "remove": true } instead.',description:"The new value, as text. Read by the same parser the `config` command uses. Required unless `remove` is true."}),remove:S(ft(!0).optional(),{code:"config_remove_invalid",hint:'Send { "path": "…", "remove": true } with no value to take a field out of the manifest, or a value to set it.',description:"Take the field out of the manifest instead of setting it, so it returns to its default. Checked like any edit: a required field is refused. A field that is not there is left as it is. Not sent together with `value`."}),confirm:ie(R().optional(),"Required only for a field whose own row carries a `confirm` sentence. Absent is not consent.")}),_n=et.partial({path:!0}).extend({changes:ie(E(et).min(1).optional(),"Several changes, each `{path, value}` or `{path, remove: true}`, applied in order and checked against the file as the earlier ones left it. One write and one reload; any refusal writes nothing. Sent instead of a top-level `path`.")}),An=r({enabled:ie(R().optional(),"Switch the channel on or off. It takes effect at the agent's next start, because a channel is constructed at boot."),credential:S(n().min(1).optional(),{code:"channel_credential_unreadable",hint:"The value goes into the .env beside the manifest at 0600, under the variable that channel's own entry names. Send a non-empty string; an empty one fails the load exactly as a missing variable does.",description:"The channel's credential — a Telegram bot token. Never returned by any route; only whether it is set."})}),Mt=r({answers:S(x(n(),S(n(),{code:"provision_answer_invalid",hint:"Answers arrive as strings from the terminal and from here, and are validated per step. Send the value as a string — including a boolean-looking choice, whose values are named in GET /v1/provision.",description:"One answer. Always text, whatever the step's type looks like."})).optional(),{code:"provision_answers_required",hint:'Send { "answers": { "name": "milo", … } }. Every step you leave out takes its default, exactly as `init --yes` does with flags; GET /v1/provision lists them.',description:"A subset of the wizard's steps, as strings. `GET /v1/provision` lists every step with its prompt, default and choices. Send this or `template`, not both."}),template:S(n().min(1).optional(),{code:"provision_template_invalid",hint:"Send the template's name as a string. GET /v1/templates lists what this server has.",description:"Create the agent from a template in this server's sandbox instead of from answers. Needs `name`; takes `vars`."}),name:S(n().optional(),{code:"provision_name_required",hint:'Send { "template": "…", "name": "Acme store" }. The id every route keys on is derived from it.',description:"The new agent's name, with `template`. Its slug becomes the id; the template sees both as {{agent.name}} and {{agent.id}}."}),vars:S(x(n(),S(n(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})).optional(),{code:"template_value_invalid",hint:`Send { "vars": { "store": "Acme" } }, every value a string. GET /v1/templates lists each template's variables.`,description:"Values for the template's declared variables. A secret variable's value goes to the agent's .env and is never returned."})}),Dt=(a)=>S(n().trim().min(1),{code:"participant_id_invalid",hint:'A participant id as your system knows the person, e.g. "user:018f…". Agents are "agent:<agentId>".',description:`The participant id${a===""?"":` (${a})`}.`}),Lt=r({id:Dt(""),name:ie(n().min(1).optional(),"A display name, shown to agents beside the id."),role:S(D(["admin","member"]).optional(),{code:"participant_role_invalid",hint:'Either "admin" (may assign agents to members) or "member". Omitted is "member".',description:'What the participant may do: "admin" also assigns agents.'}),title:ie(n().trim().min(1).max(120).optional(),"A job title, as the team knows the person. Told to an agent answering another member's agent about whom it represents and who is asking. Not a permission."),timezone:ie(n().trim().min(1).optional(),`An IANA timezone, such as "Europe/London". Told to an agent answering another member's agent, so "tomorrow at nine" means the right hour. Refused when the runtime does not know it.`),channelIds:S(E(n().min(1)).optional(),{code:"participant_channel_ids_invalid",hint:'A list of the person\'s own channel senders as `<channel type>:<id or handle>`, e.g. ["telegram:@ada", "whatsapp:+44 7700 900123"].',description:"The person's own channel senders, matched like allowFrom. Under sessions.scope peer, their turns from these channels and from the API share one conversation. Absent, a channel turn from them keeps its own."})}),Ut=r({kind:S(D(["room","dm"]),{code:"conversation_kind_invalid",hint:'"dm" is one human and one agent and is always answered; "room" is anyone, and an agent answers only when mentioned.',description:"A room or a direct conversation."}),members:S(E(n().trim().min(1)).min(1),{code:"conversation_members_required",hint:'Participant ids: registered humans, and agents as "agent:<agentId>".',description:"Who is in it."}),title:ie(n().min(1).optional(),"A name for a room, for the embedder's own listing.")}),Bt=r({add:S(E(n().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to add.",description:"Participant ids to add."}),remove:S(E(n().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to remove.",description:"Participant ids to remove."})}),Ft=r({text:S(n().trim().min(1),{code:"message_text_required",hint:'Send { "text": "…" }.',description:"What was said."}),mentions:S(E(n().trim().min(1)).optional(),{code:"conversation_mention_unknown",hint:'Member participant ids this message addresses, e.g. ["agent:crew"]. In a room only a mentioned agent answers.',description:"Members this addresses. In a room, the agents that answer."}),authorId:S(n().trim().min(1).optional(),{code:"conversation_author_required",hint:"Who said it. A key bound to a participant fills this in and may name no one else; an unbound key must name the author.",description:"The human member who said it. Filled in from a participant-bound key."})}),Kt=r({sessionKey:S(n().min(1),{code:"session_key_required",hint:'Send { "sessionKey": "local:abc123" }: the key a message would name.',description:"The key a message would carry as its sessionKey."}),from:Fe.optional()}),Ht=r({from:Fe.optional()}),Gt=r({participantId:Dt("assignee"),channelIds:S(E(n().min(1)).optional(),{code:"assignee_channel_ids_invalid",hint:'A list of the owner\'s own channel senders as `<channel type>:<id or handle>`, e.g. ["telegram:@moeen", "whatsapp:+880 1711-223344", "slack:U0123ABC"].',description:"The owner's own channel senders (pilot.15), matched like allowFrom: case folded, `@` optional, a phone number by its digits. A turn from one of these acts as the owner: it keeps the owner's personal tools (Composio, MCP servers marked personal) and, under sessions.scope owner, lands in the owner's conversation. Absent, no channel turn does."})}),qt=r({presence:S(D(["online","offline"]),{code:"presence_invalid",hint:'Send { "presence": "online" } or "offline". It is pushed by you, never inferred; until it is, a person reads as online and no agent stands in for them.',description:"Whether the person is there. Decides whether their agent stands in for them in a DM."})}),Wt=r({scope:S(n().trim().min(1),{code:"memory_scope_invalid",hint:'A shared scope: "space", "owner:<participantId>" or "project:<projectId>".',description:"Where the note goes. `owner:<id>` is written only by that person; `space` by an admin or the designated space writer; a project by an admin."}),text:S(n().trim().min(1),{code:"memory_note_empty",hint:'Send { "scope": "space", "text": "…" } — one or two sentences worth remembering.',description:"The note. Recalled into an agent's prompt when a turn is about it."})}),Vt=r({name:ie(n().min(1).optional(),"A display name for the embedder's own listing."),agents:S(E(n().trim().min(1)).optional(),{code:"project_agents_invalid",hint:'Agent ids, bare ("crew", not "agent:crew"). Given, it replaces the membership; omitted, it is left alone.',description:"The agents that share this project's memory. Replaces the list when given."})}),Qt=r({writer:S(n().trim().min(1),{code:"space_writer_invalid",hint:'A registered participant id, or "agent:<agentId>" for an agent whose memory_write should go to the space.',description:"The one non-admin who may write the space. An agent named here saves every memory_write to the space, so name one that holds nobody's private context."})}),Xt=r({bundle:S(x(n(),He()),{code:"bundle_files_invalid",hint:'Send { "bundle": <the body GET /v1/agents/:id/export returned> }.',description:"A bundle from GET /v1/agents/:id/export: MEMORY.md, memory/<name>.md and knowledge/<name>.md, nothing else."}),mode:S(D(["skip","overwrite"]).optional(),{code:"bundle_mode_invalid",hint:'Either "skip" (keep a knowledge file that exists, the default) or "overwrite". Memory is always merged note by note.',description:"What to do with a knowledge file the agent already has. Memory is merged either way."})}),Zt=r({approve:S(R(),{code:"action_decision_required",hint:'Send { "approve": true } to run the queued call as it was asked, or false to decline it.',description:"Run the queued call (true) or decline it (false)."})}),en=r({url:S(n().min(1),{code:"webhook_url_invalid",hint:"Send an absolute https:// URL. A receiver on a private network needs the operator to allow it in WEBHOOK_ALLOW.",description:"Where deliveries are POSTed. Checked against every address it resolves to, at subscribe and at every send."}),types:S(E(n()).min(1),{code:"webhook_types_required",hint:'Send { "types": ["turn.end", "approval.requested"] }. Any event type except model.chunk; the wire spec lists them.',description:"The event types to deliver. `model.chunk` is not deliverable."}),agents:S(E(n()).min(1).optional(),{code:"webhook_scope_invalid",hint:"Send agent ids this credential can reach, or leave agents out to hear every agent it can reach.",description:"Narrow the subscription to these agents. It can never hear more than the creating credential reaches."})}),tn=r({values:S(x(n(),S(n(),{code:"secret_value_invalid",hint:"Send each value as a non-empty string.",description:"One variable's value. Written to the agent's .env at 0600; never returned."})),{code:"secrets_values_required",hint:'Send { "values": { "MODEL_API_KEY": "…" } }. GET /v1/agents/:id/secrets lists the variables this agent reads.',description:"Variables to write into the agent's .env, keyed by name. Only names the agent's manifest reads are accepted."})});function B(a,e){let d=a.safeParse(e??{});if(d.success)return{ok:!0,value:d.data};let u=d.error.issues[0],p=(u?.path??[]).filter((N)=>typeof N==="string"),m=Pn(a,p);return{ok:!1,error:{...{code:"request_body_invalid",message:p.length===0?u?.message??"The request body is invalid.":`${p.join(".")}: ${u?.message}`,hint:"The field above is the one to fix. GET /v1/openapi.json describes every body this server accepts, including the error code each field produces."},...m?.code===void 0?{}:{code:m.code},...m?.hint===void 0?{}:{hint:m.hint},...p.length===0?{}:{field:p.join(".")}}}}function Pn(a,e){let d=a,u=Ee(a);for(let p of e){if(d=In(d,p),d===void 0)break;u=Ee(d)??Ee(nn(d))??u}return u}function Ee(a){let e=a?.meta();if(e?.code===void 0&&e?.hint===void 0)return;return e}function In(a,e){let d=nn(a),u=d?.shape;if(u?.[e]!==void 0)return u[e];return d?.def?.valueType}function nn(a){let e=a;for(let d=0;d<8&&e!==void 0;d+=1){let u=e.def?.innerType;if(u===void 0)return e;e=u}return e}var $n={"GET /v1/health":{summary:"Liveness, the version, and how many agents are hosted."},"GET /v1/ready":{summary:"Whether a turn can be served yet.",statuses:[{code:503,when:"still starting; channels may still be connecting"}]},"GET /v1/activity":{summary:"Whether the process is idle, and when it must next be woken. For an external waker.",statuses:[{code:403,when:"the key is scoped to agents or sessions"}]},"GET /v1/agents":{summary:"Every agent this server knows about, hosted or switched off."},"GET /v1/agents/:id":{summary:"One agent, with its dialect, window, counts and warnings."},"GET /v1/backup":{summary:"The silo as a tar.gz: a consistent store snapshot and every hosted agent's directory, with a backup.json manifest. No .env or .git unless asked for. An admin key with no agents scope.",query:[{name:"include",about:"Any of env, git, home, comma-separated: each agent's .env (its secrets), its .git directories, and the rest of the state directory under home/."}],statuses:[{code:400,when:"include names something other than env, git or home, or home on a server with no state directory"},{code:403,when:"the key is scoped to some agents"}]},"GET /v1/agents/:id/export":{summary:"A slice of the agent as a JSON bundle: its carried memory file, memory archive and knowledge. Never the manifest, secrets or skills."},"POST /v1/agents/:id/import":{summary:"Merge a bundle into the agent: memory note by note, knowledge kept or overwritten. Reloads when the carried file or knowledge changed, and restores everything if that reload refuses.",body:Xt,statuses:[{code:400,when:"a path a bundle cannot carry, or a bundle the agent would not load"}]},"GET /v1/agents/:id/workspace":{summary:"The files the agent's prompt is built from: name, tier, field, whether it exists, size.",statuses:[{code:409,when:"the manifest does not parse, so its files cannot be named"}]},"GET /v1/agents/:id/workspace/:file":{summary:"One declared workspace file's text, for an editor to show before it replaces it.",statuses:[{code:404,when:"not a file the manifest declares"},{code:409,when:"the manifest does not parse"}]},"PUT /v1/agents/:id/workspace/:file":{summary:"Replace one of the agent's declared workspace files; reload it, or diagnose it when it is not running.",body:Et,statuses:[{code:400,when:"a running agent would not load with the new text (the old text is put back)"},{code:404,when:"a file the manifest does not declare"},{code:409,when:"an agent with no manifest file, or one whose manifest does not parse"}]},"GET /v1/agents/:id/vars":{summary:"The template an agent was made from and the plain variable values it was last rendered with. Secrets never appear.",statuses:[{code:409,when:"an agent with no template record"},{code:501,when:"a server with no templates directory (an embedded handler)"}]},"PATCH /v1/agents/:id/vars":{summary:"Apply changed template variables: re-render the files nobody edited since they were rendered, then reload.",body:Ct,statuses:[{code:202,when:"files changed and a turn is running: the reload lands when it ends"},{code:400,when:"a secret or undeclared variable, or a result the agent would not load (every file is put back)"},{code:409,when:"the agent was not made from a template on 0.2.0 or later"},{code:501,when:"this server has no templates"}]},"POST /v1/agents/:id/tools/refresh":{summary:"Fetch the tool providers' catalogues and schemas now, and reload the agent only if what it serves changed.",body:_t,statuses:[{code:202,when:"something changed and a turn is running: the reload lands when it ends"},{code:400,when:"a provider the agent does not have, or a reload the agent refuses"}]},"POST /v1/agents/:id/reload":{summary:"Re-read the manifest by replacing the agent with a new instance.",statuses:[{code:409,when:"a turn is running — it is not aborted to apply a change"},{code:400,when:"a team member, which has no manifest of its own"}]},"GET /v1/provision":{summary:"The questions creating an agent asks, and whether this server can answer them."},"POST /v1/agents":{summary:"Create an agent, from answers or from a template, and adopt it into this host, live.",body:Mt,statuses:[{code:201,when:"created; `adopted` is empty with an `error` if it is not running"},{code:403,when:"neither a loopback bind nor an authenticated admin credential"},{code:501,when:"this server has no provisioner"}]},"POST /v1/webhooks":{summary:"Subscribe a URL to event types. The signing secret is returned once.",body:en,statuses:[{code:201,when:"created; `secret` is in this response and no other"},{code:400,when:"a refused URL, an undeliverable type, or agents outside this key's reach"}]},"POST /v1/participants":{summary:"Register a human participant under the embedder's own id. No account is stored.",body:Lt,statuses:[{code:201,when:"registered, or updated if the id existed"}]},"GET /v1/participants":{summary:"The registered human participants."},"DELETE /v1/participants/:participantId":{summary:"Remove a participant and their conversation memberships."},"POST /v1/conversations":{summary:"Create a room or a DM among participants and agents (agent:<id>).",body:Ut,statuses:[{code:201,when:"created"},{code:403,when:"a participant-bound key creating a conversation it is not in"}]},"GET /v1/conversations":{summary:"The conversations this credential can see."},"GET /v1/conversations/:conversationId":{summary:"One conversation and its members."},"PATCH /v1/conversations/:conversationId/members":{summary:"Add or remove members of a room.",body:Bt},"POST /v1/conversations/:conversationId/messages":{summary:"Post a human member's message. In a room only the mentioned agents answer; in a DM the agent always does. Their replies arrive as conversation.message.",body:Ft,statuses:[{code:202,when:"logged; the turns it starts run behind the response"},{code:403,when:"a participant-bound key naming another author"}]},"GET /v1/conversations/:conversationId/messages":{summary:"The conversation's log, oldest first, after a sequence number."},"PUT /v1/participants/:participantId/presence":{summary:"Push whether a person is there. In a DM between two people, an offline person's agent stands in for them.",body:qt,statuses:[{code:403,when:"a participant-bound key setting someone else's presence"}]},"POST /v1/memory/notes":{summary:"Add a note to a shared memory scope — the space, a person's owner scope, or a project. Agents recall it when a turn is about it.",body:Wt,statuses:[{code:403,when:"this participant may not write that scope"},{code:404,when:"the scope's owner or project does not exist"}]},"GET /v1/memory/notes":{summary:"Every note in one shared scope, oldest first. An owner scope is readable by its owner."},"DELETE /v1/memory/notes/:noteId":{summary:"Remove a note. Whoever may write its scope may remove it."},"GET /v1/participants/:participantId/memory/reads":{summary:"The person's audit: every time an agent recalled their owner scope for somebody else, stand-ins included."},"GET /v1/projects":{summary:"Projects, each with the agents that share its memory."},"PUT /v1/projects/:projectId":{summary:"Define a project, or replace which agents share its memory. An admin's act.",body:Vt},"DELETE /v1/projects/:projectId":{summary:"Remove a project and its notes."},"PUT /v1/memory/space/writer":{summary:"Name the one non-admin who may write the space. An agent named here saves its memory_write to the space.",body:Qt},"GET /v1/actions":{summary:"Mutating calls stand-ins queued for their owners. A member-bound key sees its own."},"POST /v1/actions/:actionId":{summary:"Approve or decline a queued action. Approved, the exact call runs as the owner's agent and the outcome is posted in the DM.",body:Zt,statuses:[{code:404,when:"no such action, or not this key's to decide"},{code:409,when:"already decided"}]},"PUT /v1/agents/:id/assignee":{summary:"Record which member an agent works for. An admin participant's act.",body:Gt},"GET /v1/agents/:id/assignee":{summary:"Who the agent is assigned to, as `{id, assignment}`; `assignment` is null when nobody."},"DELETE /v1/agents/:id/assignee":{summary:"Clear an agent's assignment."},"GET /v1/webhooks":{summary:"The subscriptions this credential can see, with their delivery health. Never a secret."},"DELETE /v1/webhooks/:webhookId":{summary:"Delete a subscription and anything it still owed.",statuses:[{code:404,when:"no such subscription, or one outside this key's reach"}]},"GET /v1/usage":{summary:"What every agent in scope cost, per model call, grouped by agent, model, day or sender.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/usage":{summary:"What this agent cost, from the meter.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/turns":{summary:"Every turn this agent has taken, newest first, across sessions, paged by `before`.",statuses:[{code:400,when:"`limit` or `before` is not a positive whole number"}]},"GET /v1/templates":{summary:"The templates an agent can be created from, and the variables each declares."},"GET /v1/agents/:id/secrets":{summary:"Which variables the agent's manifest reads, and whether each is set. Never a value.",statuses:[{code:501,when:"this server has no credential writer"}]},"PUT /v1/agents/:id/secrets":{summary:"Write the agent's credentials into its .env and apply them: reload or adopt.",body:tn,statuses:[{code:200,when:"written; `applied` says whether the agent is running on them"},{code:400,when:"a variable the manifest does not read, or an empty value"},{code:501,when:"this server has no credential writer"}]},"DELETE /v1/agents/:id":{summary:"Delete an agent for good: off this host, its rows out of the store, its directory off disk. Needs ?confirm=<id>.",statuses:[{code:400,when:"no ?confirm=<id>"},{code:409,when:"two sandbox directories declare this id"},{code:501,when:"this server cannot delete agents"}]},"POST /v1/agents/:id/stop":{summary:"Switch an agent off durably and drop it from this host now.",body:Rt,statuses:[{code:409,when:"a turn is running"}]},"POST /v1/agents/:id/start":{summary:"Switch it back on and have this host adopt it.",statuses:[{code:501,when:"this server cannot look up manifests"}]},"POST /v1/agents/:id/messages":{summary:"Start a turn. Returns once accepted; the turn runs detached.",body:Tt,statuses:[{code:202,when:"accepted"},{code:429,when:"over limits.maxConcurrentTurns or limits.tokens; nothing recorded"}]},"POST /v1/agents/:id/deliveries":{summary:"Send exact text on one of the agent's channels, with no turn. It joins that conversation's history as the agent's.",body:At,statuses:[{code:202,when:"queued, or already queued under this key"},{code:404,when:"the agent has no running channel with that id"}]},"POST /v1/agents/:id/turns/:turnId/stop":{summary:"Cooperatively stop a turn this API started.",statuses:[{code:409,when:"no cancel handle — a channel or schedule started it"}]},"GET /v1/agents/:id/turns/:turnId/stream":{summary:"One turn's events as SSE, replayed from the start and then live.",query:[{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/events":{summary:"Every event this process emits, as SSE. The firehose.",query:[{name:"agentId",about:"Narrow to one agent."},{name:"sessionKey",about:"Narrow to one conversation."},{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/agents/:id/approvals":{summary:"Questions waiting on a person, oldest first."},"POST /v1/agents/:id/approvals/:approvalId":{summary:"Answer one blocked tool call.",body:Pt},"POST /v1/keys":{summary:"Mint an operator key. The secret is returned once and never again.",body:It,statuses:[{code:201,when:"minted"}]},"GET /v1/keys":{summary:"Every key, live and revoked. Never a secret."},"DELETE /v1/keys/:keyId":{summary:"Revoke a key. A soft delete; the row survives."},"GET /v1/agents/:id/turns/:turnId":{summary:"One turn's stored row."},"GET /v1/agents/:id/sessions":{summary:"Conversations, most recently active first."},"GET /v1/agents/:id/sessions/:key":{summary:"One conversation's summary."},"GET /v1/agents/:id/sessions/:key/messages":{summary:"A page of a conversation's messages.",query:[{name:"limit",about:"How many to return."},{name:"before",about:"Page backwards from this message id."}]},"DELETE /v1/agents/:id/sessions/:key":{summary:"Drop a conversation's history, turns and derived index."},"POST /v1/agents/:id/sessions/:key/phase":{summary:"Move a session into a declared phase.",body:$t},"POST /v1/agents/:id/sessions/:key/compact":{summary:"Fold a conversation's older turns into a saved digest; the next turn starts from it, and every message stays stored.",body:Ot},"POST /v1/agents/:id/sessions/:key/recall":{summary:"Keep a conversation out of history recall, or put it back; its messages stay.",body:zt},"POST /v1/agents/:id/sessions/resolve":{summary:"The conversation a message naming this sessionKey would run in, before sending it; nothing changes.",body:Kt},"POST /v1/agents/:id/sessions/rotate":{summary:"Start the caller's conversation afresh on every surface (sessions.scope owner or peer).",body:Ht},"GET /v1/agents/:id/config":{summary:"Every manifest field this surface may set, what it does, and its current value."},"PATCH /v1/agents/:id/config":{summary:"Set one manifest field, then replace the agent so it takes effect.",statuses:[{code:409,when:"the field carries a confirm sentence and `confirm` was not true"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:400,when:"the path is not settable here, or the result would not validate"}]},"PATCH /v1/agents/:id/channels/:channelId":{summary:"Connect or disconnect a channel, and set its credential.",statuses:[{code:400,when:"neither `enabled` nor `credential` was sent, or the channel is unknown"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:501,when:"the host supplied no channel actions"}]},"POST /v1/agents/:id/channels/:channelId/unpair":{summary:"Forget a channel's stored pairing, so the next start offers a new code.",statuses:[{code:404,when:"this agent has no such channel"},{code:409,when:"the channel stores no pairing — a typed credential is a PATCH"}]},"GET /v1/agents/:id/schedules":{summary:"Every schedule, from the store."},"POST /v1/agents/:id/schedules":{summary:"Create a schedule. Validated by the manifest's own schedule rules.",statuses:[{code:201,when:"created"}]},"GET /v1/agents/:id/schedules/preview":{summary:"What an expression means before it is written: the next instants, zone and jitter.",statuses:[{code:400,when:"an expression core's own parser refuses, with its hint"}]},"GET /v1/agents/:id/schedules/:sid":{summary:"One schedule's row."},"PATCH /v1/agents/:id/schedules/:sid":{summary:"Replace a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so reconciliation would undo the write"}]},"DELETE /v1/agents/:id/schedules/:sid":{summary:"Delete a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so the next boot would re-create it"}]},"POST /v1/agents/:id/schedules/:sid/run":{summary:"Fire a schedule now, out of band.",statuses:[{code:429,when:"over a governor limit; nothing recorded"}]},"GET /v1/agents/:id/tools":{summary:"The resolved catalogue, with trust and phases."},"GET /v1/agents/:id/skills":{summary:"What the skills index holds."},"GET /v1/agents/:id/context":{summary:"The prompt the next turn would be given, without running one.",query:[{name:"sessionKey",about:"Which conversation to assemble for."},{name:"input",about:"Pretend this is the next message."}]},"POST /v1/channels/:channelId/webhook/:agentId":{summary:"A channel provider's webhook. Open by design; the provider authenticates itself."},"GET /v1/openapi.json":{summary:"This document."},"GET /docs":{summary:"A browser reference over this document."}};function On(a){return a.startsWith("/v1/")||a==="/docs"}function zn(a){let e={};for(let d of a.routes){if(!On(d.pattern))continue;let u=$n[`${d.method} ${d.pattern}`];if(u===void 0)continue;let p=d.pattern.replace(/:([A-Za-z0-9_]+)/g,"{$1}"),m=[...d.pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((F)=>({name:F[1],in:"path",required:!0,schema:{type:"string"}})),b=(u.query??[]).map((F)=>({name:F.name,in:"query",required:!1,description:F.about,schema:{type:"string"}})),N={};for(let F of u.statuses??[])N[String(F.code)]={description:F.when};if(N["200"]===void 0&&N["201"]===void 0){if(N["202"]===void 0)N["200"]={description:"OK"}}if(N["401"]={description:"No credential, or one this server does not accept."},d.pattern.includes(":id"))N["404"]={description:"No such agent, or it is switched off."};e[p]??={};let V={summary:u.summary,...m.length+b.length===0?{}:{parameters:[...m,...b]},responses:N};if(u.body!==void 0)V.requestBody={required:!0,content:{"application/json":{schema:Ys(u.body,{target:"draft-2020-12",io:"input"})}}};e[p][d.method.toLowerCase()]=V}return{openapi:"3.1.0",info:{title:"Dispach agent server",version:xe,description:"Generated from the router table and the request schemas — see openapi.ts. The binding contract is docs/04-SPEC-WIRE.md, which is checked against the code; @dispach/client's types are the response reference."},...a.serverUrl===void 0?{}:{servers:[{url:a.serverUrl}]},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer",description:"An operator key or the configured token."}},schemas:{Error:{type:"object",description:"Every failure has this shape. `hint` is never absent — it is the part that says what to do.",properties:{error:{type:"object",required:["code","message","hint"],properties:{code:{type:"string"},message:{type:"string"},hint:{type:"string"},field:{type:"string"}}}}}}},security:[{bearer:[]}],paths:e}}var Rn=new Set(["127.0.0.1","::1","localhost","[::1]"]);function Se(a){return Rn.has(a.toLowerCase())}function me(a){let e=a.trim();if(e===""||e.toLowerCase()==="null")return;try{return new URL(e.includes("://")?e:`http://${e}`).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return}}function tt(a){return Se(a)||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(a)}function Ne(a,e){let d=Se(e.host),u=a.headers.get("host"),p=a.headers.get("origin");if(d){let b=u===null?void 0:me(u),N=e.allowedHosts??[];if(!(b!==void 0&&(tt(b)||N.some((F)=>me(F)===b))))return{code:"host_not_allowed",message:`This server does not answer to the host ${u??"(absent)"}.`,hint:"It is bound to loopback, so only a loopback name or address can legitimately reach it — a request addressed to any other name arrived through DNS pointed at this machine, which is how a web page reaches a local server it was never given access to. Add the name to server.allowedHosts if a proxy on this machine needs it.",field:"server.allowedHosts"}}if(p===null)return;let m=me(p);if(m!==void 0){if(tt(m))return;if((e.allowedOrigins??[]).some((b)=>me(b)===m))return;if(!d&&u!==null&&me(u)===m)return}return{code:"origin_not_allowed",message:`Refusing a request from the origin ${p}.`,hint:d?"This server is bound to loopback, so a page served from anywhere else has no business calling it. Add the origin to server.allowedOrigins if you meant to allow it.":"Only a page served from this server's own host may call it. Add the origin to server.allowedOrigins if you meant to allow it — there is no wildcard, deliberately.",field:"server.allowedOrigins"}}function Mn(a,e){let d=a.headers.get("origin");if(d===null)return{};if(Ne(a,e)!==void 0)return{};return{"access-control-allow-origin":d,vary:"Origin"}}function Dn(a,e){let d=a.headers.get("access-control-request-headers");return{"access-control-allow-methods":e.join(", "),"access-control-allow-headers":d??"authorization, content-type","access-control-max-age":"600"}}function Ce(a,e){if(a.kind!=="key")return a.kind!=="claim";let d=a.scope?.can;return d===void 0||d.includes(e)}function X(a,e){if(a.kind!=="key")return a.kind!=="claim";let d=a.scope?.agents;return d===void 0||d.includes(e)}function de(a,e){if(a.kind!=="key")return a.kind!=="claim";let d=a.scope?.sessions;if(d===void 0)return!0;if(e.startsWith(d.endsWith("*")?d.slice(0,-1):d))return!0;let u=a.scope?.participant;return u!==void 0&&(Vr(e,`owner:${u}`)||Vr(e,`peer:${u}`))}function rn(a,e){if(e.sessionKey===void 0||de(a,e.sessionKey))return!0;return e.parentSessionKey!==void 0&&de(a,e.parentSessionKey)}function ve(a){if(a.kind==="claim")return{agentIds:[]};if(a.kind!=="key")return{};let e=a.scope?.agents,d=a.scope?.sessions;return{...e===void 0?{}:{agentIds:e},...d===void 0?{}:{sessionPrefix:d.endsWith("*")?d.slice(0,-1):d}}}function Ke(a){if(a.kind!=="key")return!1;let e=a.scope;return e!==void 0&&(e.agents!==void 0||e.sessions!==void 0||e.can!==void 0)}function we(a,e){let d=a.kind==="key"?a.scope?.participant:void 0;if(d===void 0)return{ok:!0,from:e};if(e===void 0)return{ok:!0,from:{id:d,kind:"user"}};if(e.id===d&&e.kind==="user")return{ok:!0,from:e};return{ok:!1,error:{code:"sender_not_bound_participant",message:`This key speaks for ${d}, and the message names ${e.kind} ${e.id}.`,hint:`A key bound to a participant starts turns only as that participant, so the tools the turn calls act for them. Omit from (it is filled in), or send from.id "${d}" with kind "user". A backend that names senders itself needs a key minted without scope.participant.`,field:"from"}}}async function Be(a,e,d,u,p){let m=await a.resolveSessionKey(d,{source:"api",...u===void 0?{}:{from:u},...p===void 0?{}:{peerAsk:p}});return de(e,m)?m:d}class sn{#e=[];add(a,e,d,u){return this.#e.push({method:a.toUpperCase(),pattern:e,handler:d,capability:u.capability,streaming:u.streaming===!0,segments:nt(e)}),this}routes(){return this.#e.map(({method:a,pattern:e,handler:d,streaming:u,capability:p})=>({method:a,pattern:e,handler:d,streaming:u,capability:p}))}match(a,e){let d=nt(e),u=[];for(let p of this.#e){let m=Ln(p.segments,d);if(m===void 0)continue;if(u.push(p),p.method===a.toUpperCase())return{kind:"found",handler:p.handler,params:m,streaming:p.streaming,capability:p.capability}}if(u.length>0)return{kind:"method",allowed:[...new Set(u.map((p)=>p.method))]};return{kind:"none"}}}function nt(a){return a.split("/").filter((e)=>e!=="")}function Ln(a,e){if(a.length!==e.length)return;let d={};for(let[u,p]of a.entries()){let m=e[u];if(m===void 0)return;if(p.startsWith(":")){try{d[p.slice(1)]=decodeURIComponent(m)}catch{return}continue}if(p!==m)return}return d}var on=15000;function Un(a){let e=[];if(a.event!==void 0)e.push(`event: ${a.event}`);if(a.id!==void 0)e.push(`id: ${a.id}`);let d=typeof a.data==="string"?a.data:JSON.stringify(a.data);for(let u of d.split(`
3
- `))e.push(`data: ${u}`);return`${e.join(`
2
+ import{V,Yt,_,ne,Ye,Jt,Cr,hr,Br,Bs,qr,Vr,ys,Qs,so,ms,Ss,ws,Wr,Ds,qt,bs,Zr,PA,yr,Xr,ei,go,ti,Rs,sA,un,co,GA,ni,_s,ks,vs,oi,Ls,Ps,Gs,Fs,Us,xs}from"./index-bhj4pmrx.js";import{Ys,t,r,f,me,a,i,g,Xe,x,y,de}from"./index-ss77hvwy.js";import{existsSync as ke,mkdirSync as Jn,readFileSync as ht,rmSync as Xn,statSync as Zn,writeFileSync as ft}from"node:fs";import{mkdtemp as ea,readdir as ta,readFile as et,rm as na}from"node:fs/promises";import{tmpdir as aa}from"node:os";import{basename as Te,dirname as Ae,join as tt,relative as ra,resolve as we,sep as sa}from"node:path";import{createReadStream as Rr}from"node:fs";import{stat as Mr}from"node:fs/promises";import{Readable as _t}from"node:stream";import{createGzip as Lr}from"node:zlib";function Yr(s={}){let e=s.now??(()=>new Date),d=new Map;return{approver:(b)=>new Promise((w)=>{let N={pending:{approvalId:b.approvalId,agentId:b.agentId,sessionKey:b.sessionKey,slug:b.slug,callId:b.callId,match:b.match,mutating:b.mutating,reason:b.reason,requestedAt:e().toISOString()},settle:(A)=>{d.delete(b.approvalId),w(A)}};d.set(b.approvalId,N),b.signal.addEventListener("abort",()=>N.settle(!1),{once:!0})}),pending:(b)=>[...d.values()].map((w)=>w.pending).filter((w)=>w.agentId===b).sort((w,N)=>w.requestedAt.localeCompare(N.requestedAt)),resolve:(b,w)=>{let N=d.get(b);if(N===void 0)return!1;return N.settle(w),!0},get size(){return d.size}}}function v(s,e,d={}){return new Response(JSON.stringify({error:s}),{status:e,headers:{"content-type":"application/json; charset=utf-8",...d}})}function mt(){return v({code:"unauthorized",message:"Missing or invalid bearer token.",hint:"Send Authorization: Bearer <token>, where the token is either the value of the variable named by server.tokenEnv or an operator key from POST /v1/keys. A revoked key, an expired one and a wrong one answer the same way on purpose."},401)}function Xt(){return v({code:"claim_spent",message:"That claim has already been exchanged.",hint:"A claim is good for one key. Use the key it minted; if it is lost, restart with --claim to print a new one — a claim lives in the process rather than the database, so it never outlives the boot that printed it."},401)}function ia(s,e){return v({code:"capability_required",message:`This credential cannot ${e}.`,hint:`The key is scoped, and "${s}" is not among its capabilities. GET /v1/keys shows what each key may do; mint another with POST /v1/keys, or use the server token. An unscoped key has all of them.`,field:"scope.can"},403)}function gt(s,e){if(s.length!==e.length)return!1;let d=0;for(let p=0;p<s.length;p+=1)d|=s.charCodeAt(p)^e.charCodeAt(p);return d===0}function oa(s){let e=s.headers.get("authorization")??"";return e.startsWith("Bearer ")?e.slice(7):""}async function la(s){let e=oa(s.request);if(s.expected!==void 0&&gt(e,s.expected))return{kind:"token"};if(e!==""){let d=await s.keys.findLive(await hr(e),new Date(s.at).toISOString());if(d!==void 0)return await s.keys.touch(d.keyId,new Date(s.at).toISOString()),{kind:"key",keyId:d.keyId,label:d.label,...d.scope===void 0?{}:{scope:d.scope}};if(s.claim!==void 0&&gt(e,s.claim.token)){if(s.request.method!=="POST"||s.pathname!=="/v1/keys")return mt();if(!s.claim.live())return Xt();return{kind:"claim"}}}return mt()}var Ee="dispach.bearer";function ca(s){let e=s.headers.get("sec-websocket-protocol");if(e===null)return;let d=e.split(",").map((b)=>b.trim()),p=d.indexOf(Ee);return p===-1?void 0:d[p+1]??""}function da(s,e){let d=new Headers(s.headers);return d.set("authorization",`Bearer ${e}`),new Request(s.url,{method:s.method,headers:d})}function P(s,e){return s.meta({...e})}function pe(s,e){return s.meta({description:e})}var st=i({id:P(t().trim().min(1),{code:"sender_invalid",hint:'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.',description:"Stable identifier for the sender. Appears on the turn row and in events."}),kind:P(y(qt,{error:(s)=>{let e=typeof s.input==="string"?s.input:void 0,d=e===void 0?void 0:Yt(e,qt);return`from.kind must be one of: ${qt.join(", ")}.${d===void 0?"":` Did you mean "${d}"?`}`}}),{code:"sender_invalid",hint:'This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".',description:'The trust boundary. "agent" fences the text as data and blocks mutating tools for the whole turn.'}),name:P(t().optional(),{code:"sender_invalid",hint:"A display name, shown beside the sender id. Omit it rather than sending an empty string.",description:"Human-readable name for the sender."})}).meta({description:"Attribution for a turn somebody other than the token-holder is sending. Omit for your own."}),ua=P(Xe([de("none"),i({channel:t().min(1),to:t().min(1)})]),{code:"deliver_invalid",hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',description:'Where the reply goes. "none" leaves it on the event stream and in the store.'}),vt=8000,Zt=i({text:P(t().trim().min(1),{code:"message_text_required",hint:'Send { "text": "..." }. An empty turn would be billed for a full prompt and produce nothing.',description:"What to say to the agent."}),sessionKey:pe(t().min(1).optional(),"Which conversation this belongs to. Defaults to `api:default`."),role:P(t().trim().min(1).optional(),{code:"model_role_unknown",hint:"Name a role declared under model: in the manifest (GET /v1/agents/:id/config lists them), or omit role to run on main. A person adds one with PATCH /config path model.<name>.",description:"A model role to run this turn on instead of main: one declared under `model:`, as a schedule names one with `role:`. This turn only; the conversation's other turns are unaffected. Refused before the turn starts when no such role is declared."}),runtimeNote:P(t().trim().min(1).max(vt).optional(),{code:"message_note_invalid",hint:`Send runtimeNote as non-empty text of at most ${vt} characters: the active project, today's date in the person's zone, an attachment's extracted text.`,description:"Your application's note about this message: shown to the model in its own block before the text, labelled as not written by the person, for this turn only. Kept on the turn record (`GET …/turns`), never in history. Refused when `from` is an agent."}),peerAsk:P(i({askedBy:t().trim().min(1).max(200)}).strict().optional(),{code:"message_peer_ask_invalid",hint:'Send { "peerAsk": { "askedBy": "<silo>/<agent>" } }, naming the agent that asked, or omit it.',description:"Marks this turn as another agent's ask (`docs/24-SPEC-PEER-ASK.md`): it runs without `handoff` and `ask_agent`, so it is one hop, and the agent is told who asked. It only narrows what the turn may do, so any caller may set it; the control plane's relay always does."}),images:P(a(i({path:t().optional(),data:t().optional(),mediaType:t().optional()}).strict()).optional(),{code:"message_images_invalid",hint:`Send images as [{ "path": "files/…/shot.png" }] (relative to the agent's directory), or [{ "data": "<base64>", "mediaType": "image/png" }].`,description:"Images sent with this message: PNG, JPEG, GIF or WebP, at most five, 3.75 MB each. A path inside the agent's directory, or inline base64 (within the 1 MB body limit). The model receives them on this turn; history keeps an `[image: <path>]` line."}),deliver:ua.optional(),from:st.optional(),stream:pe(f().optional(),"Stream the turn's events inline as SSE rather than returning a handle."),chunks:pe(f().optional(),"Include per-token `model.chunk` frames. Off by default — the reader decides."),children:pe(f().optional(),"Include the events of subagents this turn runs (they carry `parentTurnId`). Off by default.")}),en=i({content:P(t(),{code:"workspace_content_required",hint:'Send { "content": "<the whole file>" }. It replaces the file; frontmatter included.',description:"The file's new text, in full, frontmatter included."})}),tn=i({vars:P(x(t(),P(t(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})),{code:"vars_required",hint:'Send { "vars": { "userName": "…" } }: the template variables to change. The rest keep the values the agent was made with.',description:"The template variables to change. Only files nobody has edited since they were rendered are rewritten."})}),nn=i({providers:P(a(t().min(1)).min(1).optional(),{code:"tools_refresh_providers_invalid",hint:`Name provider ids from the agent's tools.providers, e.g. { "providers": ["composio"] }, or send {} to refresh every one.`,description:"Which providers to refresh. Omit for all of them."})}),rn=i({channel:P(t().min(1),{code:"delivery_channel_required",hint:`Name a channel id from the agent's manifest, e.g. { "channel": "tg", ... } — the id, not the type.`,description:"The channel id to send on."}),to:P(t().min(1),{code:"delivery_recipient_required",hint:"The channel's own address for the conversation: a Telegram chat id, a WhatsApp JID, a Slack channel id. The peer id an inbound message arrived with is always right.",description:"Who to send it to, in the channel's own addressing."}),text:P(t().trim().min(1),{code:"delivery_text_required",hint:'Send { "text": "..." }. An empty message has nothing to deliver.',description:"The exact text to send. No model turn runs."}),key:P(t().min(1),{code:"delivery_key_required",hint:"Any string unique to this send, such as your own message id. A retry with the same key is not sent or recorded twice.",description:"Idempotency key: a repeated key is accepted and does nothing."})}),sn=i({granted:P(f(),{code:"approval_decision_required",hint:'Send { "granted": true } or { "granted": false }. There is no default: one direction would deny a call over a typo and the other would grant one, and neither is a decision anybody made.',description:"Whether the blocked tool call may proceed."})}),pa=i({agents:a(t().min(1)).optional().meta({code:"key_scope_agents_invalid",hint:'Send { "agents": ["milo"] } — a list of agent ids. Omit it for a key that reaches every agent. An id naming no agent on this server is reported rather than silently matching nothing.',description:"Agent ids this key may reach. Absent means all of them."}),sessions:t().min(1).optional().meta({code:"key_scope_sessions_invalid",hint:'Send { "sessions": "team_42:" } — a session-key prefix, with an optional trailing "*". A prefix rather than a list, because the conversations this key will cover do not exist yet when it is minted.',description:"Session-key prefix. Absent means every session."}),can:a(y(["read","chat","write","admin","peer"])).optional().meta({code:"key_scope_can_invalid",hint:'Send { "can": ["chat", "read"] }. read (every GET), chat (send a message, answer an approval, stop a turn), write (schedules, phase, clearing a session), admin (keys, provisioning, start/stop/reload), and peer (a plugin route that asks for it — an A2A endpoint — and nothing else). Absent means all five; an empty array means none, and is honoured as written.',description:"Capabilities this key may exercise. Absent means all of them."}),participant:t().min(1).optional().meta({code:"key_scope_participant_invalid",hint:'Send { "participant": "user:018f…" } — the id this key speaks for. Every turn it starts acts for that participant: a from naming anyone else is refused, and an omitted one is filled in. Omit it for a backend that names senders itself.',description:"The participant every turn this key starts acts for. Absent: any sender."}),expiresIn:r().int().positive().optional().meta({code:"key_scope_expires_invalid",hint:'Send { "expiresIn": 3600 } — whole seconds from now, as a number. Relative rather than an absolute instant, because that would need the caller and this server to agree about the clock; the response reports the absolute expiresAt this server computed.',description:"Seconds until this key stops authenticating. Absent means never."})}),on=i({label:P(t(),{code:"key_label_required",hint:'Send { "label": "my browser" }. A label is required rather than defaulted because it is the only thing distinguishing two credentials in a listing, and "key 2" is a name nobody can act on when deciding which to revoke.',description:"How this credential is shown in a listing. Required; see `keyLabelProblem`."}),scope:pa.optional().meta({code:"key_scope_invalid",hint:'Send { "scope": { "agents": ["milo"], "can": ["chat"] } }, or omit it entirely for a key that reaches everything — which is what every key minted before scopes existed does.',description:"Opt-in narrowing. Absent is an unscoped key."})}),ln=i({phase:P(t().min(1),{code:"phase_invalid",hint:"Send the name of a phase this agent's manifest declares. `GET /v1/agents/:id` lists them.",description:"The phase to move this session into."})}),cn=i({keepTurns:P(r().int().min(1).optional(),{code:"compact_keep_invalid",hint:'Send { "keepTurns": 2 }, a whole number of at least 1, or omit it to keep the last 2 turns verbatim.',description:"How many of the newest turns stay verbatim. Everything before them becomes a digest and the person's requests. Default 2."})}),dn=i({recall:P(f(),{code:"recall_invalid",hint:'Send { "recall": false } to keep this conversation out of history recall, or true to put it back. Its messages are kept either way.',description:"Whether this conversation is indexed for history recall."})}),pn=i({reason:P(t().optional(),{code:"agent_stop_invalid",hint:"A short note, recorded on the row and shown wherever the agent is reported as off.",description:"Why, for whoever reads the listing later."})}),yt=i({path:P(t().min(1),{code:"config_path_unknown",hint:"GET /v1/agents/:id/config lists every field this surface may change, with what each one does.",description:"A dotted path, exactly as it appears in the manifest — `tools.pinned`, `model.main.id`."}),value:P(t().optional(),{code:"config_value_unreadable",hint:'Text, the way it is typed at a terminal: a bare word, a number, true or false, a list as ["a", "b"], or a map as {k: v}. Quote anything containing a colon or a "#". To take a field out, send { "remove": true } instead.',description:"The new value, as text. Read by the same parser the `config` command uses. Required unless `remove` is true."}),remove:P(de(!0).optional(),{code:"config_remove_invalid",hint:'Send { "path": "…", "remove": true } with no value to take a field out of the manifest, or a value to set it.',description:"Take the field out of the manifest instead of setting it, so it returns to its default. Checked like any edit: a required field is refused. A field that is not there is left as it is. Not sent together with `value`."}),confirm:pe(f().optional(),"Required only for a field whose own row carries a `confirm` sentence. Absent is not consent.")}),hn=yt.partial({path:!0}).extend({changes:pe(a(yt).min(1).optional(),"Several changes, each `{path, value}` or `{path, remove: true}`, applied in order and checked against the file as the earlier ones left it. One write and one reload; any refusal writes nothing. Sent instead of a top-level `path`.")}),fn=i({enabled:pe(f().optional(),"Switch the channel on or off. It takes effect at the agent's next start, because a channel is constructed at boot."),credential:P(t().min(1).optional(),{code:"channel_credential_unreadable",hint:"The value goes into the .env beside the manifest at 0600, under the variable that channel's own entry names. Send a non-empty string; an empty one fails the load exactly as a missing variable does.",description:"The channel's credential — a Telegram bot token. Never returned by any route; only whether it is set."})}),mn=i({answers:P(x(t(),P(t(),{code:"provision_answer_invalid",hint:"Answers arrive as strings from the terminal and from here, and are validated per step. Send the value as a string — including a boolean-looking choice, whose values are named in GET /v1/provision.",description:"One answer. Always text, whatever the step's type looks like."})).optional(),{code:"provision_answers_required",hint:'Send { "answers": { "name": "milo", … } }. Every step you leave out takes its default, exactly as `init --yes` does with flags; GET /v1/provision lists them.',description:"A subset of the wizard's steps, as strings. `GET /v1/provision` lists every step with its prompt, default and choices. Send this or `template`, not both."}),template:P(t().min(1).optional(),{code:"provision_template_invalid",hint:"Send the template's name as a string. GET /v1/templates lists what this server has.",description:"Create the agent from a template in this server's sandbox instead of from answers. Needs `name`; takes `vars`."}),name:P(t().optional(),{code:"provision_name_required",hint:'Send { "template": "…", "name": "Acme store" }. The id every route keys on is derived from it.',description:"The new agent's name, with `template`. Its slug becomes the id; the template sees both as {{agent.name}} and {{agent.id}}."}),vars:P(x(t(),P(t(),{code:"template_value_invalid",hint:"Template values are one line of text, sent as strings.",description:"One variable's value."})).optional(),{code:"template_value_invalid",hint:`Send { "vars": { "store": "Acme" } }, every value a string. GET /v1/templates lists each template's variables.`,description:"Values for the template's declared variables. A secret variable's value goes to the agent's .env and is never returned."})}),gn=(s)=>P(t().trim().min(1),{code:"participant_id_invalid",hint:'A participant id as your system knows the person, e.g. "user:018f…". Agents are "agent:<agentId>".',description:`The participant id${s===""?"":` (${s})`}.`}),vn=i({id:gn(""),name:pe(t().min(1).optional(),"A display name, shown to agents beside the id."),role:P(y(["admin","member"]).optional(),{code:"participant_role_invalid",hint:'Either "admin" (may assign agents to members) or "member". Omitted is "member".',description:'What the participant may do: "admin" also assigns agents.'}),title:pe(t().trim().min(1).max(120).optional(),"A job title, as the team knows the person. Told to an agent answering another member's agent about whom it represents and who is asking. Not a permission."),timezone:pe(t().trim().min(1).optional(),`An IANA timezone, such as "Europe/London". Told to an agent answering another member's agent, so "tomorrow at nine" means the right hour. Refused when the runtime does not know it.`),channelIds:P(a(t().min(1)).optional(),{code:"participant_channel_ids_invalid",hint:'A list of the person\'s own channel senders as `<channel type>:<id or handle>`, e.g. ["telegram:@ada", "whatsapp:+44 7700 900123"].',description:"The person's own channel senders, matched like allowFrom. Under sessions.scope peer, their turns from these channels and from the API share one conversation. Absent, a channel turn from them keeps its own."})}),yn=i({kind:P(y(["room","dm"]),{code:"conversation_kind_invalid",hint:'"dm" is one human and one agent and is always answered; "room" is anyone, and an agent answers only when mentioned.',description:"A room or a direct conversation."}),members:P(a(t().trim().min(1)).min(1),{code:"conversation_members_required",hint:'Participant ids: registered humans, and agents as "agent:<agentId>".',description:"Who is in it."}),title:pe(t().min(1).optional(),"A name for a room, for the embedder's own listing.")}),bn=i({add:P(a(t().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to add.",description:"Participant ids to add."}),remove:P(a(t().trim().min(1)).optional(),{code:"conversation_members_required",hint:"Participant ids to remove.",description:"Participant ids to remove."})}),wn=i({text:P(t().trim().min(1),{code:"message_text_required",hint:'Send { "text": "…" }.',description:"What was said."}),mentions:P(a(t().trim().min(1)).optional(),{code:"conversation_mention_unknown",hint:'Member participant ids this message addresses, e.g. ["agent:crew"]. In a room only a mentioned agent answers.',description:"Members this addresses. In a room, the agents that answer."}),authorId:P(t().trim().min(1).optional(),{code:"conversation_author_required",hint:"Who said it. A key bound to a participant fills this in and may name no one else; an unbound key must name the author.",description:"The human member who said it. Filled in from a participant-bound key."})}),xn=i({sessionKey:P(t().min(1),{code:"session_key_required",hint:'Send { "sessionKey": "local:abc123" }: the key a message would name.',description:"The key a message would carry as its sessionKey."}),from:st.optional()}),kn=i({from:st.optional()}),jn=i({participantId:gn("assignee"),channelIds:P(a(t().min(1)).optional(),{code:"assignee_channel_ids_invalid",hint:'A list of the owner\'s own channel senders as `<channel type>:<id or handle>`, e.g. ["telegram:@moeen", "whatsapp:+880 1711-223344", "slack:U0123ABC"].',description:"The owner's own channel senders (pilot.15), matched like allowFrom: case folded, `@` optional, a phone number by its digits. A turn from one of these acts as the owner: it keeps the owner's personal tools (Composio, MCP servers marked personal) and, under sessions.scope owner, lands in the owner's conversation. Absent, no channel turn does."})}),Sn=i({presence:P(y(["online","offline"]),{code:"presence_invalid",hint:'Send { "presence": "online" } or "offline". It is pushed by you, never inferred; until it is, a person reads as online and no agent stands in for them.',description:"Whether the person is there. Decides whether their agent stands in for them in a DM."})}),Nn=i({scope:P(t().trim().min(1),{code:"memory_scope_invalid",hint:'A shared scope: "space", "owner:<participantId>" or "project:<projectId>".',description:"Where the note goes. `owner:<id>` is written only by that person; `space` by an admin or the designated space writer; a project by an admin."}),text:P(t().trim().min(1),{code:"memory_note_empty",hint:'Send { "scope": "space", "text": "…" } — one or two sentences worth remembering.',description:"The note. Recalled into an agent's prompt when a turn is about it."})}),Tn=i({name:pe(t().min(1).optional(),"A display name for the embedder's own listing."),agents:P(a(t().trim().min(1)).optional(),{code:"project_agents_invalid",hint:'Agent ids, bare ("crew", not "agent:crew"). Given, it replaces the membership; omitted, it is left alone.',description:"The agents that share this project's memory. Replaces the list when given."})}),En=i({writer:P(t().trim().min(1),{code:"space_writer_invalid",hint:'A registered participant id, or "agent:<agentId>" for an agent whose memory_write should go to the space.',description:"The one non-admin who may write the space. An agent named here saves every memory_write to the space, so name one that holds nobody's private context."})}),Cn=i({bundle:P(x(t(),me()),{code:"bundle_files_invalid",hint:'Send { "bundle": <the body GET /v1/agents/:id/export returned> }.',description:"A bundle from GET /v1/agents/:id/export: MEMORY.md, memory/<name>.md and knowledge/<name>.md, nothing else."}),mode:P(y(["skip","overwrite"]).optional(),{code:"bundle_mode_invalid",hint:'Either "skip" (keep a knowledge file that exists, the default) or "overwrite". Memory is always merged note by note.',description:"What to do with a knowledge file the agent already has. Memory is merged either way."})}),An=i({approve:P(f(),{code:"action_decision_required",hint:'Send { "approve": true } to run the queued call as it was asked, or false to decline it.',description:"Run the queued call (true) or decline it (false)."})}),_n=i({url:P(t().min(1),{code:"webhook_url_invalid",hint:"Send an absolute https:// URL. A receiver on a private network needs the operator to allow it in WEBHOOK_ALLOW.",description:"Where deliveries are POSTed. Checked against every address it resolves to, at subscribe and at every send."}),types:P(a(t()).min(1),{code:"webhook_types_required",hint:'Send { "types": ["turn.end", "approval.requested"] }. Any event type except model.chunk; the wire spec lists them.',description:"The event types to deliver. `model.chunk` is not deliverable."}),agents:P(a(t()).min(1).optional(),{code:"webhook_scope_invalid",hint:"Send agent ids this credential can reach, or leave agents out to hear every agent it can reach.",description:"Narrow the subscription to these agents. It can never hear more than the creating credential reaches."})}),Pn=i({values:P(x(t(),P(t(),{code:"secret_value_invalid",hint:"Send each value as a non-empty string.",description:"One variable's value. Written to the agent's .env at 0600; never returned."})),{code:"secrets_values_required",hint:'Send { "values": { "MODEL_API_KEY": "…" } }. GET /v1/agents/:id/secrets lists the variables this agent reads.',description:"Variables to write into the agent's .env, keyed by name. Only names the agent's manifest reads are accepted."})}),bt={code:t(),message:t(),hint:t(),field:t().optional(),detail:t().optional()},xe=g({...bt,details:a(g(bt)).optional()}),nt=g({error:xe}).meta({description:"Every failure has this shape. `hint` is never absent: it is the part that says what to do."}),ha=g({status:de("ok"),version:t(),uptimeMs:r(),agents:r().int()}),wt=g({status:y(["ready","starting","draining"]),agents:r().int()}),xt=g({turnId:t(),sessionKey:t(),replayed:de(!0).optional()}),fa=g({turnId:t(),stopping:de(!0)}),In=g({turnId:t(),agentId:t(),sessionKey:t(),status:t(),source:t(),input:t(),text:t(),reasoning:t(),steps:r().int(),promptTokens:r(),outputTokens:r(),cachedPromptTokens:r().optional(),cacheSource:t().optional(),sender:t().optional(),senderName:t().optional(),senderKind:y(qt).optional(),note:t().optional(),errorCode:t().optional(),errorMessage:t().optional(),errorHint:t().optional(),errorDetail:t().optional(),startedAt:t(),endedAt:t().optional(),durationMs:r().optional()}),ma=g({id:t(),turns:a(In),nextBefore:r().int().optional()}),On=g({agentId:t(),sessionKey:t(),channel:t(),peerId:t(),thread:t().optional(),phase:t().optional(),recall:de(!1).optional(),createdAt:t(),updatedAt:t()}),ga=On.extend({messages:r().int(),turns:r().int(),lastActivityAt:t(),compactedAt:t().optional(),head:f()}),va=a(ga),ya=g({id:r().int(),sessionKey:t(),turnId:t().optional(),role:t(),content:t(),toolCalls:a(g({})).optional(),toolCallId:t().optional(),origin:t().optional(),tainted:f().optional(),createdAt:t()}),ba=g({messages:a(ya),nextBefore:r().int().optional()}),wa=g({sessionKey:t(),before:r(),after:r(),digest:y(["model","mechanical"]),keptTurns:r().int()}),xa=g({requested:t(),sessionKey:t()}),ka=g({sessionKey:t(),previous:t()}),it=g({keyId:t(),label:t(),createdAt:t(),lastUsedAt:t().optional(),revokedAt:t().optional(),scope:g({agents:a(t()).optional(),sessions:t().optional(),can:a(t()).optional(),participant:t().optional()}).optional(),expiresAt:t().optional()}),ja=it,Sa=it.extend({secret:t().meta({description:"The credential. In this response and no other."})}),Na=g({keys:a(it),scope:t().meta({description:"What a key's scope does and does not mean."})}),Ta=g({id:t(),dir:t(),files:a(t()),adopted:a(t()),error:xe.optional()}),Ea=g({scheduleId:t(),turnId:t(),sessionKey:t(),outOfBand:de(!0)}),h=t(),W=a(t()),te=r().int(),ot=y(["none","loaded","pending"]),_e=g({agentId:h,id:h,kind:y(["cron","every","at"]),expr:h,timezone:h.optional(),task:h,deliverChannel:h.optional(),deliverTo:h.optional(),sessionMode:h,role:h.optional(),toolsAllow:W.optional(),timeoutMs:r().optional(),maxSteps:r().optional(),enabled:f(),origin:h,anchorAt:h,nextRunAt:h.optional(),lastFiredAt:h.optional(),lastStatus:h.optional(),lastError:h.optional(),lastRunId:h.optional(),runs:te}),Ca=g({schedules:a(_e)}),Aa=g({kind:h,zone:h,next:W,jitterMs:r()}),_a=g({removed:h}),Pa=g({id:h,type:h,enabled:f(),status:h.optional(),credentialEnv:h.optional(),credentialSet:f().optional()}),$n=g({id:h,name:h,description:h.optional(),ask:f(),status:de("loaded"),model:h,channels:a(Pa),entryPhase:h.nullable(),phases:W.optional(),sessionScope:h}),zn=g({id:h,name:h,status:de("disabled"),reason:h.optional(),disabledAt:h.optional()}),Ia=a(Xe([$n.extend({assignee:h.nullable()}),zn])),Oa=Xe([$n.extend({dialect:h,window:r(),capabilities:g({}),tools:te,catalogueTokens:r(),skills:te,schedules:te}),zn,g({id:h,status:y(["not_running","failed"]),error:xe.optional()})]),kt=g({}),$a=g({idle:f(),turnsRunning:te,deliveries:g({outbox:kt,webhooks:kt}),nextWakeAt:h.optional()}),za=g({id:h,removed:de(!0),dir:h,sessions:te,messages:te,turns:te}),jt=g({id:h,status:y(["disabled","loaded"]),disabledAt:h.optional(),reason:h.optional(),adopted:W.optional()}),St=g({id:h,status:y(["loaded","pending"]),adopted:W,running:r().optional(),holdAfterMs:r().optional()}),Ra=g({version:r(),agentId:h,exportedAt:h,files:a(g({path:h,content:h}))}),Ma=g({id:h,added:W,merged:a(g({path:h,notes:te})),skipped:W,overwritten:W,evicted:te,reload:ot}),La=g({id:h,template:h,vars:x(h,h)}),Nt=g({id:h,rendered:W,skipped:a(g({file:h,reason:h})),reload:ot}),Da=g({id:h,files:a(g({name:h,tier:h,field:h,exists:f(),bytes:te}))}),Ua=g({id:h,file:h,tier:h.optional(),field:h.optional(),exists:f(),content:h}),lt={applied:f(),pending:xe.optional()},Ba=g({id:h,file:h,written:de(!0),loads:f(),error:xe.optional(),...lt}),Tt=g({id:h,providers:a(g({provider:h,ok:f(),fetched:te,error:h.optional()})),added:W,removed:W,changed:W,reload:ot}),Fa=g({step:h,prompt:h,fallback:h,optional:f(),secret:f(),requires:g({step:h,value:h}).optional(),choices:a(g({value:h,label:h,hint:h.optional()})).optional()}),Ka=g({available:f(),local:f(),allowed:f(),steps:a(Fa)}),Ha=g({templates:a(g({name:h,description:h.optional(),vars:a(g({name:h,description:h.optional(),required:f(),default:h.optional(),secret:f()})),problem:xe.optional()}))}),qa=g({id:h,secrets:a(g({name:h,set:f(),usedBy:W}))}),Ga=g({written:W,shadowed:W,applied:y(["none","pending","reloaded","adopted"]),adopted:W,stopped:f().optional(),error:xe.optional()}),Wa=g({sessionKey:h,key:h,duplicate:f()}),Va=g({approvals:a(g({approvalId:h,agentId:h,sessionKey:h,slug:h,callId:h,match:h.optional(),mutating:f(),reason:h,requestedAt:h}))}),Qa=g({approvalId:h,granted:f()}),Rn=g({subscriptionId:h,url:h,types:W,scope:g({agents:W.optional(),sessionPrefix:h.optional()}).optional(),createdAt:h,consecutiveFailures:te,lastError:h.optional(),lastSuccessAt:h.optional(),lastFailureAt:h.optional(),pending:te,failing:f()}),Ya=Rn.extend({secret:h.meta({description:"The signing secret. In this response and no other."})}),Ja=g({webhooks:a(Rn)}),Ce=g({id:h,deleted:f()}),at=g({id:h,kind:de("human"),name:h.optional(),role:y(["admin","member"]),title:h.optional(),channelIds:W.optional(),timezone:h.optional(),createdAt:h,presence:y(["online","offline"]).optional(),presenceAt:h.optional()}),Xa=g({participants:a(at)}),Pe=g({id:h,kind:y(["room","dm"]),title:h.optional(),members:W,createdAt:h}),Za=g({conversations:a(Pe)}),Mn=g({id:h,conversationId:h,authorId:h,origin:y(["human","agent"]),text:h,mentions:W,hop:te,turnId:h.optional(),onBehalfOf:h.optional(),seq:te,createdAt:h}),er=g({conversationId:h,messages:a(Mn),nextAfter:te.optional()}),Ln=g({id:h,agentId:h,conversationId:h,ownerId:h,requestedBy:h,slug:h,args:x(h,me()),status:y(["pending","done","failed","denied"]),result:h.optional(),createdAt:h,decidedAt:h.optional()}),tr=g({actions:a(Ln)}),Dn=g({agentId:h,participantId:h,channelIds:W.optional(),assignedBy:h.optional(),assignedAt:h}),nr=g({id:h,assignment:Dn.nullable()}),ar=g({id:h,unassigned:f()}),Un=g({id:h,scope:h,text:h,writtenBy:h,createdAt:h}),rr=g({notes:a(Un)}),sr=g({reads:a(g({scope:h,reader:h,turnId:h,sessionKey:h,requestedBy:h.optional(),onBehalfOf:h.optional(),sources:W,at:h}))}),Bn=g({id:h,name:h.optional(),agents:W,createdAt:h}),ir=g({projects:a(Bn)}),or=g({writer:h}),Fn=g({buckets:a(g({agentId:h.optional(),model:h.optional(),day:h.optional(),sender:h.optional(),calls:te,promptTokens:r(),cachedPromptTokens:r(),cacheWriteTokens:r(),outputTokens:r(),images:r(),audioSeconds:r(),estimatedCalls:te})),meteredSince:h.optional()}),lr=Fn.extend({id:h}),cr=g({cleared:h,memoryFilesKept:de(!0)}),dr=g({sessionKey:h,phase:h.nullable()}),ur=g({sessionKey:h,recall:f()}),pr=g({running:f(),editable:f(),file:h.optional(),settings:a(g({path:h,means:h,confirm:h.optional(),value:me().optional()}))}),fr=g({path:h,before:me().optional(),after:me().optional(),reflowed:f(),changed:f()}),mr=g({path:h.optional(),changes:a(fr).optional(),reloaded:f(),...lt}),gr=g({channelId:h,notes:W,...lt}),vr=g({channelId:h,note:h,restarted:f()}),br=a(g({slug:h,summary:h,mutating:f(),trust:h,trustReason:h.optional(),provider:h,tags:W,phases:W.optional()})),wr=g({configured:f(),maxActive:r().optional(),threshold:r().optional(),cached:f().optional(),skills:a(g({name:h,description:h,tokens:r(),whenNotToUse:h.optional(),scripts:W,trusted:f()}))}),xr=g({slots:a(g({slot:te,label:h,tokens:r(),pinned:f()})),history:a(g({label:h,tokens:r(),messages:te})),total:r(),window:r(),wireTokens:r(),reserveOutput:r(),calibration:g({}),compactions:te}),kr=g({openapi:h,info:g({title:h,version:h}),paths:x(h,g({}))});function G(s,e){let d=s.safeParse(e??{});if(d.success)return{ok:!0,value:d.data};let p=d.error.issues[0],b=(p?.path??[]).filter((A)=>typeof A==="string"),w=jr(s,b);return{ok:!1,error:{...{code:"request_body_invalid",message:b.length===0?p?.message??"The request body is invalid.":`${b.join(".")}: ${p?.message}`,hint:"The field above is the one to fix. GET /v1/openapi.json describes every body this server accepts, including the error code each field produces."},...w?.code===void 0?{}:{code:w.code},...w?.hint===void 0?{}:{hint:w.hint},...b.length===0?{}:{field:b.join(".")}}}}function jr(s,e){let d=s,p=De(s);for(let b of e){if(d=Sr(d,b),d===void 0)break;p=De(d)??De(Kn(d))??p}return p}function De(s){let e=s?.meta();if(e?.code===void 0&&e?.hint===void 0)return;return e}function Sr(s,e){let d=Kn(s),p=d?.shape;if(p?.[e]!==void 0)return p[e];return d?.def?.valueType}function Kn(s){let e=s;for(let d=0;d<8&&e!==void 0;d+=1){let p=e.def?.innerType;if(p===void 0)return e;e=p}return e}var ze={sse:{type:"text/event-stream",about:"Server-sent events. Each frame's `data` is one event; the event table is in the wire spec (docs/04-SPEC-WIRE.md)."},text:{type:"text/plain",about:"Plain text."},html:{type:"text/html",about:"An HTML page."},gzip:{type:"application/gzip",about:"A gzip-compressed tar archive."}},Hn={"GET /v1/health":{summary:"Liveness, the version, and how many agents are hosted.",responses:{200:ha}},"GET /v1/ready":{summary:"Whether a turn can be served yet.",responses:{200:wt,503:wt},statuses:[{code:503,when:"`starting` (not ready yet) or `draining` (on the way down); the body has the same shape as the 200"}]},"GET /v1/activity":{responses:{200:$a},summary:"Whether the process is idle, and when it must next be woken. For an external waker.",statuses:[{code:403,when:"the key is scoped to agents or sessions"}]},"GET /v1/agents":{responses:{200:Ia},summary:"Every agent this server knows about, hosted or switched off."},"GET /v1/agents/:id":{summary:"One agent, with its dialect, window, counts and warnings.",responses:{200:Oa}},"GET /v1/backup":{responses:{200:"gzip"},summary:"The silo as a tar.gz: a consistent store snapshot and every hosted agent's directory, with a backup.json manifest. No .env or .git unless asked for. An admin key with no agents scope.",query:[{name:"include",about:"Any of env, git, home, comma-separated: each agent's .env (its secrets), its .git directories, and the rest of the state directory under home/."}],statuses:[{code:400,when:"include names something other than env, git or home, or home on a server with no state directory"},{code:403,when:"the key is scoped to some agents"}]},"GET /v1/agents/:id/export":{responses:{200:Ra},summary:"A slice of the agent as a JSON bundle: its carried memory file, memory archive and knowledge. Never the manifest, secrets or skills.",query:[{name:"paths",about:"Narrow the bundle to these sections, comma-separated: MEMORY.md, memory/, knowledge/."}],statuses:[{code:400,when:"`paths` names something a bundle cannot carry"}]},"POST /v1/agents/:id/import":{responses:{200:Ma},summary:"Merge a bundle into the agent: memory note by note, knowledge kept or overwritten. Reloads when the carried file or knowledge changed, and restores everything if that reload refuses.",body:Cn,statuses:[{code:400,when:"a path a bundle cannot carry, or a bundle the agent would not load"}]},"GET /v1/agents/:id/workspace":{responses:{200:Da},summary:"The files the agent's prompt is built from: name, tier, field, whether it exists, size.",statuses:[{code:409,when:"the manifest does not parse, so its files cannot be named"}]},"GET /v1/agents/:id/workspace/:file":{responses:{200:Ua},summary:"One declared workspace file's text, for an editor to show before it replaces it.",statuses:[{code:404,when:"not a file the manifest declares"},{code:409,when:"the manifest does not parse"}]},"PUT /v1/agents/:id/workspace/:file":{responses:{200:Ba},summary:"Replace one of the agent's declared workspace files; reload it, or diagnose it when it is not running.",body:en,statuses:[{code:400,when:"a running agent would not load with the new text (the old text is put back)"},{code:404,when:"a file the manifest does not declare"},{code:409,when:"an agent with no manifest file, or one whose manifest does not parse"}]},"GET /v1/agents/:id/vars":{responses:{200:La},summary:"The template an agent was made from and the plain variable values it was last rendered with. Secrets never appear.",statuses:[{code:409,when:"an agent with no template record"},{code:501,when:"a server with no templates directory (an embedded handler)"}]},"PATCH /v1/agents/:id/vars":{responses:{200:Nt,202:Nt},summary:"Apply changed template variables: re-render the files nobody edited since they were rendered, then reload.",body:tn,statuses:[{code:200,when:"applied: `reload` says whether the agent was reloaded"},{code:202,when:"files changed and a turn is running: the reload lands when it ends"},{code:400,when:"a secret or undeclared variable, or a result the agent would not load (every file is put back)"},{code:409,when:"the agent was not made from a template on 0.2.0 or later"},{code:501,when:"this server has no templates"}]},"POST /v1/agents/:id/tools/refresh":{responses:{200:Tt,202:Tt},summary:"Fetch the tool providers' catalogues and schemas now, and reload the agent only if what it serves changed.",body:nn,statuses:[{code:200,when:"refreshed; reloaded now if what the agent serves changed"},{code:202,when:"something changed and a turn is running: the reload lands when it ends"},{code:400,when:"a provider the agent does not have, or a reload the agent refuses"},{code:409,when:"a turn is in flight and the runtime refused to hold the reload"}]},"POST /v1/agents/:id/reload":{responses:{200:St,202:St},summary:"Re-read the manifest by replacing the agent with a new instance.",statuses:[{code:200,when:"loaded: `adopted` lists every agent that came back"},{code:202,when:"a turn is running: it finishes on the old configuration and the swap follows, announced by agent.reloaded"},{code:400,when:"a team member, which has no manifest of its own"},{code:409,when:"the runtime refused to hold the swap behind a running turn"}]},"GET /v1/provision":{responses:{200:Ka},summary:"The questions creating an agent asks, and whether this server can answer them."},"POST /v1/agents":{summary:"Create an agent, from answers or from a template, and adopt it into this host, live.",body:mn,success:201,responses:{201:Ta},statuses:[{code:201,when:"created; `adopted` is empty with an `error` if it is not running"},{code:403,when:"neither a loopback bind nor an authenticated admin credential"},{code:501,when:"this server has no provisioner"}]},"POST /v1/webhooks":{responses:{201:Ya},summary:"Subscribe a URL to event types. The signing secret is returned once.",body:_n,success:201,statuses:[{code:201,when:"created; `secret` is in this response and no other"},{code:400,when:"a refused URL, an undeliverable type, or agents outside this key's reach"}]},"POST /v1/participants":{responses:{201:at},summary:"Register a human participant under the embedder's own id. No account is stored.",body:vn,success:201,statuses:[{code:201,when:"registered, or updated if the id existed"}]},"GET /v1/participants":{summary:"The registered human participants.",responses:{200:Xa}},"DELETE /v1/participants/:participantId":{responses:{200:Ce},summary:"Remove a participant and their conversation memberships."},"POST /v1/conversations":{responses:{201:Pe},summary:"Create a room or a DM among participants and agents (agent:<id>).",body:yn,success:201,statuses:[{code:201,when:"created"},{code:403,when:"a participant-bound key creating a conversation it is not in"}]},"GET /v1/conversations":{summary:"The conversations this credential can see.",responses:{200:Za}},"GET /v1/conversations/:conversationId":{summary:"One conversation and its members.",responses:{200:Pe}},"PATCH /v1/conversations/:conversationId/members":{responses:{200:Pe},summary:"Add or remove members of a room.",body:bn},"POST /v1/conversations/:conversationId/messages":{responses:{202:Mn},summary:"Post a human member's message. In a room only the mentioned agents answer; in a DM the agent always does. Their replies arrive as conversation.message.",body:wn,success:202,statuses:[{code:202,when:"logged; the turns it starts run behind the response"},{code:403,when:"a participant-bound key naming another author"}]},"GET /v1/conversations/:conversationId/messages":{responses:{200:er},summary:"The conversation's log, oldest first, after a sequence number."},"PUT /v1/participants/:participantId/presence":{responses:{200:at},summary:"Push whether a person is there. In a DM between two people, an offline person's agent stands in for them.",body:Sn,statuses:[{code:403,when:"a participant-bound key setting someone else's presence"}]},"POST /v1/memory/notes":{responses:{201:Un},summary:"Add a note to a shared memory scope — the space, a person's owner scope, or a project. Agents recall it when a turn is about it.",body:Nn,success:201,statuses:[{code:201,when:"saved"},{code:403,when:"this participant may not write that scope"},{code:404,when:"the scope's owner or project does not exist"}]},"GET /v1/memory/notes":{responses:{200:rr},summary:"Every note in one shared scope, oldest first. An owner scope is readable by its owner."},"DELETE /v1/memory/notes/:noteId":{responses:{200:Ce},summary:"Remove a note. Whoever may write its scope may remove it."},"GET /v1/participants/:participantId/memory/reads":{responses:{200:sr},summary:"The person's audit: every time an agent recalled their owner scope for somebody else, stand-ins included."},"GET /v1/projects":{summary:"Projects, each with the agents that share its memory.",responses:{200:ir}},"PUT /v1/projects/:projectId":{responses:{200:Bn},summary:"Define a project, or replace which agents share its memory. An admin's act.",body:Tn},"DELETE /v1/projects/:projectId":{responses:{200:Ce},summary:"Remove a project and its notes."},"PUT /v1/memory/space/writer":{responses:{200:or},summary:"Name the one non-admin who may write the space. An agent named here saves its memory_write to the space.",body:En},"GET /v1/actions":{responses:{200:tr},summary:"Mutating calls stand-ins queued for their owners. A member-bound key sees its own."},"POST /v1/actions/:actionId":{responses:{200:Ln},summary:"Approve or decline a queued action. Approved, the exact call runs as the owner's agent and the outcome is posted in the DM.",body:An,statuses:[{code:404,when:"no such action, or not this key's to decide"},{code:409,when:"already decided"}]},"PUT /v1/agents/:id/assignee":{responses:{200:Dn},summary:"Record which member an agent works for. An admin participant's act.",body:jn},"GET /v1/agents/:id/assignee":{responses:{200:nr},summary:"Who the agent is assigned to, as `{id, assignment}`; `assignment` is null when nobody."},"DELETE /v1/agents/:id/assignee":{summary:"Clear an agent's assignment.",responses:{200:ar}},"GET /v1/webhooks":{responses:{200:Ja},summary:"The subscriptions this credential can see, with their delivery health. Never a secret."},"DELETE /v1/webhooks/:webhookId":{responses:{200:Ce},summary:"Delete a subscription and anything it still owed.",statuses:[{code:404,when:"no such subscription, or one outside this key's reach"}]},"GET /v1/usage":{responses:{200:Fn},summary:"What every agent in scope cost, per model call, grouped by agent, model, day or sender.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/usage":{responses:{200:lr},summary:"What this agent cost, from the meter.",statuses:[{code:400,when:"an unknown grouping or a date that does not parse"}]},"GET /v1/agents/:id/turns":{summary:"Every turn this agent has taken, newest first, across sessions, paged by `before`.",responses:{200:ma},query:[{name:"limit",about:"How many to return, up to 200. Default 50."},{name:"before",about:"The previous page's `nextBefore`."}],statuses:[{code:400,when:"`limit` or `before` is not a positive whole number"}]},"GET /v1/templates":{responses:{200:Ha},summary:"The templates an agent can be created from, and the variables each declares."},"GET /v1/agents/:id/secrets":{responses:{200:qa},summary:"Which variables the agent's manifest reads, and whether each is set. Never a value.",statuses:[{code:501,when:"this server has no credential writer"}]},"PUT /v1/agents/:id/secrets":{responses:{200:Ga},summary:"Write the agent's credentials into its .env and apply them: reload or adopt.",body:Pn,statuses:[{code:200,when:"written; `applied` says whether the agent is running on them"},{code:400,when:"a variable the manifest does not read, or an empty value"},{code:501,when:"this server has no credential writer"}]},"DELETE /v1/agents/:id":{responses:{200:za},summary:"Delete an agent for good: off this host, its rows out of the store, its directory off disk. Needs ?confirm=<id>.",statuses:[{code:400,when:"no ?confirm=<id>"},{code:409,when:"two sandbox directories declare this id"},{code:501,when:"this server cannot delete agents"}]},"POST /v1/agents/:id/stop":{responses:{200:jt},summary:"Switch an agent off durably and drop it from this host now.",body:pn,statuses:[{code:409,when:"a turn is running"}]},"POST /v1/agents/:id/start":{responses:{200:jt},summary:"Switch it back on and have this host adopt it.",statuses:[{code:400,when:"the agent's manifest would not load; the row is put back to stopped"},{code:501,when:"this server cannot look up manifests"}]},"POST /v1/agents/:id/messages":{summary:"Start a turn. Returns once accepted; the turn runs detached.",body:Zt,success:202,responses:{200:xt,202:{json:xt,sse:!0}},headers:[{name:"Idempotency-Key",about:"1-255 printable ASCII characters unique to this logical message. A retry with the same key and the same text and session answers 200 with the original turn (`replayed: true`) and runs nothing; with different text it is a 409. Remembered for 24 hours."}],statuses:[{code:200,when:"a replay of an Idempotency-Key already used for this message: the original turn, `replayed: true`"},{code:202,when:"accepted: `{turnId, sessionKey}`, or with `stream: true` an event stream whose first frame is that object"},{code:403,when:"a participant-bound key naming another sender in `from`"},{code:409,when:"idempotency_key_reused: the key belongs to a turn with different text or session"},{code:429,when:"over limits.maxConcurrentTurns or limits.tokens; nothing recorded"}]},"POST /v1/agents/:id/deliveries":{success:202,responses:{202:Wa},summary:"Send exact text on one of the agent's channels, with no turn. It joins that conversation's history as the agent's.",body:rn,statuses:[{code:202,when:"queued, or already queued under this key"},{code:404,when:"the agent has no running channel with that id"}]},"POST /v1/agents/:id/turns/:turnId/stop":{summary:"Cooperatively stop a turn this API started.",success:202,responses:{202:fa},statuses:[{code:409,when:"no cancel handle — a channel or schedule started it"}]},"GET /v1/agents/:id/turns/:turnId/stream":{summary:"One turn's events as SSE, replayed from the start and then live.",responses:{200:"sse"},query:[{name:"chunks",about:"Include per-token frames. Off by default."},{name:"children",about:"Include the events of subagents this turn runs. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"}]},"GET /v1/events":{summary:"Every event this process emits, as SSE. The firehose.",responses:{200:"sse"},query:[{name:"agentId",about:"Narrow to one agent."},{name:"sessionKey",about:"Narrow to one conversation."},{name:"chunks",about:"Include per-token frames. Off by default."},{name:"types",about:"Narrow to these event types, comma-separated."}],statuses:[{code:200,when:"an event stream; see the event table in the wire spec"},{code:400,when:"`types` names an event type that does not exist"},{code:404,when:"`agentId` names no agent this key reaches"}]},"GET /v1/agents/:id/approvals":{summary:"Questions waiting on a person, oldest first.",responses:{200:Va}},"POST /v1/agents/:id/approvals/:approvalId":{responses:{200:Qa},summary:"Answer one blocked tool call.",body:sn},"POST /v1/keys":{summary:"Mint an operator key. The secret is returned once and never again.",body:on,success:201,responses:{201:Sa},statuses:[{code:201,when:"minted"}]},"GET /v1/keys":{summary:"Every key, live and revoked. Never a secret.",responses:{200:Na}},"DELETE /v1/keys/:keyId":{summary:"Revoke a key. A soft delete; the row survives, and revoking a revoked key answers its original stamp.",responses:{200:ja}},"GET /v1/agents/:id/turns/:turnId":{summary:"One turn's stored row.",responses:{200:In}},"GET /v1/agents/:id/sessions":{summary:"Conversations, most recently active first.",responses:{200:va}},"GET /v1/agents/:id/sessions/:key":{summary:"One conversation's stored record.",responses:{200:On}},"GET /v1/agents/:id/sessions/:key/messages":{summary:"A page of a conversation's messages.",responses:{200:ba},query:[{name:"limit",about:"How many to return."},{name:"before",about:"Page backwards from this message id."}]},"DELETE /v1/agents/:id/sessions/:key":{responses:{200:cr},summary:"Drop a conversation's history, turns and derived index."},"POST /v1/agents/:id/sessions/:key/phase":{responses:{200:dr},summary:"Move a session into a declared phase.",body:ln},"POST /v1/agents/:id/sessions/:key/compact":{summary:"Fold a conversation's older turns into a saved digest; the next turn starts from it, and every message stays stored.",body:cn,responses:{200:wa},statuses:[{code:409,when:"session_too_short: nothing older than the turns kept verbatim to fold"},{code:409,when:"nothing_to_gain: the digest would be no smaller than what it replaces; nothing changed"}]},"POST /v1/agents/:id/sessions/:key/recall":{responses:{200:ur},summary:"Keep a conversation out of history recall, or put it back; its messages stay.",body:dn},"POST /v1/agents/:id/sessions/resolve":{summary:"The conversation a message naming this sessionKey would run in, before sending it; nothing changes.",body:xn,responses:{200:xa},statuses:[{code:403,when:"a participant-bound key naming another sender in `from`"}]},"POST /v1/agents/:id/sessions/rotate":{summary:"Start the caller's conversation afresh on every surface (sessions.scope owner or peer).",body:kn,responses:{200:ka},statuses:[{code:403,when:"a participant-bound key naming another sender in `from`"},{code:409,when:"session_not_rotatable: no conversation of the caller's to start afresh (sessions.scope channel-peer, or a sender with no person behind it)"}]},"GET /v1/agents/:id/config":{responses:{200:pr},summary:"Every manifest field this surface may set, what it does, and its current value."},"PATCH /v1/agents/:id/config":{responses:{200:mr},summary:"Set one manifest field, then replace the agent so it takes effect.",body:hn,statuses:[{code:409,when:"the field carries a confirm sentence and `confirm` was not true"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:400,when:"the path is not settable here, or the result would not validate"}]},"PATCH /v1/agents/:id/channels/:channelId":{responses:{200:gr},summary:"Connect or disconnect a channel, and set its credential.",body:fn,statuses:[{code:400,when:"neither `enabled` nor `credential` was sent, or the channel is unknown"},{code:409,when:"the agent came from an object, so there is no manifest to edit"},{code:501,when:"the host supplied no channel actions"}]},"POST /v1/agents/:id/channels/:channelId/unpair":{responses:{200:vr},summary:"Forget a channel's stored pairing, so the next start offers a new code.",statuses:[{code:404,when:"this agent has no such channel"},{code:409,when:"the channel stores no pairing — a typed credential is a PATCH"}]},"GET /v1/agents/:id/schedules":{summary:"Every schedule, from the store.",responses:{200:Ca}},"POST /v1/agents/:id/schedules":{responses:{201:_e},summary:"Create a schedule. Validated by the manifest's own schedule rules.",success:201,statuses:[{code:201,when:"created"}]},"GET /v1/agents/:id/schedules/preview":{responses:{200:Aa},summary:"What an expression means before it is written: the next instants, zone and jitter.",statuses:[{code:400,when:"an expression core's own parser refuses, with its hint"}]},"GET /v1/agents/:id/schedules/:sid":{summary:"One schedule's row.",responses:{200:_e}},"PATCH /v1/agents/:id/schedules/:sid":{responses:{200:_e},summary:"Replace a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so reconciliation would undo the write"}]},"DELETE /v1/agents/:id/schedules/:sid":{responses:{200:_a},summary:"Delete a schedule the API created.",statuses:[{code:409,when:"the manifest declares it, so the next boot would re-create it"}]},"POST /v1/agents/:id/schedules/:sid/run":{summary:"Fire a schedule now, out of band.",success:202,responses:{202:Ea},statuses:[{code:429,when:"over a governor limit; nothing recorded"}]},"GET /v1/agents/:id/tools":{summary:"The resolved catalogue, with trust and phases.",responses:{200:br}},"GET /v1/agents/:id/skills":{summary:"What the skills index holds.",responses:{200:wr}},"GET /v1/agents/:id/context":{responses:{200:xr},summary:"The prompt the next turn would be given, without running one.",query:[{name:"sessionKey",about:"Which conversation to assemble for."},{name:"input",about:"Pretend this is the next message."}]},"POST /v1/channels/:channelId/webhook/:agentId":{responses:{200:"text",404:"text"},summary:"A channel provider's webhook. Open by design; the provider authenticates itself."},"GET /v1/openapi.json":{summary:"This document.",responses:{200:kr}},"GET /docs":{summary:"A browser reference over this document.",responses:{200:"html"}}},Nr={"/v1/ws":{get:{summary:"The event stream over a WebSocket: the same events as GET /v1/events, plus subscribe and stop frames. Answered by serve(), not by an embedded handler.",description:`Authenticate with the subprotocol list a browser will send: \`new WebSocket(url, ["${Ee}", key])\`; the server echoes \`${Ee}\`. An \`Authorization\` header works for a client that can set one. \`?token=\` is still accepted and is deprecated, because a credential in a URL reaches access logs and \`Referer\`.`,parameters:[{name:"Sec-WebSocket-Protocol",in:"header",required:!1,description:`\`${Ee}, <key>\`: the credential, for a browser.`,schema:{type:"string"}},{name:"agentId",in:"query",required:!1,description:"Narrow to one agent. Omitted, every agent this key reaches.",schema:{type:"string"}},{name:"chunks",in:"query",required:!1,description:"Include per-token frames. Off by default; a subscribe frame can change it.",schema:{type:"string"}},{name:"token",in:"query",required:!1,deprecated:!0,description:"The credential as a query parameter. Use the subprotocol instead.",schema:{type:"string"}}],responses:{"101":{description:"Switching protocols: the socket is open."},"401":Ie("No credential, or one this server does not accept."),"403":Ie("An origin or Host this server does not accept."),"404":Ie("`agentId` names no agent this key reaches.")}}}};function Tr(s){return s.startsWith("/v1/")||s==="/docs"}var Et={200:"OK",201:"Created",202:"Accepted"};function Er(s){if(!Tr(s.pattern))return;let e=Hn[`${s.method} ${s.pattern}`];if(e===void 0)return;let d={},p=(A,U)=>{let H=String(A);d[H]=d[H]===void 0?U:`${d[H]}; or ${U}`};for(let A of e.statuses??[])p(A.code,A.when);let b=(A,U)=>{if(d[String(A)]===void 0)p(A,U)},w=e.success??200;b(w,Et[w]??"OK");for(let A of Object.keys(e.responses??{}))b(Number(A),Et[Number(A)]??"See the schema.");if(e.body!==void 0)b(400,"The body is not JSON, is over the size limit, or fails its schema: request_body_invalid, or the failing field's own code.");if(s.capability!=="open")b(401,"No credential, or one this server does not accept."),b(403,"capability_required: a scoped key without this route's capability; or an origin or Host this server does not accept.");else b(403,"An origin or Host this server does not accept.");if(s.pattern.includes(":"))b(404,s.pattern.includes(":id")?"No such agent, or it is switched off, or it is outside this key's scope; or no such resource under it.":"No such resource, or one outside this key's scope.");b(500,"internal_error: not caused by the request. The server's log has the cause.");let N={};for(let[A,U]of Object.entries(d)){let H=Number(A),C=e.responses?.[H];if(C===void 0)N[A]=H>=400?{description:U,json:nt}:{description:U};else if(typeof C==="string")N[A]={description:U,media:ze[C].type};else if("json"in C)N[A]={description:U,json:C.json,media:ze.sse.type};else N[A]={description:U,json:C}}return N}function Ie(s){return{description:s,content:{"application/json":{schema:{$ref:"#/components/schemas/Error"}}}}}function Ue(s,e){let{$schema:d,...p}=Ys(s,{target:"draft-2020-12",io:e});return e==="output"?Ar(p):p}function Ar(s){let e=(d)=>{if(Array.isArray(d))return d.map(e);if(typeof d!=="object"||d===null)return d;let p={};for(let[b,w]of Object.entries(d))if(!(b==="additionalProperties"&&typeof w==="object"&&w!==null&&Object.keys(w).length===0))p[b]=e(w);return p};return e(s)}function _r(s){let e={};for(let d of s.routes){let p=Hn[`${d.method} ${d.pattern}`],b=Er(d);if(p===void 0||b===void 0)continue;let w=d.pattern.replace(/:([A-Za-z0-9_]+)/g,"{$1}"),N=[...d.pattern.matchAll(/:([A-Za-z0-9_]+)/g)].map((M)=>({name:M[1],in:"path",required:!0,schema:{type:"string"}})),A=(p.query??[]).map((M)=>({name:M.name,in:"query",required:!1,description:M.about,schema:{type:"string"}})),U=(p.headers??[]).map((M)=>({name:M.name,in:"header",required:!1,description:M.about,schema:{type:"string"}})),H=[...N,...A,...U],C={};for(let[M,D]of Object.entries(b)){if(Number(M)>=400&&D.json===nt){C[M]=Ie(D.description);continue}let k={};if(D.json!==void 0)k["application/json"]={schema:Ue(D.json,"output")};if(D.media!==void 0){let F=Object.values(ze).find((J)=>J.type===D.media);k[D.media]={schema:{type:"string",...D.media===ze.gzip.type?{format:"binary"}:{},...F===void 0?{}:{description:F.about}}}}C[M]={description:D.description,...Object.keys(k).length===0?{}:{content:k}}}e[w]??={};let ae={summary:p.summary,...H.length===0?{}:{parameters:H},...d.capability==="open"?{security:[]}:{},responses:C};if(p.body!==void 0)ae.requestBody={required:!0,content:{"application/json":{schema:Ue(p.body,"input")}}};e[w][d.method.toLowerCase()]=ae}for(let[d,p]of Object.entries(Nr))e[d]={...e[d],...p};return{openapi:"3.1.0",info:{title:"Dispach agent server",version:Ye,description:"Generated from the router table and the request and response schemas — see openapi.ts. Every declared response body is checked against the handler by the server's test harness. The binding contract is docs/04-SPEC-WIRE.md, which is checked against the code."},...s.serverUrl===void 0?{}:{servers:[{url:s.serverUrl}]},components:{securitySchemes:{bearer:{type:"http",scheme:"bearer",description:"An operator key or the configured token."}},schemas:{Error:Ue(nt,"output")}},security:[{bearer:[]}],paths:e}}var Pr=new Set(["127.0.0.1","::1","localhost","[::1]"]);function Me(s){return Pr.has(s.toLowerCase())}function je(s){let e=s.trim();if(e===""||e.toLowerCase()==="null")return;try{return new URL(e.includes("://")?e:`http://${e}`).hostname.toLowerCase().replace(/^\[|\]$/g,"")}catch{return}}function Ct(s){return Me(s)||/^127\.\d{1,3}\.\d{1,3}\.\d{1,3}$/.test(s)}function Le(s,e){let d=Me(e.host),p=s.headers.get("host"),b=s.headers.get("origin");if(d){let N=p===null?void 0:je(p),A=e.allowedHosts??[];if(!(N!==void 0&&(Ct(N)||A.some((H)=>je(H)===N))))return{code:"host_not_allowed",message:`This server does not answer to the host ${p??"(absent)"}.`,hint:"It is bound to loopback, so only a loopback name or address can legitimately reach it — a request addressed to any other name arrived through DNS pointed at this machine, which is how a web page reaches a local server it was never given access to. Add the name to server.allowedHosts if a proxy on this machine needs it.",field:"server.allowedHosts"}}if(b===null)return;let w=je(b);if(w!==void 0){if(Ct(w))return;if((e.allowedOrigins??[]).some((N)=>je(N)===w))return;if(!d&&p!==null&&je(p)===w)return}return{code:"origin_not_allowed",message:`Refusing a request from the origin ${b}.`,hint:d?"This server is bound to loopback, so a page served from anywhere else has no business calling it. Add the origin to server.allowedOrigins if you meant to allow it.":"Only a page served from this server's own host may call it. Add the origin to server.allowedOrigins if you meant to allow it — there is no wildcard, deliberately.",field:"server.allowedOrigins"}}function Ir(s,e){let d=s.headers.get("origin");if(d===null)return{};if(Le(s,e)!==void 0)return{};return{"access-control-allow-origin":d,vary:"Origin"}}function Or(s,e){let d=s.headers.get("access-control-request-headers");return{"access-control-allow-methods":e.join(", "),"access-control-allow-headers":d??"authorization, content-type","access-control-max-age":"600"}}function Be(s,e){if(s.kind!=="key")return s.kind!=="claim";let d=s.scope?.can;return d===void 0||d.includes(e)}function se(s,e){if(s.kind!=="key")return s.kind!=="claim";let d=s.scope?.agents;return d===void 0||d.includes(e)}function ve(s,e){if(s.kind!=="key")return s.kind!=="claim";let d=s.scope?.sessions;if(d===void 0)return!0;if(e.startsWith(d.endsWith("*")?d.slice(0,-1):d))return!0;let p=s.scope?.participant;return p!==void 0&&(Vr(e,`owner:${p}`)||Vr(e,`peer:${p}`))}function qn(s,e){if(e.sessionKey===void 0||ve(s,e.sessionKey))return!0;return e.parentSessionKey!==void 0&&ve(s,e.parentSessionKey)}function Ne(s){if(s.kind==="claim")return{agentIds:[]};if(s.kind!=="key")return{};let e=s.scope?.agents,d=s.scope?.sessions;return{...e===void 0?{}:{agentIds:e},...d===void 0?{}:{sessionPrefix:d.endsWith("*")?d.slice(0,-1):d}}}function ct(s){if(s.kind!=="key")return!1;let e=s.scope;return e!==void 0&&(e.agents!==void 0||e.sessions!==void 0||e.can!==void 0)}function Oe(s,e){let d=s.kind==="key"?s.scope?.participant:void 0;if(d===void 0)return{ok:!0,from:e};if(e===void 0)return{ok:!0,from:{id:d,kind:"user"}};if(e.id===d&&e.kind==="user")return{ok:!0,from:e};return{ok:!1,error:{code:"sender_not_bound_participant",message:`This key speaks for ${d}, and the message names ${e.kind} ${e.id}.`,hint:`A key bound to a participant starts turns only as that participant, so the tools the turn calls act for them. Omit from (it is filled in), or send from.id "${d}" with kind "user". A backend that names senders itself needs a key minted without scope.participant.`,field:"from"}}}async function rt(s,e,d,p,b){let w=await s.resolveSessionKey(d,{source:"api",...p===void 0?{}:{from:p},...b===void 0?{}:{peerAsk:b}});return ve(e,w)?w:d}class Gn{#e=[];add(s,e,d,p){return this.#e.push({method:s.toUpperCase(),pattern:e,handler:d,capability:p.capability,streaming:p.streaming===!0,segments:At(e)}),this}routes(){return this.#e.map(({method:s,pattern:e,handler:d,streaming:p,capability:b})=>({method:s,pattern:e,handler:d,streaming:p,capability:b}))}match(s,e){let d=At(e),p=[];for(let b of this.#e){let w=$r(b.segments,d);if(w===void 0)continue;if(p.push(b),b.method===s.toUpperCase())return{kind:"found",handler:b.handler,params:w,streaming:b.streaming,capability:b.capability}}if(p.length>0)return{kind:"method",allowed:[...new Set(p.map((b)=>b.method))]};return{kind:"none"}}}function At(s){return s.split("/").filter((e)=>e!=="")}function $r(s,e){if(s.length!==e.length)return;let d={};for(let[p,b]of s.entries()){let w=e[p];if(w===void 0)return;if(b.startsWith(":")){try{d[b.slice(1)]=decodeURIComponent(w)}catch{return}continue}if(b!==w)return}return d}var Wn=15000;function zr(s){let e=[];if(s.event!==void 0)e.push(`event: ${s.event}`);if(s.id!==void 0)e.push(`id: ${s.id}`);let d=typeof s.data==="string"?s.data:JSON.stringify(s.data);for(let p of d.split(`
3
+ `))e.push(`data: ${p}`);return`${e.join(`
4
4
  `)}
5
5
 
6
- `}function Ge(a){let e=new TextEncoder,d,u,p=!1,m=new ReadableStream({start(b){let N=()=>{if(p)return;if(p=!0,u!==void 0)clearInterval(u);d?.(),d=void 0;try{b.close()}catch{}},V=(j)=>{if(p)return;try{b.enqueue(e.encode(Un(j)))}catch{N()}};a.signal?.addEventListener("abort",N,{once:!0});let F=a.start({send:V,close:N});if(p){F?.();return}d=F,u=setInterval(()=>{if(p)return;try{b.enqueue(e.encode(`: ping
6
+ `}function dt(s){let e=new TextEncoder,d,p,b=!1,w=new ReadableStream({start(N){let A=()=>{if(b)return;if(b=!0,p!==void 0)clearInterval(p);d?.(),d=void 0;try{N.close()}catch{}},U=(C)=>{if(b)return;try{N.enqueue(e.encode(zr(C)))}catch{A()}};s.signal?.addEventListener("abort",A,{once:!0});let H=s.start({send:U,close:A});if(b){H?.();return}d=H,p=setInterval(()=>{if(b)return;try{N.enqueue(e.encode(`: ping
7
7
 
8
- `))}catch{N()}},a.heartbeatMs??on),u.unref?.()},cancel(){if(p)return;if(p=!0,u!==void 0)clearInterval(u);d?.(),d=void 0}});return new Response(m,{status:a.status??200,headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}})}var pe=512;function ge(a,e){return`${a.toString(8).padStart(e-1,"0")}\x00`}function _e(a,e,d,u){let p=new Uint8Array(pe),m=(N,V)=>{p.set(new TextEncoder().encode(N),V)};m(a.slice(0,100),0),m(ge(420,8),100),m(ge(0,8),108),m(ge(0,8),116),m(ge(e,12),124),m(ge(Math.floor(d/1000),12),136),m(" ",148),m(u,156),m("ustar\x00",257),m("00",263);let b=0;for(let N of p)b+=N;return m(`${b.toString(8).padStart(6,"0")}\x00 `,148),p}function rt(a,e,d){if(new TextEncoder().encode(a).length<=100)return[_e(a,e,d,"0")];let u=(b)=>`${b} path=${a}
9
- `,p=u(0);for(let b=p.length;;b=p.length)if(p=u(new TextEncoder().encode(u(b)).length),new TextEncoder().encode(p).length===b)break;let m=new TextEncoder().encode(p);return[_e("PaxHeader",m.length,d,"x"),...ln(m),_e(a,e,d,"0")]}function ln(a){let e=a.length%pe;return e===0?[a]:[a,new Uint8Array(pe-e)]}async function*Hn(a,e){try{yield*Gn(a)}finally{await e()}}async function*Gn(a){for(let e of a){if("bytes"in e.source){yield*rt(e.name,e.source.bytes.length,Date.now()),yield*ln(e.source.bytes);continue}let d=await Fn(e.source.path);yield*rt(e.name,d.size,d.mtimeMs);let u=0;if(d.size>0)for await(let p of Bn(e.source.path,{end:d.size-1})){let m=p;u+=m.length,yield m}if(u<d.size)yield new Uint8Array(d.size-u);if(d.size%pe!==0)yield new Uint8Array(pe-d.size%pe)}yield new Uint8Array(pe*2)}function qn(a,e=async()=>{}){let d=at.from(Hn(a,e)).pipe(Kn());return at.toWeb(d)}var Wn=':root{color-scheme:dark;--ground: #0a0a0a;--raised: #111111;--raised-2: #171717;--line: #262626;--line-strong: #333333;--text: #ededed;--dim: #a1a1a1;--faint: #6b6b6b;--accent: #d75fd7;--accent-soft: rgb(215 95 215 / 12%);--accent-ink: #0a0a0a;--warn: #d7af5f;--warn-soft: rgb(215 175 95 / 10%);--bad: #f7768e;--bad-soft: rgb(247 118 142 / 10%);--ok: #5fd75f;--info: #5f87d7;--shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 24px rgb(0 0 0 / 25%);--radius: 8px;--mono: "JetBrains Mono", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;--sans: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif}@media(prefers-color-scheme:light){:root:not([data-theme=dark]){color-scheme:light;--ground: #fafafa;--raised: #ffffff;--raised-2: #f4f4f5;--line: #e5e5e5;--line-strong: #d4d4d4;--text: #171717;--dim: #616161;--faint: #9a9a9a;--accent: #b23fb2;--accent-soft: rgb(178 63 178 / 9%);--accent-ink: #ffffff;--warn: #9a6b12;--warn-soft: rgb(154 107 18 / 8%);--bad: #c62a4a;--bad-soft: rgb(198 42 74 / 7%);--ok: #1f8a3a;--info: #2f5fb3;--shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%)}}:root[data-theme=light]{color-scheme:light;--ground: #fafafa;--raised: #ffffff;--raised-2: #f4f4f5;--line: #e5e5e5;--line-strong: #d4d4d4;--text: #171717;--dim: #616161;--faint: #9a9a9a;--accent: #b23fb2;--accent-soft: rgb(178 63 178 / 9%);--accent-ink: #ffffff;--warn: #9a6b12;--warn-soft: rgb(154 107 18 / 8%);--bad: #c62a4a;--bad-soft: rgb(198 42 74 / 7%);--ok: #1f8a3a;--info: #2f5fb3;--shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%)}*{box-sizing:border-box}html,body{margin:0;background:var(--ground);color:var(--text)}body{font:14px / 1.55 var(--sans);-webkit-font-smoothing:antialiased;font-feature-settings:"cv11","ss01"}code{font-family:var(--mono);font-size:.88em;background:var(--raised-2);border:1px solid var(--line);border-radius:4px;padding:1px 5px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}::selection{background:var(--accent-soft)}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:500;color:inherit;background:var(--raised);border:1px solid var(--line);border-radius:6px;padding:6px 12px;cursor:pointer;transition:background .12s,border-color .12s,color .12s}button:hover:not(:disabled){border-color:var(--line-strong);background:var(--raised-2)}button:disabled{opacity:.45;cursor:default}button.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink);font-weight:600}button.primary:hover:not(:disabled){background:var(--accent);border-color:var(--accent);filter:brightness(1.08)}button.bad{color:var(--bad)}input,textarea,select{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%;transition:border-color .12s,box-shadow .12s}input:focus,textarea:focus,select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)}.shell{display:grid;grid-template-columns:248px 1fr;height:100vh}.side{background:var(--ground);border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}.side header{padding:14px 16px;height:52px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--line)}.brand{font-weight:700;letter-spacing:-.01em;font-size:15px;display:flex;align-items:center;gap:8px}.wordmark{display:block;color:var(--accent);width:auto}.version{font-family:var(--mono);font-size:11px;color:var(--faint)}.side nav{padding:8px 10px;overflow-y:auto;flex:1;min-height:0}.side footer{padding:10px 14px;border-top:1px solid var(--line);display:flex;gap:8px;align-items:center}.row-button{display:flex;align-items:center;gap:8px;width:100%;text-align:left;background:none;border:1px solid transparent;border-radius:6px;padding:6px 9px;font-size:13px;font-weight:450;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.row-button:hover:not(:disabled){background:var(--raised-2);border-color:transparent;color:var(--text)}.row-button[aria-current=true]{background:var(--raised-2);color:var(--text);border-color:var(--line)}.row-button.session{font-family:var(--mono);font-size:12px}.row-button.session.person{font-family:var(--sans)}.group{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.08em;color:var(--faint);padding:16px 9px 6px}.main{display:flex;flex-direction:column;min-height:0;min-width:0}.bar{display:flex;gap:12px;align-items:center;padding:0 20px;border-bottom:1px solid var(--line);font-size:12px;color:var(--dim);height:52px;flex-shrink:0;background:color-mix(in srgb,var(--ground) 85%,transparent);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.bar strong{color:var(--text);font-size:14px;font-weight:600;white-space:nowrap}.bar .crumb{color:var(--faint)}.bar .spacer{flex:1}.bar a,.bar .ghost{color:var(--dim);font-size:12px;font-weight:500;padding:5px 10px;border:1px solid var(--line);border-radius:6px;background:transparent;white-space:nowrap}.bar a:hover,.bar .ghost:hover:not(:disabled){color:var(--text);text-decoration:none;background:var(--raised-2)}.scroll{flex:1;overflow-y:auto;min-height:0;padding:28px 24px}.pad{max-width:820px;margin:0 auto}.pad.wide{max-width:1100px}.page-head{margin:0 0 22px}.page-head h1{font-size:24px;font-weight:650;letter-spacing:-.02em;margin:0 0 4px}.page-head p{color:var(--dim);margin:0;max-width:68ch}.row{margin:0 0 18px;white-space:pre-wrap;overflow-wrap:anywhere}.row.user{background:var(--raised-2);border:1px solid var(--line);border-radius:12px;padding:10px 14px;margin-left:auto;max-width:85%;width:fit-content}.row.reply{white-space:normal}.row.reply>:first-child{margin-top:0}.row.reply>:last-child{margin-bottom:0}.row.reply p,.row.reply ul,.row.reply ol,.row.reply blockquote{margin:0 0 10px}.row.reply h1,.row.reply h2,.row.reply h3,.row.reply h4{margin:16px 0 8px;letter-spacing:-.01em;line-height:1.3}.row.reply h1{font-size:20px}.row.reply h2{font-size:17px}.row.reply h3,.row.reply h4{font-size:15px}.row.reply ul,.row.reply ol{padding-left:22px}.row.reply li>p{margin:0 0 4px}.row.reply blockquote{border-left:3px solid var(--line-strong);padding:2px 12px;color:var(--dim)}.row.reply hr{border:none;border-top:1px solid var(--line);margin:14px 0}.row.reply a{text-decoration:underline;text-underline-offset:2px}.md-code{margin:0 0 10px;border:1px solid var(--line);border-radius:var(--radius);background:var(--ground);overflow:hidden}.md-code.open{border-style:dashed}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:4px 6px 4px 12px;font-family:var(--mono);font-size:11px;color:var(--faint);border-bottom:1px solid var(--line);background:var(--raised)}.md-code-head button{font-size:11px;padding:2px 8px}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto;font-family:var(--mono);font-size:12.5px;line-height:1.55}.md-code pre code{background:none;border:none;padding:0;font-size:inherit}.md-table{overflow-x:auto;margin:0 0 10px}.md-table table{width:auto;min-width:50%;border:1px solid var(--line);border-radius:var(--radius);border-collapse:separate;border-spacing:0}.md-table th{padding:8px 12px;background:var(--raised-2);text-transform:none;letter-spacing:0;font-size:12px;color:var(--text);border-bottom:1px solid var(--line)}.md-table td{padding:8px 12px;font-family:var(--sans);font-size:13px;border-top:1px solid var(--line)}.label{font-family:var(--mono);font-size:11px;color:var(--faint);margin-bottom:4px}.tool{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:8px 12px;font-family:var(--mono);font-size:12px}.tool .slug{color:var(--accent);font-weight:600}.tool .out{color:var(--dim);max-height:13em;overflow-y:auto;margin-top:5px;display:inline}.tool.failed{border-color:color-mix(in srgb,var(--bad) 40%,var(--line))}.tool.failed .slug{color:var(--bad)}.tool .mut{color:var(--warn);font-size:11px}.fence{border:1px dashed var(--warn);border-radius:6px;padding:7px 9px;margin-top:5px}.fence .why{color:var(--warn);font-size:11px;margin-bottom:4px}.payload-code{font-family:var(--mono);font-size:28px;font-weight:600;letter-spacing:.18em;margin:10px 0;-webkit-user-select:all;user-select:all}.channel-input.stale .payload-code{opacity:.35}.payload-qr{display:block;width:240px;max-width:100%;height:auto;border-radius:6px;margin:8px 0}.channel-input.stale .payload-qr{opacity:.35}.note{font-size:12px;color:var(--dim);border-left:2px solid var(--line-strong);padding:2px 0 2px 11px;white-space:pre-wrap}.note.bad{color:var(--bad);border-left-color:var(--bad);background:var(--bad-soft);border-radius:0 6px 6px 0;padding:8px 12px}.ask{border:1px solid color-mix(in srgb,var(--warn) 55%,var(--line));border-radius:var(--radius);padding:12px 14px;background:var(--warn-soft)}.ask .what{font-family:var(--mono);font-size:12px;margin:6px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}.ask .buttons{display:flex;gap:8px;flex-wrap:wrap}.ask .settled{font-size:12px;color:var(--dim)}details.fold summary{cursor:pointer;color:var(--faint);font-family:var(--mono);font-size:11px}details.fold[open] summary{margin-bottom:5px}details.fold .body{color:var(--dim);font-size:13px}.tool details.subagent{margin-top:4px}.tool details.subagent summary{cursor:pointer;color:var(--dim);font-size:11px}.tool details.subagent ul{list-style:none;margin:4px 0 0;padding-left:12px;border-left:1px solid var(--line);color:var(--dim)}.tool details.subagent li.failed .slug{color:var(--bad)}.composer{padding:12px 24px 18px}.composer .inner{max-width:820px;margin:0 auto;display:flex;gap:8px;align-items:flex-end;background:var(--raised);border:1px solid var(--line);border-radius:12px;padding:8px;box-shadow:var(--shadow)}.composer .inner:focus-within{border-color:color-mix(in srgb,var(--accent) 60%,var(--line))}.composer .role-pick{width:auto;font-family:var(--mono);font-size:12px;padding:6px 8px}.attachments{max-width:820px;margin:0 auto 8px;display:flex;gap:8px;flex-wrap:wrap}.attachment{position:relative;display:inline-block}.attachment img{height:56px;width:56px;object-fit:cover;border-radius:8px;border:1px solid var(--line);display:block}.attachment button{position:absolute;top:-6px;right:-6px;width:18px;height:18px;padding:0;line-height:1;font-size:12px;border-radius:50%}.composer textarea{resize:none;min-height:40px;max-height:190px;font-family:var(--sans);border:none;background:transparent;box-shadow:none}.composer textarea:focus{box-shadow:none}.hint{font-size:11px;color:var(--faint);max-width:820px;margin:6px auto 0}.card{border:1px solid var(--line);border-radius:var(--radius);padding:18px 20px;margin-bottom:14px;background:var(--raised)}.card h2{margin:0 0 4px;font-size:15px;font-weight:600}.card h3{margin:0 0 8px;font-size:13px;font-weight:600}.card p{margin:0 0 12px;color:var(--dim);font-size:13px}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);font-weight:600;padding:0 10px 8px 0}td{padding:9px 10px 9px 0;border-top:1px solid var(--line);font-family:var(--mono);font-size:12px}td.revoked{color:var(--faint);text-decoration:line-through}.secret{font-family:var(--mono);font-size:12px;background:var(--ground);border:1px solid var(--ok);border-radius:6px;padding:9px 11px;overflow-wrap:anywhere;margin-bottom:8px}.gate{display:grid;place-items:center;min-height:100vh;padding:20px;background:radial-gradient(ellipse 60% 40% at 50% 0%,var(--accent-soft),transparent 70%),var(--ground)}.gate .card{max-width:440px;width:100%;padding:28px;box-shadow:var(--shadow)}.gate .card h2{font-size:18px;letter-spacing:-.01em;margin-bottom:6px}.gate .brand{margin-bottom:18px}.gate input{font-family:var(--mono);font-size:12px}.gate .ask{border:none;background:none;padding:0}.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0;background:var(--faint)}.dot.live{background:var(--ok);box-shadow:0 0 0 3px color-mix(in srgb,var(--ok) 18%,transparent)}.dot.busy{background:var(--warn);box-shadow:0 0 0 3px color-mix(in srgb,var(--warn) 18%,transparent)}.dot.off{background:var(--faint)}.dot.warn{background:var(--warn)}@media(max-width:720px){.shell{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr);height:100dvh}.side{min-width:0;border-right:none;border-bottom:1px solid var(--line)}.side header{height:48px}.side nav{display:flex;gap:4px;overflow-x:auto;padding:6px 10px;flex:none}.side nav .group,.side nav .agent-note,.side footer{display:none}.side nav .row-button,.side nav .agent-row{width:auto;flex-shrink:0}.bar{padding:0 14px;height:48px}.bar .hide-narrow{display:none}.scroll{padding:18px 16px}.composer{padding:10px 12px 12px}}.agent-row{display:block}.agent-row .row-button:disabled{color:var(--faint);cursor:default}.agent-off{color:var(--warn);font-size:11px}.agent-note{display:flex;gap:6px;align-items:baseline;padding:0 9px 6px 24px;font-size:11px;color:var(--faint)}.link{background:none;border:none;padding:0;color:var(--accent);font-size:11px;text-decoration:underline;cursor:pointer}.link:hover:not(:disabled){background:none}.link:disabled{color:var(--faint);cursor:default;text-decoration:none}.empty{color:var(--dim);font-size:13px;max-width:60ch}.empty-state{border:1px dashed var(--line-strong);border-radius:var(--radius);padding:28px;text-align:center;color:var(--dim)}.empty-state h3{color:var(--text);margin:0 0 6px;font-size:14px}.empty-state p{margin:0 auto;max-width:56ch;font-size:13px}.panel-table{width:100%;border-collapse:separate;border-spacing:0;font-size:12px;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden;background:var(--raised)}.panel-table th{text-align:left;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--faint);padding:10px 12px;border-bottom:1px solid var(--line);background:var(--raised-2)}.panel-table td{padding:10px 12px;border-top:none;border-bottom:1px solid var(--line);vertical-align:top}.panel-table tr:last-child td{border-bottom:none}.panel-table tr:hover td{background:var(--raised-2)}.panel-table tr.off td{color:var(--faint)}.channel{border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;margin-bottom:12px;background:var(--raised)}.channel h3{margin:0 0 6px;font-size:13px;font-weight:600}.status{margin:0;font-size:12px}.status-connected{color:var(--ok)}.status-error,.status-disconnected{color:var(--bad)}.status-needs_input{color:var(--warn)}.channel-input{margin-top:10px;padding:10px;border-radius:6px;background:var(--ground)}.payload{margin:0;font-family:var(--mono);font-size:11px;white-space:pre-wrap;word-break:break-all;max-height:9em;overflow-y:auto}.channel-input.stale .payload{opacity:.45}.warn{color:var(--warn);font-size:12px;margin:0 0 6px}.provision{display:flex;flex-direction:column;gap:16px;max-width:60ch}.provision>button[type=submit]{align-self:flex-start}.field label{display:block;font-size:12px;font-weight:500;color:var(--dim);margin-bottom:6px}.field.invalid input,.field.invalid select{border-color:var(--bad)}.sub{color:var(--dim);font-size:12px;margin-top:2px;max-width:60ch}.error{color:var(--bad);font-size:13px;max-width:60ch}.ok{color:var(--ok);font-size:13px}.created{max-width:66ch;font-size:13px}.created h3{font-size:15px;font-weight:600;margin:0 0 10px}.created p{margin:0 0 10px}.blank-secrets{border:1px solid var(--warn);border-radius:6px;padding:11px 13px;margin:14px 0}.blank-secrets p{margin:0 0 6px}.blank-secrets p:last-child{margin:0}.config-row{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px;margin-bottom:10px}.config-head{display:flex;align-items:baseline;gap:8px;font-family:var(--mono);font-size:13px;font-weight:600}.config-row .sub{margin:4px 0 10px;max-width:72ch}.config-row input[type=text],.config-row input:not([type]),.config-row textarea{width:100%;font-family:var(--mono);font-size:12px}.config-row button{margin-top:8px}.config-row label input[type=checkbox]{width:auto;margin-right:4px;vertical-align:baseline}.form-grid{display:grid;grid-template-columns:6em 1fr;gap:8px 12px;align-items:start;max-width:60ch}.form-grid label{font-size:12px;color:var(--dim);padding-top:9px}.form-grid input,.form-grid select{width:100%}.form-grid>div>input+input{margin-top:6px}.warnings{border:1px solid color-mix(in srgb,var(--warn) 45%,var(--line));background:var(--warn-soft);border-radius:var(--radius);padding:10px 14px;margin-bottom:20px;font-size:13px}.warnings summary{cursor:pointer;list-style:none;display:flex;gap:8px;align-items:center}.warnings summary::-webkit-details-marker{display:none}.warnings h3{margin:0;color:var(--warn);font-size:13px;font-weight:600}.warnings .sub{margin:8px 0 4px}.warning{margin-top:10px;padding-top:10px;border-top:1px solid color-mix(in srgb,var(--warn) 20%,transparent)}.warning-message{margin:0}.warning .hint{margin:4px 0 0;max-width:none}.channel-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem}.channel-actions form{display:flex;gap:.35rem}.channel-actions input{min-width:14rem}.status-off{opacity:.7}.model-card.primary{border-color:color-mix(in srgb,var(--accent) 35%,var(--line))}.model-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}.model-role{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint)}.model-id{font-family:var(--mono);font-size:16px;font-weight:600;overflow-wrap:anywhere}.control{margin-bottom:16px;min-width:0}.control-label{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px;font-size:13px;font-weight:600;margin-bottom:8px}.control-label .sub{font-weight:400;margin:0;flex-basis:100%}.mono-value{font-family:var(--mono);font-size:12px;color:var(--accent);margin-left:auto}.control-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:0 24px}.inline{display:flex;gap:8px;align-items:center}input[type=range]{accent-color:var(--accent);padding:0;border:none;background:none;box-shadow:none}.segmented{margin:0;min-width:0;display:inline-flex;flex-wrap:wrap;gap:2px;padding:3px;background:var(--ground);border:1px solid var(--line);border-radius:8px}.segmented button{border:1px solid transparent;background:none;padding:4px 11px;font-size:12px;color:var(--dim);border-radius:6px}.segmented button:hover:not(:disabled){background:var(--raised-2);border-color:transparent;color:var(--text)}.segmented button[aria-pressed=true]{background:var(--accent-soft);border-color:color-mix(in srgb,var(--accent) 45%,var(--line));color:var(--accent);font-weight:600}.model-foot{display:flex;align-items:center;gap:10px;flex-wrap:wrap;border-top:1px solid var(--line);padding-top:12px}.model-form{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px 16px;margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}.model-form label{display:flex;flex-direction:column;gap:6px;font-size:12px;font-weight:500;color:var(--dim)}.model-form label .sub,.model-form label .error{font-size:11px;margin:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.agent-card{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:16px 18px;display:flex;flex-direction:column;gap:12px;text-align:left;transition:border-color .12s,transform .12s}button.agent-card{font-size:13px;font-weight:400;width:100%}button.agent-card:hover:not(:disabled){border-color:color-mix(in srgb,var(--accent) 50%,var(--line));background:var(--raised)}.agent-card.off{opacity:.75}.agent-card .head{display:flex;align-items:center;gap:10px}.agent-card .name{font-weight:600;font-size:15px;letter-spacing:-.01em}.agent-card .id{font-family:var(--mono);font-size:11px;color:var(--faint)}.agent-card .model{font-family:var(--mono);font-size:12px;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats{display:flex;flex-wrap:wrap;gap:6px}.pill{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--line);border-radius:999px;padding:2px 9px;font-size:11px;font-weight:500;color:var(--dim);background:var(--ground);white-space:nowrap}.pill.accent{color:var(--accent);border-color:color-mix(in srgb,var(--accent) 35%,var(--line));background:var(--accent-soft)}.pill.ok{color:var(--ok)}.pill.warn{color:var(--warn);border-color:color-mix(in srgb,var(--warn) 35%,var(--line))}.pill.bad{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 40%,var(--line));background:var(--bad-soft)}.error-line{color:var(--bad);font-size:12px;margin-top:4px;overflow-wrap:anywhere}.member{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px}.member .head{display:flex;align-items:center;gap:10px;margin-bottom:8px}.avatar{width:28px;height:28px;border-radius:7px;display:grid;place-items:center;font-weight:700;font-size:12px;color:var(--accent);background:var(--accent-soft);border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));flex-shrink:0;text-transform:uppercase}.member .task{color:var(--dim);font-size:13px;margin:0 0 10px}.lead{display:flex;align-items:center;gap:12px;border:1px solid color-mix(in srgb,var(--accent) 35%,var(--line));background:var(--accent-soft);border-radius:var(--radius);padding:14px 16px;margin-bottom:14px}.section-title{font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);margin:28px 0 10px}pre.snippet{position:relative;margin:0;background:var(--ground);border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;font-family:var(--mono);font-size:12px;line-height:1.6;overflow-x:auto;white-space:pre}.snippet-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:8px}.snippet-head h3{margin:0;font-size:13px;font-weight:600}.snippet-head button{font-size:11px;padding:3px 9px}.method{font-family:var(--mono);font-size:10px;font-weight:700;letter-spacing:.04em;padding:2px 6px;border-radius:4px;color:var(--accent-ink);background:var(--accent)}.method.get{background:var(--info);color:#fff}.endpoints{display:grid;gap:6px}.endpoint{display:flex;align-items:center;gap:10px;font-size:13px;padding:8px 12px;border:1px solid var(--line);border-radius:6px;background:var(--raised)}.endpoint code{background:none;border:none;padding:0;font-size:12px}.endpoint .what{color:var(--dim);margin-left:auto;font-size:12px;text-align:right}.cta-row{display:flex;gap:10px;flex-wrap:wrap}.cta-row a{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--line);border-radius:6px;font-size:13px;font-weight:500;color:var(--text);background:var(--raised)}.cta-row a.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}.cta-row a:hover{text-decoration:none;filter:brightness(1.08)}.fallbacks{margin:0 0 10px;padding-left:22px;display:grid;gap:6px}.fallbacks li{display:flex;align-items:center;gap:10px;font-size:13px}.schedule-card .head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}.schedule-id{font-size:13px;font-weight:600}.schedule-card .task{margin:0 0 12px;color:var(--text)}.schedule-card.off .task{color:var(--dim)}.facts{display:grid;grid-template-columns:max-content 1fr;gap:4px 12px;margin:0 0 12px;font-size:12px}.facts dt{color:var(--faint);text-transform:uppercase;letter-spacing:.06em;font-size:10px;padding-top:2px}.facts dd{margin:0;overflow-wrap:anywhere}.schedule-card .actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;border-top:1px solid var(--line);padding-top:10px}.schedule-form{margin-top:18px}.schedule-form h3{margin-bottom:14px}.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}.chips .pill{cursor:pointer}.chips .pill:hover{color:var(--text);border-color:var(--line-strong)}.preview{display:block;margin-top:6px}.preview.bad{color:var(--bad)}.model-form textarea{resize:vertical;font-family:var(--sans)}.model-form .field-like{display:flex;flex-direction:column;gap:6px;font-size:12px;font-weight:500;color:var(--dim)}.search{margin-bottom:14px;max-width:420px}.tool-group{margin-bottom:18px}.tool-group h3{font-size:13px;font-weight:600;margin:0 0 8px;display:flex;align-items:baseline;gap:8px}.tool-group h3 .sub{margin:0}.rules{list-style:none;margin:0 0 10px;padding:0;display:grid;gap:6px}.rules li{display:flex;align-items:center;gap:10px;font-size:13px}.refresh-report ul{margin:0 0 8px;padding-left:18px;font-size:13px}:root{--chart: #c955c9}@media(prefers-color-scheme:light){:root:not([data-theme=dark]){--chart: #b23fb2}}:root[data-theme=light]{--chart: #b23fb2}.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:8px}.tile{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px}.tile-label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint)}.tile-value{font-size:24px;font-weight:650;letter-spacing:-.02em;font-variant-numeric:tabular-nums;margin:4px 0 2px}.chart{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:12px 12px 6px;margin-bottom:18px}.chart svg{display:block;width:100%;height:auto}.chart .bar{fill:var(--chart)}.chart .bar.hot{fill:var(--accent)}.chart .axis{stroke:var(--line-strong);stroke-width:1}.chart .value{fill:var(--dim);font-size:10px;font-family:var(--mono)}.chart .tick{fill:var(--faint);font-size:10px;font-family:var(--mono)}.chart .tooltip{min-height:1.6em;font-size:12px;color:var(--dim);font-family:var(--mono);padding:4px 2px 0}.turns{display:grid;gap:8px}.turn{padding:0;margin:0;overflow:hidden}.turn.bad{border-color:color-mix(in srgb,var(--warn) 40%,var(--line))}.turn-head{width:100%;display:flex;align-items:center;gap:12px;text-align:left;background:none;border:none;border-radius:0;padding:12px 16px;font-weight:400}.turn-head:hover:not(:disabled){background:var(--raised-2);border-color:transparent}.turn-input{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}.turn-meta{display:flex;gap:12px;font-family:var(--mono);font-size:11px;color:var(--faint);white-space:nowrap}.turn-body{border-top:1px solid var(--line);padding:14px 16px 16px}.turn-body .facts{margin-bottom:14px}@media(max-width:720px){.turn-meta{display:none}}.person .head,.card>.head{display:flex;align-items:center;gap:10px;margin-bottom:10px}.person .name{font-weight:600}.person .id{font-family:var(--mono);font-size:11px;color:var(--faint)}.person{display:flex;flex-direction:column;gap:12px}.facts-label{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);margin-bottom:6px}.check{display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.check input{width:auto}.members{display:flex;flex-wrap:wrap;gap:10px 16px}.rooms-layout{display:grid;grid-template-columns:260px minmax(0,1fr);gap:18px}.rooms-list .row-button{margin-bottom:2px}.rooms-main{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);display:flex;flex-direction:column;min-height:420px}.rooms-main .empty-state{border:none;margin:auto}.room-head{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:8px}.room-log{flex:1;padding:14px 16px;overflow-y:auto;display:grid;gap:12px;align-content:start}.room-msg{font-size:13px}.room-msg.agent{border-left:2px solid var(--accent);padding-left:12px}.room-post{border-top:1px solid var(--line);padding:12px 16px}.notes{display:grid;gap:8px}.note-card{margin:0;padding:12px 14px}@media(max-width:720px){.rooms-layout{grid-template-columns:minmax(0,1fr)}}.editor{flex:1;min-height:420px;border:none;border-radius:0;background:var(--ground);font-family:var(--mono);font-size:12.5px;line-height:1.6;padding:14px 16px;resize:vertical}.editor:focus{box-shadow:none}.model-form label.check,label.check{flex-direction:row;align-items:center;font-weight:400;color:var(--text)}.inline-field{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;color:var(--dim)}.room-skip{margin-top:6px;font-size:12px;color:var(--warn)}.tool-detail{margin-top:6px}.tool-detail-summary{cursor:pointer;color:var(--dim);font-size:12px}.tool-detail pre{max-height:320px;overflow:auto}.replay{list-style:none;padding:0;margin:12px 0 0;display:grid;gap:10px}.replay pre,.tool-detail pre{max-width:100%;box-sizing:border-box;white-space:pre-wrap;overflow-wrap:anywhere}.replay pre{max-height:280px;overflow:auto;margin:4px 0 0}.palette-layer{position:fixed;inset:0;z-index:50;display:flex;justify-content:center;align-items:flex-start;padding:12vh 16px 16px}button.palette-backdrop,button.palette-backdrop:hover:not(:disabled){position:absolute;inset:0;border:none;border-radius:0;background:#00000059;cursor:default}.palette{position:relative;width:min(560px,100%);background:var(--raised);border:1px solid var(--line);border-radius:12px;box-shadow:0 16px 48px #0000004d;overflow:hidden}.palette input{width:100%;border:none;border-bottom:1px solid var(--line);border-radius:0;padding:14px 16px;font-size:15px;background:transparent}.palette-list{list-style:none;margin:0;padding:6px;max-height:50vh;overflow:auto}.palette-item{width:100%;display:flex;justify-content:space-between;gap:12px;padding:8px 10px;border:none;border-radius:8px;background:transparent;text-align:left}.palette-item[aria-current=true]{background:var(--raised-2)}.palette .sub{margin:0}.palette .empty{padding:16px}.caps-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0}.caps-row .mono-value{margin:0;min-width:80px}.caps-row select,.caps-row input{width:auto}\n',Vn=`(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))r(d);new MutationObserver(d=>{for(const f of d)if(f.type==="childList")for(const m of f.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&r(m)}).observe(document,{childList:!0,subtree:!0});function o(d){const f={};return d.integrity&&(f.integrity=d.integrity),d.referrerPolicy&&(f.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?f.credentials="include":d.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function r(d){if(d.ep)return;d.ep=!0;const f=o(d);fetch(d.href,f)}})();function a0(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Br={exports:{}},Gi={};var ym;function l0(){if(ym)return Gi;ym=1;var l=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function o(r,d,f){var m=null;if(f!==void 0&&(m=""+f),d.key!==void 0&&(m=""+d.key),"key"in d){f={};for(var v in d)v!=="key"&&(f[v]=d[v])}else f=d;return d=f.ref,{$$typeof:l,type:r,key:m,ref:d!==void 0?d:null,props:f}}return Gi.Fragment=c,Gi.jsx=o,Gi.jsxs=o,Gi}var bm;function i0(){return bm||(bm=1,Br.exports=l0()),Br.exports}var i=i0(),Lr={exports:{}},ve={};var pm;function s0(){if(pm)return ve;pm=1;var l=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),f=Symbol.for("react.consumer"),m=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),y=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),S=Symbol.iterator;function N(C){return C===null||typeof C!="object"?null:(C=S&&C[S]||C["@@iterator"],typeof C=="function"?C:null)}var R={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},L=Object.assign,P={};function J(C,q,I){this.props=C,this.context=q,this.refs=P,this.updater=I||R}J.prototype.isReactComponent={},J.prototype.setState=function(C,q){if(typeof C!="object"&&typeof C!="function"&&C!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,C,q,"setState")},J.prototype.forceUpdate=function(C){this.updater.enqueueForceUpdate(this,C,"forceUpdate")};function Z(){}Z.prototype=J.prototype;function F(C,q,I){this.props=C,this.context=q,this.refs=P,this.updater=I||R}var _=F.prototype=new Z;_.constructor=F,L(_,J.prototype),_.isPureReactComponent=!0;var ge=Array.isArray;function ee(){}var V={H:null,A:null,T:null,S:null},le=Object.prototype.hasOwnProperty;function W(C,q,I){var ie=I.ref;return{$$typeof:l,type:C,key:q,ref:ie!==void 0?ie:null,props:I}}function Y(C,q){return W(C.type,q,C.props)}function ne(C){return typeof C=="object"&&C!==null&&C.$$typeof===l}function ae(C){var q={"=":"=0",":":"=2"};return"$"+C.replace(/[=:]/g,function(I){return q[I]})}var Q=/\\/+/g;function se(C,q){return typeof C=="object"&&C!==null&&C.key!=null?ae(""+C.key):q.toString(36)}function re(C){switch(C.status){case"fulfilled":return C.value;case"rejected":throw C.reason;default:switch(typeof C.status=="string"?C.then(ee,ee):(C.status="pending",C.then(function(q){C.status==="pending"&&(C.status="fulfilled",C.value=q)},function(q){C.status==="pending"&&(C.status="rejected",C.reason=q)})),C.status){case"fulfilled":return C.value;case"rejected":throw C.reason}}throw C}function D(C,q,I,ie,me){var be=typeof C;(be==="undefined"||be==="boolean")&&(C=null);var ye=!1;if(C===null)ye=!0;else switch(be){case"bigint":case"string":case"number":ye=!0;break;case"object":switch(C.$$typeof){case l:case c:ye=!0;break;case j:return ye=C._init,D(ye(C._payload),q,I,ie,me)}}if(ye)return me=me(C),ye=ie===""?"."+se(C,0):ie,ge(me)?(I="",ye!=null&&(I=ye.replace(Q,"$&/")+"/"),D(me,q,I,"",function(Wt){return Wt})):me!=null&&(ne(me)&&(me=Y(me,I+(me.key==null||C&&C.key===me.key?"":(""+me.key).replace(Q,"$&/")+"/")+ye)),q.push(me)),1;ye=0;var ze=ie===""?".":ie+":";if(ge(C))for(var oe=0;oe<C.length;oe++)ie=C[oe],be=ze+se(ie,oe),ye+=D(ie,q,I,be,me);else if(oe=N(C),typeof oe=="function")for(C=oe.call(C),oe=0;!(ie=C.next()).done;)ie=ie.value,be=ze+se(ie,oe++),ye+=D(ie,q,I,be,me);else if(be==="object"){if(typeof C.then=="function")return D(re(C),q,I,ie,me);throw q=String(C),Error("Objects are not valid as a React child (found: "+(q==="[object Object]"?"object with keys {"+Object.keys(C).join(", ")+"}":q)+"). If you meant to render a collection of children, use an array instead.")}return ye}function te(C,q,I){if(C==null)return C;var ie=[],me=0;return D(C,ie,"","",function(be){return q.call(I,be,me++)}),ie}function G(C){if(C._status===-1){var q=C._result;q=q(),q.then(function(I){(C._status===0||C._status===-1)&&(C._status=1,C._result=I)},function(I){(C._status===0||C._status===-1)&&(C._status=2,C._result=I)}),C._status===-1&&(C._status=0,C._result=q)}if(C._status===1)return C._result.default;throw C._result}var Ae=typeof reportError=="function"?reportError:function(C){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var q=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof C=="object"&&C!==null&&typeof C.message=="string"?String(C.message):String(C),error:C});if(!window.dispatchEvent(q))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",C);return}console.error(C)},Ce={map:te,forEach:function(C,q,I){te(C,function(){q.apply(this,arguments)},I)},count:function(C){var q=0;return te(C,function(){q++}),q},toArray:function(C){return te(C,function(q){return q})||[]},only:function(C){if(!ne(C))throw Error("React.Children.only expected to receive a single React element child.");return C}};return ve.Activity=g,ve.Children=Ce,ve.Component=J,ve.Fragment=o,ve.Profiler=d,ve.PureComponent=F,ve.StrictMode=r,ve.Suspense=x,ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=V,ve.__COMPILER_RUNTIME={__proto__:null,c:function(C){return V.H.useMemoCache(C)}},ve.cache=function(C){return function(){return C.apply(null,arguments)}},ve.cacheSignal=function(){return null},ve.cloneElement=function(C,q,I){if(C==null)throw Error("The argument must be a React element, but you passed "+C+".");var ie=L({},C.props),me=C.key;if(q!=null)for(be in q.key!==void 0&&(me=""+q.key),q)!le.call(q,be)||be==="key"||be==="__self"||be==="__source"||be==="ref"&&q.ref===void 0||(ie[be]=q[be]);var be=arguments.length-2;if(be===1)ie.children=I;else if(1<be){for(var ye=Array(be),ze=0;ze<be;ze++)ye[ze]=arguments[ze+2];ie.children=ye}return W(C.type,me,ie)},ve.createContext=function(C){return C={$$typeof:m,_currentValue:C,_currentValue2:C,_threadCount:0,Provider:null,Consumer:null},C.Provider=C,C.Consumer={$$typeof:f,_context:C},C},ve.createElement=function(C,q,I){var ie,me={},be=null;if(q!=null)for(ie in q.key!==void 0&&(be=""+q.key),q)le.call(q,ie)&&ie!=="key"&&ie!=="__self"&&ie!=="__source"&&(me[ie]=q[ie]);var ye=arguments.length-2;if(ye===1)me.children=I;else if(1<ye){for(var ze=Array(ye),oe=0;oe<ye;oe++)ze[oe]=arguments[oe+2];me.children=ze}if(C&&C.defaultProps)for(ie in ye=C.defaultProps,ye)me[ie]===void 0&&(me[ie]=ye[ie]);return W(C,be,me)},ve.createRef=function(){return{current:null}},ve.forwardRef=function(C){return{$$typeof:v,render:C}},ve.isValidElement=ne,ve.lazy=function(C){return{$$typeof:j,_payload:{_status:-1,_result:C},_init:G}},ve.memo=function(C,q){return{$$typeof:y,type:C,compare:q===void 0?null:q}},ve.startTransition=function(C){var q=V.T,I={};V.T=I;try{var ie=C(),me=V.S;me!==null&&me(I,ie),typeof ie=="object"&&ie!==null&&typeof ie.then=="function"&&ie.then(ee,Ae)}catch(be){Ae(be)}finally{q!==null&&I.types!==null&&(q.types=I.types),V.T=q}},ve.unstable_useCacheRefresh=function(){return V.H.useCacheRefresh()},ve.use=function(C){return V.H.use(C)},ve.useActionState=function(C,q,I){return V.H.useActionState(C,q,I)},ve.useCallback=function(C,q){return V.H.useCallback(C,q)},ve.useContext=function(C){return V.H.useContext(C)},ve.useDebugValue=function(){},ve.useDeferredValue=function(C,q){return V.H.useDeferredValue(C,q)},ve.useEffect=function(C,q){return V.H.useEffect(C,q)},ve.useEffectEvent=function(C){return V.H.useEffectEvent(C)},ve.useId=function(){return V.H.useId()},ve.useImperativeHandle=function(C,q,I){return V.H.useImperativeHandle(C,q,I)},ve.useInsertionEffect=function(C,q){return V.H.useInsertionEffect(C,q)},ve.useLayoutEffect=function(C,q){return V.H.useLayoutEffect(C,q)},ve.useMemo=function(C,q){return V.H.useMemo(C,q)},ve.useOptimistic=function(C,q){return V.H.useOptimistic(C,q)},ve.useReducer=function(C,q,I){return V.H.useReducer(C,q,I)},ve.useRef=function(C){return V.H.useRef(C)},ve.useState=function(C){return V.H.useState(C)},ve.useSyncExternalStore=function(C,q,I){return V.H.useSyncExternalStore(C,q,I)},ve.useTransition=function(){return V.H.useTransition()},ve.version="19.2.8",ve}var xm;function Lo(){return xm||(xm=1,Lr.exports=s0()),Lr.exports}var T=Lo(),Hr={exports:{}},Yi={},qr={exports:{}},$r={};var jm;function c0(){return jm||(jm=1,(function(l){function c(D,te){var G=D.length;D.push(te);e:for(;0<G;){var Ae=G-1>>>1,Ce=D[Ae];if(0<d(Ce,te))D[Ae]=te,D[G]=Ce,G=Ae;else break e}}function o(D){return D.length===0?null:D[0]}function r(D){if(D.length===0)return null;var te=D[0],G=D.pop();if(G!==te){D[0]=G;e:for(var Ae=0,Ce=D.length,C=Ce>>>1;Ae<C;){var q=2*(Ae+1)-1,I=D[q],ie=q+1,me=D[ie];if(0>d(I,G))ie<Ce&&0>d(me,I)?(D[Ae]=me,D[ie]=G,Ae=ie):(D[Ae]=I,D[q]=G,Ae=q);else if(ie<Ce&&0>d(me,G))D[Ae]=me,D[ie]=G,Ae=ie;else break e}}return te}function d(D,te){var G=D.sortIndex-te.sortIndex;return G!==0?G:D.id-te.id}if(l.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var f=performance;l.unstable_now=function(){return f.now()}}else{var m=Date,v=m.now();l.unstable_now=function(){return m.now()-v}}var x=[],y=[],j=1,g=null,S=3,N=!1,R=!1,L=!1,P=!1,J=typeof setTimeout=="function"?setTimeout:null,Z=typeof clearTimeout=="function"?clearTimeout:null,F=typeof setImmediate<"u"?setImmediate:null;function _(D){for(var te=o(y);te!==null;){if(te.callback===null)r(y);else if(te.startTime<=D)r(y),te.sortIndex=te.expirationTime,c(x,te);else break;te=o(y)}}function ge(D){if(L=!1,_(D),!R)if(o(x)!==null)R=!0,ee||(ee=!0,ae());else{var te=o(y);te!==null&&re(ge,te.startTime-D)}}var ee=!1,V=-1,le=5,W=-1;function Y(){return P?!0:!(l.unstable_now()-W<le)}function ne(){if(P=!1,ee){var D=l.unstable_now();W=D;var te=!0;try{e:{R=!1,L&&(L=!1,Z(V),V=-1),N=!0;var G=S;try{t:{for(_(D),g=o(x);g!==null&&!(g.expirationTime>D&&Y());){var Ae=g.callback;if(typeof Ae=="function"){g.callback=null,S=g.priorityLevel;var Ce=Ae(g.expirationTime<=D);if(D=l.unstable_now(),typeof Ce=="function"){g.callback=Ce,_(D),te=!0;break t}g===o(x)&&r(x),_(D)}else r(x);g=o(x)}if(g!==null)te=!0;else{var C=o(y);C!==null&&re(ge,C.startTime-D),te=!1}}break e}finally{g=null,S=G,N=!1}te=void 0}}finally{te?ae():ee=!1}}}var ae;if(typeof F=="function")ae=function(){F(ne)};else if(typeof MessageChannel<"u"){var Q=new MessageChannel,se=Q.port2;Q.port1.onmessage=ne,ae=function(){se.postMessage(null)}}else ae=function(){J(ne,0)};function re(D,te){V=J(function(){D(l.unstable_now())},te)}l.unstable_IdlePriority=5,l.unstable_ImmediatePriority=1,l.unstable_LowPriority=4,l.unstable_NormalPriority=3,l.unstable_Profiling=null,l.unstable_UserBlockingPriority=2,l.unstable_cancelCallback=function(D){D.callback=null},l.unstable_forceFrameRate=function(D){0>D||125<D?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):le=0<D?Math.floor(1e3/D):5},l.unstable_getCurrentPriorityLevel=function(){return S},l.unstable_next=function(D){switch(S){case 1:case 2:case 3:var te=3;break;default:te=S}var G=S;S=te;try{return D()}finally{S=G}},l.unstable_requestPaint=function(){P=!0},l.unstable_runWithPriority=function(D,te){switch(D){case 1:case 2:case 3:case 4:case 5:break;default:D=3}var G=S;S=D;try{return te()}finally{S=G}},l.unstable_scheduleCallback=function(D,te,G){var Ae=l.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?Ae+G:Ae):G=Ae,D){case 1:var Ce=-1;break;case 2:Ce=250;break;case 5:Ce=1073741823;break;case 4:Ce=1e4;break;default:Ce=5e3}return Ce=G+Ce,D={id:j++,callback:te,priorityLevel:D,startTime:G,expirationTime:Ce,sortIndex:-1},G>Ae?(D.sortIndex=G,c(y,D),o(x)===null&&D===o(y)&&(L?(Z(V),V=-1):L=!0,re(ge,G-Ae))):(D.sortIndex=Ce,c(x,D),R||N||(R=!0,ee||(ee=!0,ae()))),D},l.unstable_shouldYield=Y,l.unstable_wrapCallback=function(D){var te=S;return function(){var G=S;S=te;try{return D.apply(this,arguments)}finally{S=G}}}})($r)),$r}var Sm;function u0(){return Sm||(Sm=1,qr.exports=c0()),qr.exports}var Kr={exports:{}},yt={};var Nm;function r0(){if(Nm)return yt;Nm=1;var l=Lo();function c(x){var y="https://react.dev/errors/"+x;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)y+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+x+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(){}var r={d:{f:o,r:function(){throw Error(c(522))},D:o,C:o,L:o,m:o,X:o,S:o,M:o},p:0,findDOMNode:null},d=Symbol.for("react.portal");function f(x,y,j){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:d,key:g==null?null:""+g,children:x,containerInfo:y,implementation:j}}var m=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function v(x,y){if(x==="font")return"";if(typeof y=="string")return y==="use-credentials"?y:""}return yt.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,yt.createPortal=function(x,y){var j=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!y||y.nodeType!==1&&y.nodeType!==9&&y.nodeType!==11)throw Error(c(299));return f(x,y,null,j)},yt.flushSync=function(x){var y=m.T,j=r.p;try{if(m.T=null,r.p=2,x)return x()}finally{m.T=y,r.p=j,r.d.f()}},yt.preconnect=function(x,y){typeof x=="string"&&(y?(y=y.crossOrigin,y=typeof y=="string"?y==="use-credentials"?y:"":void 0):y=null,r.d.C(x,y))},yt.prefetchDNS=function(x){typeof x=="string"&&r.d.D(x)},yt.preinit=function(x,y){if(typeof x=="string"&&y&&typeof y.as=="string"){var j=y.as,g=v(j,y.crossOrigin),S=typeof y.integrity=="string"?y.integrity:void 0,N=typeof y.fetchPriority=="string"?y.fetchPriority:void 0;j==="style"?r.d.S(x,typeof y.precedence=="string"?y.precedence:void 0,{crossOrigin:g,integrity:S,fetchPriority:N}):j==="script"&&r.d.X(x,{crossOrigin:g,integrity:S,fetchPriority:N,nonce:typeof y.nonce=="string"?y.nonce:void 0})}},yt.preinitModule=function(x,y){if(typeof x=="string")if(typeof y=="object"&&y!==null){if(y.as==null||y.as==="script"){var j=v(y.as,y.crossOrigin);r.d.M(x,{crossOrigin:j,integrity:typeof y.integrity=="string"?y.integrity:void 0,nonce:typeof y.nonce=="string"?y.nonce:void 0})}}else y==null&&r.d.M(x)},yt.preload=function(x,y){if(typeof x=="string"&&typeof y=="object"&&y!==null&&typeof y.as=="string"){var j=y.as,g=v(j,y.crossOrigin);r.d.L(x,j,{crossOrigin:g,integrity:typeof y.integrity=="string"?y.integrity:void 0,nonce:typeof y.nonce=="string"?y.nonce:void 0,type:typeof y.type=="string"?y.type:void 0,fetchPriority:typeof y.fetchPriority=="string"?y.fetchPriority:void 0,referrerPolicy:typeof y.referrerPolicy=="string"?y.referrerPolicy:void 0,imageSrcSet:typeof y.imageSrcSet=="string"?y.imageSrcSet:void 0,imageSizes:typeof y.imageSizes=="string"?y.imageSizes:void 0,media:typeof y.media=="string"?y.media:void 0})}},yt.preloadModule=function(x,y){if(typeof x=="string")if(y){var j=v(y.as,y.crossOrigin);r.d.m(x,{as:typeof y.as=="string"&&y.as!=="script"?y.as:void 0,crossOrigin:j,integrity:typeof y.integrity=="string"?y.integrity:void 0})}else r.d.m(x)},yt.requestFormReset=function(x){r.d.r(x)},yt.unstable_batchedUpdates=function(x,y){return x(y)},yt.useFormState=function(x,y,j){return m.H.useFormState(x,y,j)},yt.useFormStatus=function(){return m.H.useHostTransitionStatus()},yt.version="19.2.8",yt}var wm;function o0(){if(wm)return Kr.exports;wm=1;function l(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(c){console.error(c)}}return l(),Kr.exports=r0(),Kr.exports}var Tm;function d0(){if(Tm)return Yi;Tm=1;var l=u0(),c=Lo(),o=o0();function r(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function d(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function f(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function m(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function v(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function x(e){if(f(e)!==e)throw Error(r(188))}function y(e){var t=e.alternate;if(!t){if(t=f(e),t===null)throw Error(r(188));return t!==e?null:e}for(var n=e,a=t;;){var s=n.return;if(s===null)break;var u=s.alternate;if(u===null){if(a=s.return,a!==null){n=a;continue}break}if(s.child===u.child){for(u=s.child;u;){if(u===n)return x(s),e;if(u===a)return x(s),t;u=u.sibling}throw Error(r(188))}if(n.return!==a.return)n=s,a=u;else{for(var h=!1,b=s.child;b;){if(b===n){h=!0,n=s,a=u;break}if(b===a){h=!0,a=s,n=u;break}b=b.sibling}if(!h){for(b=u.child;b;){if(b===n){h=!0,n=u,a=s;break}if(b===a){h=!0,a=u,n=s;break}b=b.sibling}if(!h)throw Error(r(189))}}if(n.alternate!==a)throw Error(r(190))}if(n.tag!==3)throw Error(r(188));return n.stateNode.current===n?e:t}function j(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=j(e),t!==null)return t;e=e.sibling}return null}var g=Object.assign,S=Symbol.for("react.element"),N=Symbol.for("react.transitional.element"),R=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),J=Symbol.for("react.profiler"),Z=Symbol.for("react.consumer"),F=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),ge=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),V=Symbol.for("react.memo"),le=Symbol.for("react.lazy"),W=Symbol.for("react.activity"),Y=Symbol.for("react.memo_cache_sentinel"),ne=Symbol.iterator;function ae(e){return e===null||typeof e!="object"?null:(e=ne&&e[ne]||e["@@iterator"],typeof e=="function"?e:null)}var Q=Symbol.for("react.client.reference");function se(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Q?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case L:return"Fragment";case J:return"Profiler";case P:return"StrictMode";case ge:return"Suspense";case ee:return"SuspenseList";case W:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case R:return"Portal";case F:return e.displayName||"Context";case Z:return(e._context.displayName||"Context")+".Consumer";case _:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case V:return t=e.displayName||null,t!==null?t:se(e.type)||"Memo";case le:t=e._payload,e=e._init;try{return se(e(t))}catch{}}return null}var re=Array.isArray,D=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te=o.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,G={pending:!1,data:null,method:null,action:null},Ae=[],Ce=-1;function C(e){return{current:e}}function q(e){0>Ce||(e.current=Ae[Ce],Ae[Ce]=null,Ce--)}function I(e,t){Ce++,Ae[Ce]=e.current,e.current=t}var ie=C(null),me=C(null),be=C(null),ye=C(null);function ze(e,t){switch(I(be,t),I(me,e),I(ie,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?qh(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=qh(t),e=$h(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}q(ie),I(ie,e)}function oe(){q(ie),q(me),q(be)}function Wt(e){e.memoizedState!==null&&I(ye,e);var t=ie.current,n=$h(t,e.type);t!==n&&(I(me,e),I(ie,n))}function Ea(e){me.current===e&&(q(ie),q(me)),ye.current===e&&(q(ye),Hi._currentValue=G)}var Qn,Vl;function St(e){if(Qn===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\\n( *(at )?)/);Qn=t&&t[1]||"",Vl=-1<n.stack.indexOf(\`
8
+ `))}catch{A()}},s.heartbeatMs??Wn),p.unref?.()},cancel(){if(b)return;if(b=!0,p!==void 0)clearInterval(p);d?.(),d=void 0}});return new Response(w,{status:s.status??200,headers:{"content-type":"text/event-stream; charset=utf-8","cache-control":"no-cache, no-transform",connection:"keep-alive","x-accel-buffering":"no"}})}var be=512;function Se(s,e){return`${s.toString(8).padStart(e-1,"0")}\x00`}function Fe(s,e,d,p){let b=new Uint8Array(be),w=(A,U)=>{b.set(new TextEncoder().encode(A),U)};w(s.slice(0,100),0),w(Se(420,8),100),w(Se(0,8),108),w(Se(0,8),116),w(Se(e,12),124),w(Se(Math.floor(d/1000),12),136),w(" ",148),w(p,156),w("ustar\x00",257),w("00",263);let N=0;for(let A of b)N+=A;return w(`${N.toString(8).padStart(6,"0")}\x00 `,148),b}function Pt(s,e,d){if(new TextEncoder().encode(s).length<=100)return[Fe(s,e,d,"0")];let p=(N)=>`${N} path=${s}
9
+ `,b=p(0);for(let N=b.length;;N=b.length)if(b=p(new TextEncoder().encode(p(N)).length),new TextEncoder().encode(b).length===N)break;let w=new TextEncoder().encode(b);return[Fe("PaxHeader",w.length,d,"x"),...Vn(w),Fe(s,e,d,"0")]}function Vn(s){let e=s.length%be;return e===0?[s]:[s,new Uint8Array(be-e)]}async function*Dr(s,e){try{yield*Ur(s)}finally{await e()}}async function*Ur(s){for(let e of s){if("bytes"in e.source){yield*Pt(e.name,e.source.bytes.length,Date.now()),yield*Vn(e.source.bytes);continue}let d=await Mr(e.source.path);yield*Pt(e.name,d.size,d.mtimeMs);let p=0;if(d.size>0)for await(let b of Rr(e.source.path,{end:d.size-1})){let w=b;p+=w.length,yield w}if(p<d.size)yield new Uint8Array(d.size-p);if(d.size%be!==0)yield new Uint8Array(be-d.size%be)}yield new Uint8Array(be*2)}function Fr(s,e=async()=>{}){let d=_t.from(Dr(s,e)).pipe(Lr());return _t.toWeb(d)}var Kr=':root{color-scheme:dark;--ground: #0a0a0a;--raised: #111111;--raised-2: #171717;--line: #262626;--line-strong: #333333;--text: #ededed;--dim: #a1a1a1;--faint: #6b6b6b;--accent: #d75fd7;--accent-soft: rgb(215 95 215 / 12%);--accent-ink: #0a0a0a;--warn: #d7af5f;--warn-soft: rgb(215 175 95 / 10%);--bad: #f7768e;--bad-soft: rgb(247 118 142 / 10%);--ok: #5fd75f;--info: #5f87d7;--shadow: 0 1px 2px rgb(0 0 0 / 40%), 0 8px 24px rgb(0 0 0 / 25%);--radius: 8px;--mono: "JetBrains Mono", ui-monospace, SFMono-Regular, "SF Mono", Menlo, Consolas, monospace;--sans: Inter, ui-sans-serif, -apple-system, BlinkMacSystemFont, "Segoe UI", system-ui, sans-serif}@media(prefers-color-scheme:light){:root:not([data-theme=dark]){color-scheme:light;--ground: #fafafa;--raised: #ffffff;--raised-2: #f4f4f5;--line: #e5e5e5;--line-strong: #d4d4d4;--text: #171717;--dim: #616161;--faint: #9a9a9a;--accent: #b23fb2;--accent-soft: rgb(178 63 178 / 9%);--accent-ink: #ffffff;--warn: #9a6b12;--warn-soft: rgb(154 107 18 / 8%);--bad: #c62a4a;--bad-soft: rgb(198 42 74 / 7%);--ok: #1f8a3a;--info: #2f5fb3;--shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%)}}:root[data-theme=light]{color-scheme:light;--ground: #fafafa;--raised: #ffffff;--raised-2: #f4f4f5;--line: #e5e5e5;--line-strong: #d4d4d4;--text: #171717;--dim: #616161;--faint: #9a9a9a;--accent: #b23fb2;--accent-soft: rgb(178 63 178 / 9%);--accent-ink: #ffffff;--warn: #9a6b12;--warn-soft: rgb(154 107 18 / 8%);--bad: #c62a4a;--bad-soft: rgb(198 42 74 / 7%);--ok: #1f8a3a;--info: #2f5fb3;--shadow: 0 1px 2px rgb(0 0 0 / 6%), 0 8px 24px rgb(0 0 0 / 6%)}*{box-sizing:border-box}html,body{margin:0;background:var(--ground);color:var(--text)}body{font:14px / 1.55 var(--sans);-webkit-font-smoothing:antialiased;font-feature-settings:"cv11","ss01"}code{font-family:var(--mono);font-size:.88em;background:var(--raised-2);border:1px solid var(--line);border-radius:4px;padding:1px 5px}a{color:var(--accent);text-decoration:none}a:hover{text-decoration:underline}::selection{background:var(--accent-soft)}:focus-visible{outline:2px solid var(--accent);outline-offset:2px}button{font:inherit;font-size:13px;font-weight:500;color:inherit;background:var(--raised);border:1px solid var(--line);border-radius:6px;padding:6px 12px;cursor:pointer;transition:background .12s,border-color .12s,color .12s}button:hover:not(:disabled){border-color:var(--line-strong);background:var(--raised-2)}button:disabled{opacity:.45;cursor:default}button.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink);font-weight:600}button.primary:hover:not(:disabled){background:var(--accent);border-color:var(--accent);filter:brightness(1.08)}button.bad{color:var(--bad)}input,textarea,select{font:inherit;color:inherit;background:var(--ground);border:1px solid var(--line);border-radius:6px;padding:8px 10px;width:100%;transition:border-color .12s,box-shadow .12s}input:focus,textarea:focus,select:focus{outline:none;border-color:var(--accent);box-shadow:0 0 0 3px var(--accent-soft)}.shell{display:grid;grid-template-columns:248px 1fr;height:100vh}.side{background:var(--ground);border-right:1px solid var(--line);display:flex;flex-direction:column;min-height:0}.side header{padding:14px 16px;height:52px;display:flex;align-items:center;gap:10px;border-bottom:1px solid var(--line)}.brand{font-weight:700;letter-spacing:-.01em;font-size:15px;display:flex;align-items:center;gap:8px}.wordmark{display:block;color:var(--accent);width:auto}.version{font-family:var(--mono);font-size:11px;color:var(--faint)}.side nav{padding:8px 10px;overflow-y:auto;flex:1;min-height:0}.side footer{padding:10px 14px;border-top:1px solid var(--line);display:flex;gap:8px;align-items:center}.row-button{display:flex;align-items:center;gap:8px;width:100%;text-align:left;background:none;border:1px solid transparent;border-radius:6px;padding:6px 9px;font-size:13px;font-weight:450;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.row-button:hover:not(:disabled){background:var(--raised-2);border-color:transparent;color:var(--text)}.row-button[aria-current=true]{background:var(--raised-2);color:var(--text);border-color:var(--line)}.row-button.session{font-family:var(--mono);font-size:12px}.row-button.session.person{font-family:var(--sans)}.group{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.08em;color:var(--faint);padding:16px 9px 6px}.main{display:flex;flex-direction:column;min-height:0;min-width:0}.bar{display:flex;gap:12px;align-items:center;padding:0 20px;border-bottom:1px solid var(--line);font-size:12px;color:var(--dim);height:52px;flex-shrink:0;background:color-mix(in srgb,var(--ground) 85%,transparent);-webkit-backdrop-filter:blur(8px);backdrop-filter:blur(8px)}.bar strong{color:var(--text);font-size:14px;font-weight:600;white-space:nowrap}.bar .crumb{color:var(--faint)}.bar .spacer{flex:1}.bar a,.bar .ghost{color:var(--dim);font-size:12px;font-weight:500;padding:5px 10px;border:1px solid var(--line);border-radius:6px;background:transparent;white-space:nowrap}.bar a:hover,.bar .ghost:hover:not(:disabled){color:var(--text);text-decoration:none;background:var(--raised-2)}.scroll{flex:1;overflow-y:auto;min-height:0;padding:28px 24px}.pad{max-width:820px;margin:0 auto}.pad.wide{max-width:1100px}.page-head{margin:0 0 22px}.page-head h1{font-size:24px;font-weight:650;letter-spacing:-.02em;margin:0 0 4px}.page-head p{color:var(--dim);margin:0;max-width:68ch}.row{margin:0 0 18px;white-space:pre-wrap;overflow-wrap:anywhere}.row.user{background:var(--raised-2);border:1px solid var(--line);border-radius:12px;padding:10px 14px;margin-left:auto;max-width:85%;width:fit-content}.row.reply{white-space:normal}.row.reply>:first-child{margin-top:0}.row.reply>:last-child{margin-bottom:0}.row.reply p,.row.reply ul,.row.reply ol,.row.reply blockquote{margin:0 0 10px}.row.reply h1,.row.reply h2,.row.reply h3,.row.reply h4{margin:16px 0 8px;letter-spacing:-.01em;line-height:1.3}.row.reply h1{font-size:20px}.row.reply h2{font-size:17px}.row.reply h3,.row.reply h4{font-size:15px}.row.reply ul,.row.reply ol{padding-left:22px}.row.reply li>p{margin:0 0 4px}.row.reply blockquote{border-left:3px solid var(--line-strong);padding:2px 12px;color:var(--dim)}.row.reply hr{border:none;border-top:1px solid var(--line);margin:14px 0}.row.reply a{text-decoration:underline;text-underline-offset:2px}.md-code{margin:0 0 10px;border:1px solid var(--line);border-radius:var(--radius);background:var(--ground);overflow:hidden}.md-code.open{border-style:dashed}.md-code-head{display:flex;justify-content:space-between;align-items:center;padding:4px 6px 4px 12px;font-family:var(--mono);font-size:11px;color:var(--faint);border-bottom:1px solid var(--line);background:var(--raised)}.md-code-head button{font-size:11px;padding:2px 8px}.md-code pre{margin:0;padding:12px 14px;overflow-x:auto;font-family:var(--mono);font-size:12.5px;line-height:1.55}.md-code pre code{background:none;border:none;padding:0;font-size:inherit}.md-table{overflow-x:auto;margin:0 0 10px}.md-table table{width:auto;min-width:50%;border:1px solid var(--line);border-radius:var(--radius);border-collapse:separate;border-spacing:0}.md-table th{padding:8px 12px;background:var(--raised-2);text-transform:none;letter-spacing:0;font-size:12px;color:var(--text);border-bottom:1px solid var(--line)}.md-table td{padding:8px 12px;font-family:var(--sans);font-size:13px;border-top:1px solid var(--line)}.label{font-family:var(--mono);font-size:11px;color:var(--faint);margin-bottom:4px}.tool{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:8px 12px;font-family:var(--mono);font-size:12px}.tool .slug{color:var(--accent);font-weight:600}.tool .out{color:var(--dim);max-height:13em;overflow-y:auto;margin-top:5px;display:inline}.tool.failed{border-color:color-mix(in srgb,var(--bad) 40%,var(--line))}.tool.failed .slug{color:var(--bad)}.tool .mut{color:var(--warn);font-size:11px}.fence{border:1px dashed var(--warn);border-radius:6px;padding:7px 9px;margin-top:5px}.fence .why{color:var(--warn);font-size:11px;margin-bottom:4px}.payload-code{font-family:var(--mono);font-size:28px;font-weight:600;letter-spacing:.18em;margin:10px 0;-webkit-user-select:all;user-select:all}.channel-input.stale .payload-code{opacity:.35}.payload-qr{display:block;width:240px;max-width:100%;height:auto;border-radius:6px;margin:8px 0}.channel-input.stale .payload-qr{opacity:.35}.note{font-size:12px;color:var(--dim);border-left:2px solid var(--line-strong);padding:2px 0 2px 11px;white-space:pre-wrap}.note.bad{color:var(--bad);border-left-color:var(--bad);background:var(--bad-soft);border-radius:0 6px 6px 0;padding:8px 12px}.ask{border:1px solid color-mix(in srgb,var(--warn) 55%,var(--line));border-radius:var(--radius);padding:12px 14px;background:var(--warn-soft)}.ask .what{font-family:var(--mono);font-size:12px;margin:6px 0 10px;white-space:pre-wrap;overflow-wrap:anywhere}.ask .buttons{display:flex;gap:8px;flex-wrap:wrap}.ask .settled{font-size:12px;color:var(--dim)}details.fold summary{cursor:pointer;color:var(--faint);font-family:var(--mono);font-size:11px}details.fold[open] summary{margin-bottom:5px}details.fold .body{color:var(--dim);font-size:13px}.tool details.subagent{margin-top:4px}.tool details.subagent summary{cursor:pointer;color:var(--dim);font-size:11px}.tool details.subagent ul{list-style:none;margin:4px 0 0;padding-left:12px;border-left:1px solid var(--line);color:var(--dim)}.tool details.subagent li.failed .slug{color:var(--bad)}.composer{padding:12px 24px 18px}.composer .inner{max-width:820px;margin:0 auto;display:flex;gap:8px;align-items:flex-end;background:var(--raised);border:1px solid var(--line);border-radius:12px;padding:8px;box-shadow:var(--shadow)}.composer .inner:focus-within{border-color:color-mix(in srgb,var(--accent) 60%,var(--line))}.composer .role-pick{width:auto;font-family:var(--mono);font-size:12px;padding:6px 8px}.attachments{max-width:820px;margin:0 auto 8px;display:flex;gap:8px;flex-wrap:wrap}.attachment{position:relative;display:inline-block}.attachment img{height:56px;width:56px;object-fit:cover;border-radius:8px;border:1px solid var(--line);display:block}.attachment button{position:absolute;top:-6px;right:-6px;width:18px;height:18px;padding:0;line-height:1;font-size:12px;border-radius:50%}.composer textarea{resize:none;min-height:40px;max-height:190px;font-family:var(--sans);border:none;background:transparent;box-shadow:none}.composer textarea:focus{box-shadow:none}.hint{font-size:11px;color:var(--faint);max-width:820px;margin:6px auto 0}.card{border:1px solid var(--line);border-radius:var(--radius);padding:18px 20px;margin-bottom:14px;background:var(--raised)}.card h2{margin:0 0 4px;font-size:15px;font-weight:600}.card h3{margin:0 0 8px;font-size:13px;font-weight:600}.card p{margin:0 0 12px;color:var(--dim);font-size:13px}table{width:100%;border-collapse:collapse;font-size:13px}th{text-align:left;font-size:11px;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);font-weight:600;padding:0 10px 8px 0}td{padding:9px 10px 9px 0;border-top:1px solid var(--line);font-family:var(--mono);font-size:12px}td.revoked{color:var(--faint);text-decoration:line-through}.secret{font-family:var(--mono);font-size:12px;background:var(--ground);border:1px solid var(--ok);border-radius:6px;padding:9px 11px;overflow-wrap:anywhere;margin-bottom:8px}.gate{display:grid;place-items:center;min-height:100vh;padding:20px;background:radial-gradient(ellipse 60% 40% at 50% 0%,var(--accent-soft),transparent 70%),var(--ground)}.gate .card{max-width:440px;width:100%;padding:28px;box-shadow:var(--shadow)}.gate .card h2{font-size:18px;letter-spacing:-.01em;margin-bottom:6px}.gate .brand{margin-bottom:18px}.gate input{font-family:var(--mono);font-size:12px}.gate .ask{border:none;background:none;padding:0}.dot{width:7px;height:7px;border-radius:50%;display:inline-block;flex-shrink:0;background:var(--faint)}.dot.live{background:var(--ok);box-shadow:0 0 0 3px color-mix(in srgb,var(--ok) 18%,transparent)}.dot.busy{background:var(--warn);box-shadow:0 0 0 3px color-mix(in srgb,var(--warn) 18%,transparent)}.dot.off{background:var(--faint)}.dot.warn{background:var(--warn)}@media(max-width:720px){.shell{grid-template-columns:minmax(0,1fr);grid-template-rows:auto minmax(0,1fr);height:100dvh}.side{min-width:0;border-right:none;border-bottom:1px solid var(--line)}.side header{height:48px}.side nav{display:flex;gap:4px;overflow-x:auto;padding:6px 10px;flex:none}.side nav .group,.side nav .agent-note,.side footer{display:none}.side nav .row-button,.side nav .agent-row{width:auto;flex-shrink:0}.bar{padding:0 14px;height:48px}.bar .hide-narrow{display:none}.scroll{padding:18px 16px}.composer{padding:10px 12px 12px}}.agent-row{display:block}.agent-row .row-button:disabled{color:var(--faint);cursor:default}.agent-off{color:var(--warn);font-size:11px}.agent-note{display:flex;gap:6px;align-items:baseline;padding:0 9px 6px 24px;font-size:11px;color:var(--faint)}.link{background:none;border:none;padding:0;color:var(--accent);font-size:11px;text-decoration:underline;cursor:pointer}.link:hover:not(:disabled){background:none}.link:disabled{color:var(--faint);cursor:default;text-decoration:none}.empty{color:var(--dim);font-size:13px;max-width:60ch}.empty-state{border:1px dashed var(--line-strong);border-radius:var(--radius);padding:28px;text-align:center;color:var(--dim)}.empty-state h3{color:var(--text);margin:0 0 6px;font-size:14px}.empty-state p{margin:0 auto;max-width:56ch;font-size:13px}.panel-table{width:100%;border-collapse:separate;border-spacing:0;font-size:12px;border:1px solid var(--line);border-radius:var(--radius);overflow:hidden;background:var(--raised)}.panel-table th{text-align:left;font-weight:600;font-size:11px;text-transform:uppercase;letter-spacing:.06em;color:var(--faint);padding:10px 12px;border-bottom:1px solid var(--line);background:var(--raised-2)}.panel-table td{padding:10px 12px;border-top:none;border-bottom:1px solid var(--line);vertical-align:top}.panel-table tr:last-child td{border-bottom:none}.panel-table tr:hover td{background:var(--raised-2)}.panel-table tr.off td{color:var(--faint)}.channel{border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;margin-bottom:12px;background:var(--raised)}.channel h3{margin:0 0 6px;font-size:13px;font-weight:600}.status{margin:0;font-size:12px}.status-connected{color:var(--ok)}.status-error,.status-disconnected{color:var(--bad)}.status-needs_input{color:var(--warn)}.channel-input{margin-top:10px;padding:10px;border-radius:6px;background:var(--ground)}.payload{margin:0;font-family:var(--mono);font-size:11px;white-space:pre-wrap;word-break:break-all;max-height:9em;overflow-y:auto}.channel-input.stale .payload{opacity:.45}.warn{color:var(--warn);font-size:12px;margin:0 0 6px}.provision{display:flex;flex-direction:column;gap:16px;max-width:60ch}.provision>button[type=submit]{align-self:flex-start}.field label{display:block;font-size:12px;font-weight:500;color:var(--dim);margin-bottom:6px}.field.invalid input,.field.invalid select{border-color:var(--bad)}.sub{color:var(--dim);font-size:12px;margin-top:2px;max-width:60ch}.error{color:var(--bad);font-size:13px;max-width:60ch}.ok{color:var(--ok);font-size:13px}.created{max-width:66ch;font-size:13px}.created h3{font-size:15px;font-weight:600;margin:0 0 10px}.created p{margin:0 0 10px}.blank-secrets{border:1px solid var(--warn);border-radius:6px;padding:11px 13px;margin:14px 0}.blank-secrets p{margin:0 0 6px}.blank-secrets p:last-child{margin:0}.config-row{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px;margin-bottom:10px}.config-head{display:flex;align-items:baseline;gap:8px;font-family:var(--mono);font-size:13px;font-weight:600}.config-row .sub{margin:4px 0 10px;max-width:72ch}.config-row input[type=text],.config-row input:not([type]),.config-row textarea{width:100%;font-family:var(--mono);font-size:12px}.config-row button{margin-top:8px}.config-row label input[type=checkbox]{width:auto;margin-right:4px;vertical-align:baseline}.form-grid{display:grid;grid-template-columns:6em 1fr;gap:8px 12px;align-items:start;max-width:60ch}.form-grid label{font-size:12px;color:var(--dim);padding-top:9px}.form-grid input,.form-grid select{width:100%}.form-grid>div>input+input{margin-top:6px}.warnings{border:1px solid color-mix(in srgb,var(--warn) 45%,var(--line));background:var(--warn-soft);border-radius:var(--radius);padding:10px 14px;margin-bottom:20px;font-size:13px}.warnings summary{cursor:pointer;list-style:none;display:flex;gap:8px;align-items:center}.warnings summary::-webkit-details-marker{display:none}.warnings h3{margin:0;color:var(--warn);font-size:13px;font-weight:600}.warnings .sub{margin:8px 0 4px}.warning{margin-top:10px;padding-top:10px;border-top:1px solid color-mix(in srgb,var(--warn) 20%,transparent)}.warning-message{margin:0}.warning .hint{margin:4px 0 0;max-width:none}.channel-actions{display:flex;flex-wrap:wrap;gap:.5rem;align-items:center;margin-top:.5rem}.channel-actions form{display:flex;gap:.35rem}.channel-actions input{min-width:14rem}.status-off{opacity:.7}.model-card.primary{border-color:color-mix(in srgb,var(--accent) 35%,var(--line))}.model-head{display:flex;align-items:center;gap:12px;flex-wrap:wrap;margin-bottom:18px}.model-role{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint)}.model-id{font-family:var(--mono);font-size:16px;font-weight:600;overflow-wrap:anywhere}.control{margin-bottom:16px;min-width:0}.control-label{display:flex;flex-wrap:wrap;align-items:baseline;gap:8px;font-size:13px;font-weight:600;margin-bottom:8px}.control-label .sub{font-weight:400;margin:0;flex-basis:100%}.mono-value{font-family:var(--mono);font-size:12px;color:var(--accent);margin-left:auto}.control-row{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:0 24px}.inline{display:flex;gap:8px;align-items:center}input[type=range]{accent-color:var(--accent);padding:0;border:none;background:none;box-shadow:none}.segmented{margin:0;min-width:0;display:inline-flex;flex-wrap:wrap;gap:2px;padding:3px;background:var(--ground);border:1px solid var(--line);border-radius:8px}.segmented button{border:1px solid transparent;background:none;padding:4px 11px;font-size:12px;color:var(--dim);border-radius:6px}.segmented button:hover:not(:disabled){background:var(--raised-2);border-color:transparent;color:var(--text)}.segmented button[aria-pressed=true]{background:var(--accent-soft);border-color:color-mix(in srgb,var(--accent) 45%,var(--line));color:var(--accent);font-weight:600}.model-foot{display:flex;align-items:center;gap:10px;flex-wrap:wrap;border-top:1px solid var(--line);padding-top:12px}.model-form{display:grid;grid-template-columns:repeat(auto-fit,minmax(240px,1fr));gap:12px 16px;margin-top:14px;padding-top:14px;border-top:1px solid var(--line)}.model-form label{display:flex;flex-direction:column;gap:6px;font-size:12px;font-weight:500;color:var(--dim)}.model-form label .sub,.model-form label .error{font-size:11px;margin:0}.grid{display:grid;grid-template-columns:repeat(auto-fill,minmax(280px,1fr));gap:14px}.agent-card{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:16px 18px;display:flex;flex-direction:column;gap:12px;text-align:left;transition:border-color .12s,transform .12s}button.agent-card{font-size:13px;font-weight:400;width:100%}button.agent-card:hover:not(:disabled){border-color:color-mix(in srgb,var(--accent) 50%,var(--line));background:var(--raised)}.agent-card.off{opacity:.75}.agent-card .head{display:flex;align-items:center;gap:10px}.agent-card .name{font-weight:600;font-size:15px;letter-spacing:-.01em}.agent-card .id{font-family:var(--mono);font-size:11px;color:var(--faint)}.agent-card .model{font-family:var(--mono);font-size:12px;color:var(--dim);overflow:hidden;text-overflow:ellipsis;white-space:nowrap}.stats{display:flex;flex-wrap:wrap;gap:6px}.pill{display:inline-flex;align-items:center;gap:5px;border:1px solid var(--line);border-radius:999px;padding:2px 9px;font-size:11px;font-weight:500;color:var(--dim);background:var(--ground);white-space:nowrap}.pill.accent{color:var(--accent);border-color:color-mix(in srgb,var(--accent) 35%,var(--line));background:var(--accent-soft)}.pill.ok{color:var(--ok)}.pill.warn{color:var(--warn);border-color:color-mix(in srgb,var(--warn) 35%,var(--line))}.pill.bad{color:var(--bad);border-color:color-mix(in srgb,var(--bad) 40%,var(--line));background:var(--bad-soft)}.error-line{color:var(--bad);font-size:12px;margin-top:4px;overflow-wrap:anywhere}.member{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px}.member .head{display:flex;align-items:center;gap:10px;margin-bottom:8px}.avatar{width:28px;height:28px;border-radius:7px;display:grid;place-items:center;font-weight:700;font-size:12px;color:var(--accent);background:var(--accent-soft);border:1px solid color-mix(in srgb,var(--accent) 30%,var(--line));flex-shrink:0;text-transform:uppercase}.member .task{color:var(--dim);font-size:13px;margin:0 0 10px}.lead{display:flex;align-items:center;gap:12px;border:1px solid color-mix(in srgb,var(--accent) 35%,var(--line));background:var(--accent-soft);border-radius:var(--radius);padding:14px 16px;margin-bottom:14px}.section-title{font-size:12px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);margin:28px 0 10px}pre.snippet{position:relative;margin:0;background:var(--ground);border:1px solid var(--line);border-radius:var(--radius);padding:14px 16px;font-family:var(--mono);font-size:12px;line-height:1.6;overflow-x:auto;white-space:pre}.snippet-head{display:flex;align-items:center;justify-content:space-between;gap:10px;margin-bottom:8px}.snippet-head h3{margin:0;font-size:13px;font-weight:600}.snippet-head button{font-size:11px;padding:3px 9px}.method{font-family:var(--mono);font-size:10px;font-weight:700;letter-spacing:.04em;padding:2px 6px;border-radius:4px;color:var(--accent-ink);background:var(--accent)}.method.get{background:var(--info);color:#fff}.endpoints{display:grid;gap:6px}.endpoint{display:flex;align-items:center;gap:10px;font-size:13px;padding:8px 12px;border:1px solid var(--line);border-radius:6px;background:var(--raised)}.endpoint code{background:none;border:none;padding:0;font-size:12px}.endpoint .what{color:var(--dim);margin-left:auto;font-size:12px;text-align:right}.cta-row{display:flex;gap:10px;flex-wrap:wrap}.cta-row a{display:inline-flex;align-items:center;gap:6px;padding:7px 14px;border:1px solid var(--line);border-radius:6px;font-size:13px;font-weight:500;color:var(--text);background:var(--raised)}.cta-row a.primary{background:var(--accent);border-color:var(--accent);color:var(--accent-ink)}.cta-row a:hover{text-decoration:none;filter:brightness(1.08)}.fallbacks{margin:0 0 10px;padding-left:22px;display:grid;gap:6px}.fallbacks li{display:flex;align-items:center;gap:10px;font-size:13px}.schedule-card .head{display:flex;align-items:center;gap:8px;flex-wrap:wrap;margin-bottom:8px}.schedule-id{font-size:13px;font-weight:600}.schedule-card .task{margin:0 0 12px;color:var(--text)}.schedule-card.off .task{color:var(--dim)}.facts{display:grid;grid-template-columns:max-content 1fr;gap:4px 12px;margin:0 0 12px;font-size:12px}.facts dt{color:var(--faint);text-transform:uppercase;letter-spacing:.06em;font-size:10px;padding-top:2px}.facts dd{margin:0;overflow-wrap:anywhere}.schedule-card .actions{display:flex;gap:8px;flex-wrap:wrap;align-items:center;border-top:1px solid var(--line);padding-top:10px}.schedule-form{margin-top:18px}.schedule-form h3{margin-bottom:14px}.chips{display:flex;flex-wrap:wrap;gap:6px;margin-top:6px}.chips .pill{cursor:pointer}.chips .pill:hover{color:var(--text);border-color:var(--line-strong)}.preview{display:block;margin-top:6px}.preview.bad{color:var(--bad)}.model-form textarea{resize:vertical;font-family:var(--sans)}.model-form .field-like{display:flex;flex-direction:column;gap:6px;font-size:12px;font-weight:500;color:var(--dim)}.search{margin-bottom:14px;max-width:420px}.tool-group{margin-bottom:18px}.tool-group h3{font-size:13px;font-weight:600;margin:0 0 8px;display:flex;align-items:baseline;gap:8px}.tool-group h3 .sub{margin:0}.rules{list-style:none;margin:0 0 10px;padding:0;display:grid;gap:6px}.rules li{display:flex;align-items:center;gap:10px;font-size:13px}.refresh-report ul{margin:0 0 8px;padding-left:18px;font-size:13px}:root{--chart: #c955c9}@media(prefers-color-scheme:light){:root:not([data-theme=dark]){--chart: #b23fb2}}:root[data-theme=light]{--chart: #b23fb2}.tiles{display:grid;grid-template-columns:repeat(auto-fit,minmax(160px,1fr));gap:12px;margin-bottom:8px}.tile{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:14px 16px}.tile-label{font-size:11px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint)}.tile-value{font-size:24px;font-weight:650;letter-spacing:-.02em;font-variant-numeric:tabular-nums;margin:4px 0 2px}.chart{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);padding:12px 12px 6px;margin-bottom:18px}.chart svg{display:block;width:100%;height:auto}.chart .bar{fill:var(--chart)}.chart .bar.hot{fill:var(--accent)}.chart .axis{stroke:var(--line-strong);stroke-width:1}.chart .value{fill:var(--dim);font-size:10px;font-family:var(--mono)}.chart .tick{fill:var(--faint);font-size:10px;font-family:var(--mono)}.chart .tooltip{min-height:1.6em;font-size:12px;color:var(--dim);font-family:var(--mono);padding:4px 2px 0}.turns{display:grid;gap:8px}.turn{padding:0;margin:0;overflow:hidden}.turn.bad{border-color:color-mix(in srgb,var(--warn) 40%,var(--line))}.turn-head{width:100%;display:flex;align-items:center;gap:12px;text-align:left;background:none;border:none;border-radius:0;padding:12px 16px;font-weight:400}.turn-head:hover:not(:disabled){background:var(--raised-2);border-color:transparent}.turn-input{flex:1;min-width:0;overflow:hidden;text-overflow:ellipsis;white-space:nowrap;font-size:13px}.turn-meta{display:flex;gap:12px;font-family:var(--mono);font-size:11px;color:var(--faint);white-space:nowrap}.turn-body{border-top:1px solid var(--line);padding:14px 16px 16px}.turn-body .facts{margin-bottom:14px}@media(max-width:720px){.turn-meta{display:none}}.person .head,.card>.head{display:flex;align-items:center;gap:10px;margin-bottom:10px}.person .name{font-weight:600}.person .id{font-family:var(--mono);font-size:11px;color:var(--faint)}.person{display:flex;flex-direction:column;gap:12px}.facts-label{font-size:10px;font-weight:600;text-transform:uppercase;letter-spacing:.07em;color:var(--faint);margin-bottom:6px}.check{display:inline-flex;align-items:center;gap:6px;font-size:13px;cursor:pointer}.check input{width:auto}.members{display:flex;flex-wrap:wrap;gap:10px 16px}.rooms-layout{display:grid;grid-template-columns:260px minmax(0,1fr);gap:18px}.rooms-list .row-button{margin-bottom:2px}.rooms-main{border:1px solid var(--line);border-radius:var(--radius);background:var(--raised);display:flex;flex-direction:column;min-height:420px}.rooms-main .empty-state{border:none;margin:auto}.room-head{padding:12px 16px;border-bottom:1px solid var(--line);display:flex;flex-direction:column;gap:8px}.room-log{flex:1;padding:14px 16px;overflow-y:auto;display:grid;gap:12px;align-content:start}.room-msg{font-size:13px}.room-msg.agent{border-left:2px solid var(--accent);padding-left:12px}.room-post{border-top:1px solid var(--line);padding:12px 16px}.notes{display:grid;gap:8px}.note-card{margin:0;padding:12px 14px}@media(max-width:720px){.rooms-layout{grid-template-columns:minmax(0,1fr)}}.editor{flex:1;min-height:420px;border:none;border-radius:0;background:var(--ground);font-family:var(--mono);font-size:12.5px;line-height:1.6;padding:14px 16px;resize:vertical}.editor:focus{box-shadow:none}.model-form label.check,label.check{flex-direction:row;align-items:center;font-weight:400;color:var(--text)}.inline-field{display:inline-flex;align-items:center;gap:6px;white-space:nowrap;font-size:12px;color:var(--dim)}.room-skip{margin-top:6px;font-size:12px;color:var(--warn)}.tool-detail{margin-top:6px}.tool-detail-summary{cursor:pointer;color:var(--dim);font-size:12px}.tool-detail pre{max-height:320px;overflow:auto}.replay{list-style:none;padding:0;margin:12px 0 0;display:grid;gap:10px}.replay pre,.tool-detail pre{max-width:100%;box-sizing:border-box;white-space:pre-wrap;overflow-wrap:anywhere}.replay pre{max-height:280px;overflow:auto;margin:4px 0 0}.palette-layer{position:fixed;inset:0;z-index:50;display:flex;justify-content:center;align-items:flex-start;padding:12vh 16px 16px}button.palette-backdrop,button.palette-backdrop:hover:not(:disabled){position:absolute;inset:0;border:none;border-radius:0;background:#00000059;cursor:default}.palette{position:relative;width:min(560px,100%);background:var(--raised);border:1px solid var(--line);border-radius:12px;box-shadow:0 16px 48px #0000004d;overflow:hidden}.palette input{width:100%;border:none;border-bottom:1px solid var(--line);border-radius:0;padding:14px 16px;font-size:15px;background:transparent}.palette-list{list-style:none;margin:0;padding:6px;max-height:50vh;overflow:auto}.palette-item{width:100%;display:flex;justify-content:space-between;gap:12px;padding:8px 10px;border:none;border-radius:8px;background:transparent;text-align:left}.palette-item[aria-current=true]{background:var(--raised-2)}.palette .sub{margin:0}.palette .empty{padding:16px}.caps-row{display:flex;align-items:center;gap:10px;flex-wrap:wrap;margin:0}.caps-row .mono-value{margin:0;min-width:80px}.caps-row select,.caps-row input{width:auto}\n',Hr=`(function(){const c=document.createElement("link").relList;if(c&&c.supports&&c.supports("modulepreload"))return;for(const d of document.querySelectorAll('link[rel="modulepreload"]'))r(d);new MutationObserver(d=>{for(const f of d)if(f.type==="childList")for(const m of f.addedNodes)m.tagName==="LINK"&&m.rel==="modulepreload"&&r(m)}).observe(document,{childList:!0,subtree:!0});function o(d){const f={};return d.integrity&&(f.integrity=d.integrity),d.referrerPolicy&&(f.referrerPolicy=d.referrerPolicy),d.crossOrigin==="use-credentials"?f.credentials="include":d.crossOrigin==="anonymous"?f.credentials="omit":f.credentials="same-origin",f}function r(d){if(d.ep)return;d.ep=!0;const f=o(d);fetch(d.href,f)}})();function a0(l){return l&&l.__esModule&&Object.prototype.hasOwnProperty.call(l,"default")?l.default:l}var Br={exports:{}},Gi={};var ym;function l0(){if(ym)return Gi;ym=1;var l=Symbol.for("react.transitional.element"),c=Symbol.for("react.fragment");function o(r,d,f){var m=null;if(f!==void 0&&(m=""+f),d.key!==void 0&&(m=""+d.key),"key"in d){f={};for(var v in d)v!=="key"&&(f[v]=d[v])}else f=d;return d=f.ref,{$$typeof:l,type:r,key:m,ref:d!==void 0?d:null,props:f}}return Gi.Fragment=c,Gi.jsx=o,Gi.jsxs=o,Gi}var bm;function i0(){return bm||(bm=1,Br.exports=l0()),Br.exports}var i=i0(),Lr={exports:{}},ve={};var pm;function s0(){if(pm)return ve;pm=1;var l=Symbol.for("react.transitional.element"),c=Symbol.for("react.portal"),o=Symbol.for("react.fragment"),r=Symbol.for("react.strict_mode"),d=Symbol.for("react.profiler"),f=Symbol.for("react.consumer"),m=Symbol.for("react.context"),v=Symbol.for("react.forward_ref"),x=Symbol.for("react.suspense"),y=Symbol.for("react.memo"),j=Symbol.for("react.lazy"),g=Symbol.for("react.activity"),S=Symbol.iterator;function N(C){return C===null||typeof C!="object"?null:(C=S&&C[S]||C["@@iterator"],typeof C=="function"?C:null)}var R={isMounted:function(){return!1},enqueueForceUpdate:function(){},enqueueReplaceState:function(){},enqueueSetState:function(){}},L=Object.assign,P={};function J(C,q,I){this.props=C,this.context=q,this.refs=P,this.updater=I||R}J.prototype.isReactComponent={},J.prototype.setState=function(C,q){if(typeof C!="object"&&typeof C!="function"&&C!=null)throw Error("takes an object of state variables to update or a function which returns an object of state variables.");this.updater.enqueueSetState(this,C,q,"setState")},J.prototype.forceUpdate=function(C){this.updater.enqueueForceUpdate(this,C,"forceUpdate")};function Z(){}Z.prototype=J.prototype;function F(C,q,I){this.props=C,this.context=q,this.refs=P,this.updater=I||R}var _=F.prototype=new Z;_.constructor=F,L(_,J.prototype),_.isPureReactComponent=!0;var ge=Array.isArray;function ee(){}var V={H:null,A:null,T:null,S:null},le=Object.prototype.hasOwnProperty;function W(C,q,I){var ie=I.ref;return{$$typeof:l,type:C,key:q,ref:ie!==void 0?ie:null,props:I}}function Y(C,q){return W(C.type,q,C.props)}function ne(C){return typeof C=="object"&&C!==null&&C.$$typeof===l}function ae(C){var q={"=":"=0",":":"=2"};return"$"+C.replace(/[=:]/g,function(I){return q[I]})}var Q=/\\/+/g;function se(C,q){return typeof C=="object"&&C!==null&&C.key!=null?ae(""+C.key):q.toString(36)}function re(C){switch(C.status){case"fulfilled":return C.value;case"rejected":throw C.reason;default:switch(typeof C.status=="string"?C.then(ee,ee):(C.status="pending",C.then(function(q){C.status==="pending"&&(C.status="fulfilled",C.value=q)},function(q){C.status==="pending"&&(C.status="rejected",C.reason=q)})),C.status){case"fulfilled":return C.value;case"rejected":throw C.reason}}throw C}function D(C,q,I,ie,me){var be=typeof C;(be==="undefined"||be==="boolean")&&(C=null);var ye=!1;if(C===null)ye=!0;else switch(be){case"bigint":case"string":case"number":ye=!0;break;case"object":switch(C.$$typeof){case l:case c:ye=!0;break;case j:return ye=C._init,D(ye(C._payload),q,I,ie,me)}}if(ye)return me=me(C),ye=ie===""?"."+se(C,0):ie,ge(me)?(I="",ye!=null&&(I=ye.replace(Q,"$&/")+"/"),D(me,q,I,"",function(Wt){return Wt})):me!=null&&(ne(me)&&(me=Y(me,I+(me.key==null||C&&C.key===me.key?"":(""+me.key).replace(Q,"$&/")+"/")+ye)),q.push(me)),1;ye=0;var ze=ie===""?".":ie+":";if(ge(C))for(var oe=0;oe<C.length;oe++)ie=C[oe],be=ze+se(ie,oe),ye+=D(ie,q,I,be,me);else if(oe=N(C),typeof oe=="function")for(C=oe.call(C),oe=0;!(ie=C.next()).done;)ie=ie.value,be=ze+se(ie,oe++),ye+=D(ie,q,I,be,me);else if(be==="object"){if(typeof C.then=="function")return D(re(C),q,I,ie,me);throw q=String(C),Error("Objects are not valid as a React child (found: "+(q==="[object Object]"?"object with keys {"+Object.keys(C).join(", ")+"}":q)+"). If you meant to render a collection of children, use an array instead.")}return ye}function te(C,q,I){if(C==null)return C;var ie=[],me=0;return D(C,ie,"","",function(be){return q.call(I,be,me++)}),ie}function G(C){if(C._status===-1){var q=C._result;q=q(),q.then(function(I){(C._status===0||C._status===-1)&&(C._status=1,C._result=I)},function(I){(C._status===0||C._status===-1)&&(C._status=2,C._result=I)}),C._status===-1&&(C._status=0,C._result=q)}if(C._status===1)return C._result.default;throw C._result}var Ae=typeof reportError=="function"?reportError:function(C){if(typeof window=="object"&&typeof window.ErrorEvent=="function"){var q=new window.ErrorEvent("error",{bubbles:!0,cancelable:!0,message:typeof C=="object"&&C!==null&&typeof C.message=="string"?String(C.message):String(C),error:C});if(!window.dispatchEvent(q))return}else if(typeof process=="object"&&typeof process.emit=="function"){process.emit("uncaughtException",C);return}console.error(C)},Ce={map:te,forEach:function(C,q,I){te(C,function(){q.apply(this,arguments)},I)},count:function(C){var q=0;return te(C,function(){q++}),q},toArray:function(C){return te(C,function(q){return q})||[]},only:function(C){if(!ne(C))throw Error("React.Children.only expected to receive a single React element child.");return C}};return ve.Activity=g,ve.Children=Ce,ve.Component=J,ve.Fragment=o,ve.Profiler=d,ve.PureComponent=F,ve.StrictMode=r,ve.Suspense=x,ve.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=V,ve.__COMPILER_RUNTIME={__proto__:null,c:function(C){return V.H.useMemoCache(C)}},ve.cache=function(C){return function(){return C.apply(null,arguments)}},ve.cacheSignal=function(){return null},ve.cloneElement=function(C,q,I){if(C==null)throw Error("The argument must be a React element, but you passed "+C+".");var ie=L({},C.props),me=C.key;if(q!=null)for(be in q.key!==void 0&&(me=""+q.key),q)!le.call(q,be)||be==="key"||be==="__self"||be==="__source"||be==="ref"&&q.ref===void 0||(ie[be]=q[be]);var be=arguments.length-2;if(be===1)ie.children=I;else if(1<be){for(var ye=Array(be),ze=0;ze<be;ze++)ye[ze]=arguments[ze+2];ie.children=ye}return W(C.type,me,ie)},ve.createContext=function(C){return C={$$typeof:m,_currentValue:C,_currentValue2:C,_threadCount:0,Provider:null,Consumer:null},C.Provider=C,C.Consumer={$$typeof:f,_context:C},C},ve.createElement=function(C,q,I){var ie,me={},be=null;if(q!=null)for(ie in q.key!==void 0&&(be=""+q.key),q)le.call(q,ie)&&ie!=="key"&&ie!=="__self"&&ie!=="__source"&&(me[ie]=q[ie]);var ye=arguments.length-2;if(ye===1)me.children=I;else if(1<ye){for(var ze=Array(ye),oe=0;oe<ye;oe++)ze[oe]=arguments[oe+2];me.children=ze}if(C&&C.defaultProps)for(ie in ye=C.defaultProps,ye)me[ie]===void 0&&(me[ie]=ye[ie]);return W(C,be,me)},ve.createRef=function(){return{current:null}},ve.forwardRef=function(C){return{$$typeof:v,render:C}},ve.isValidElement=ne,ve.lazy=function(C){return{$$typeof:j,_payload:{_status:-1,_result:C},_init:G}},ve.memo=function(C,q){return{$$typeof:y,type:C,compare:q===void 0?null:q}},ve.startTransition=function(C){var q=V.T,I={};V.T=I;try{var ie=C(),me=V.S;me!==null&&me(I,ie),typeof ie=="object"&&ie!==null&&typeof ie.then=="function"&&ie.then(ee,Ae)}catch(be){Ae(be)}finally{q!==null&&I.types!==null&&(q.types=I.types),V.T=q}},ve.unstable_useCacheRefresh=function(){return V.H.useCacheRefresh()},ve.use=function(C){return V.H.use(C)},ve.useActionState=function(C,q,I){return V.H.useActionState(C,q,I)},ve.useCallback=function(C,q){return V.H.useCallback(C,q)},ve.useContext=function(C){return V.H.useContext(C)},ve.useDebugValue=function(){},ve.useDeferredValue=function(C,q){return V.H.useDeferredValue(C,q)},ve.useEffect=function(C,q){return V.H.useEffect(C,q)},ve.useEffectEvent=function(C){return V.H.useEffectEvent(C)},ve.useId=function(){return V.H.useId()},ve.useImperativeHandle=function(C,q,I){return V.H.useImperativeHandle(C,q,I)},ve.useInsertionEffect=function(C,q){return V.H.useInsertionEffect(C,q)},ve.useLayoutEffect=function(C,q){return V.H.useLayoutEffect(C,q)},ve.useMemo=function(C,q){return V.H.useMemo(C,q)},ve.useOptimistic=function(C,q){return V.H.useOptimistic(C,q)},ve.useReducer=function(C,q,I){return V.H.useReducer(C,q,I)},ve.useRef=function(C){return V.H.useRef(C)},ve.useState=function(C){return V.H.useState(C)},ve.useSyncExternalStore=function(C,q,I){return V.H.useSyncExternalStore(C,q,I)},ve.useTransition=function(){return V.H.useTransition()},ve.version="19.2.8",ve}var xm;function Lo(){return xm||(xm=1,Lr.exports=s0()),Lr.exports}var T=Lo(),Hr={exports:{}},Yi={},qr={exports:{}},$r={};var jm;function c0(){return jm||(jm=1,(function(l){function c(D,te){var G=D.length;D.push(te);e:for(;0<G;){var Ae=G-1>>>1,Ce=D[Ae];if(0<d(Ce,te))D[Ae]=te,D[G]=Ce,G=Ae;else break e}}function o(D){return D.length===0?null:D[0]}function r(D){if(D.length===0)return null;var te=D[0],G=D.pop();if(G!==te){D[0]=G;e:for(var Ae=0,Ce=D.length,C=Ce>>>1;Ae<C;){var q=2*(Ae+1)-1,I=D[q],ie=q+1,me=D[ie];if(0>d(I,G))ie<Ce&&0>d(me,I)?(D[Ae]=me,D[ie]=G,Ae=ie):(D[Ae]=I,D[q]=G,Ae=q);else if(ie<Ce&&0>d(me,G))D[Ae]=me,D[ie]=G,Ae=ie;else break e}}return te}function d(D,te){var G=D.sortIndex-te.sortIndex;return G!==0?G:D.id-te.id}if(l.unstable_now=void 0,typeof performance=="object"&&typeof performance.now=="function"){var f=performance;l.unstable_now=function(){return f.now()}}else{var m=Date,v=m.now();l.unstable_now=function(){return m.now()-v}}var x=[],y=[],j=1,g=null,S=3,N=!1,R=!1,L=!1,P=!1,J=typeof setTimeout=="function"?setTimeout:null,Z=typeof clearTimeout=="function"?clearTimeout:null,F=typeof setImmediate<"u"?setImmediate:null;function _(D){for(var te=o(y);te!==null;){if(te.callback===null)r(y);else if(te.startTime<=D)r(y),te.sortIndex=te.expirationTime,c(x,te);else break;te=o(y)}}function ge(D){if(L=!1,_(D),!R)if(o(x)!==null)R=!0,ee||(ee=!0,ae());else{var te=o(y);te!==null&&re(ge,te.startTime-D)}}var ee=!1,V=-1,le=5,W=-1;function Y(){return P?!0:!(l.unstable_now()-W<le)}function ne(){if(P=!1,ee){var D=l.unstable_now();W=D;var te=!0;try{e:{R=!1,L&&(L=!1,Z(V),V=-1),N=!0;var G=S;try{t:{for(_(D),g=o(x);g!==null&&!(g.expirationTime>D&&Y());){var Ae=g.callback;if(typeof Ae=="function"){g.callback=null,S=g.priorityLevel;var Ce=Ae(g.expirationTime<=D);if(D=l.unstable_now(),typeof Ce=="function"){g.callback=Ce,_(D),te=!0;break t}g===o(x)&&r(x),_(D)}else r(x);g=o(x)}if(g!==null)te=!0;else{var C=o(y);C!==null&&re(ge,C.startTime-D),te=!1}}break e}finally{g=null,S=G,N=!1}te=void 0}}finally{te?ae():ee=!1}}}var ae;if(typeof F=="function")ae=function(){F(ne)};else if(typeof MessageChannel<"u"){var Q=new MessageChannel,se=Q.port2;Q.port1.onmessage=ne,ae=function(){se.postMessage(null)}}else ae=function(){J(ne,0)};function re(D,te){V=J(function(){D(l.unstable_now())},te)}l.unstable_IdlePriority=5,l.unstable_ImmediatePriority=1,l.unstable_LowPriority=4,l.unstable_NormalPriority=3,l.unstable_Profiling=null,l.unstable_UserBlockingPriority=2,l.unstable_cancelCallback=function(D){D.callback=null},l.unstable_forceFrameRate=function(D){0>D||125<D?console.error("forceFrameRate takes a positive int between 0 and 125, forcing frame rates higher than 125 fps is not supported"):le=0<D?Math.floor(1e3/D):5},l.unstable_getCurrentPriorityLevel=function(){return S},l.unstable_next=function(D){switch(S){case 1:case 2:case 3:var te=3;break;default:te=S}var G=S;S=te;try{return D()}finally{S=G}},l.unstable_requestPaint=function(){P=!0},l.unstable_runWithPriority=function(D,te){switch(D){case 1:case 2:case 3:case 4:case 5:break;default:D=3}var G=S;S=D;try{return te()}finally{S=G}},l.unstable_scheduleCallback=function(D,te,G){var Ae=l.unstable_now();switch(typeof G=="object"&&G!==null?(G=G.delay,G=typeof G=="number"&&0<G?Ae+G:Ae):G=Ae,D){case 1:var Ce=-1;break;case 2:Ce=250;break;case 5:Ce=1073741823;break;case 4:Ce=1e4;break;default:Ce=5e3}return Ce=G+Ce,D={id:j++,callback:te,priorityLevel:D,startTime:G,expirationTime:Ce,sortIndex:-1},G>Ae?(D.sortIndex=G,c(y,D),o(x)===null&&D===o(y)&&(L?(Z(V),V=-1):L=!0,re(ge,G-Ae))):(D.sortIndex=Ce,c(x,D),R||N||(R=!0,ee||(ee=!0,ae()))),D},l.unstable_shouldYield=Y,l.unstable_wrapCallback=function(D){var te=S;return function(){var G=S;S=te;try{return D.apply(this,arguments)}finally{S=G}}}})($r)),$r}var Sm;function u0(){return Sm||(Sm=1,qr.exports=c0()),qr.exports}var Kr={exports:{}},yt={};var Nm;function r0(){if(Nm)return yt;Nm=1;var l=Lo();function c(x){var y="https://react.dev/errors/"+x;if(1<arguments.length){y+="?args[]="+encodeURIComponent(arguments[1]);for(var j=2;j<arguments.length;j++)y+="&args[]="+encodeURIComponent(arguments[j])}return"Minified React error #"+x+"; visit "+y+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function o(){}var r={d:{f:o,r:function(){throw Error(c(522))},D:o,C:o,L:o,m:o,X:o,S:o,M:o},p:0,findDOMNode:null},d=Symbol.for("react.portal");function f(x,y,j){var g=3<arguments.length&&arguments[3]!==void 0?arguments[3]:null;return{$$typeof:d,key:g==null?null:""+g,children:x,containerInfo:y,implementation:j}}var m=l.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE;function v(x,y){if(x==="font")return"";if(typeof y=="string")return y==="use-credentials"?y:""}return yt.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE=r,yt.createPortal=function(x,y){var j=2<arguments.length&&arguments[2]!==void 0?arguments[2]:null;if(!y||y.nodeType!==1&&y.nodeType!==9&&y.nodeType!==11)throw Error(c(299));return f(x,y,null,j)},yt.flushSync=function(x){var y=m.T,j=r.p;try{if(m.T=null,r.p=2,x)return x()}finally{m.T=y,r.p=j,r.d.f()}},yt.preconnect=function(x,y){typeof x=="string"&&(y?(y=y.crossOrigin,y=typeof y=="string"?y==="use-credentials"?y:"":void 0):y=null,r.d.C(x,y))},yt.prefetchDNS=function(x){typeof x=="string"&&r.d.D(x)},yt.preinit=function(x,y){if(typeof x=="string"&&y&&typeof y.as=="string"){var j=y.as,g=v(j,y.crossOrigin),S=typeof y.integrity=="string"?y.integrity:void 0,N=typeof y.fetchPriority=="string"?y.fetchPriority:void 0;j==="style"?r.d.S(x,typeof y.precedence=="string"?y.precedence:void 0,{crossOrigin:g,integrity:S,fetchPriority:N}):j==="script"&&r.d.X(x,{crossOrigin:g,integrity:S,fetchPriority:N,nonce:typeof y.nonce=="string"?y.nonce:void 0})}},yt.preinitModule=function(x,y){if(typeof x=="string")if(typeof y=="object"&&y!==null){if(y.as==null||y.as==="script"){var j=v(y.as,y.crossOrigin);r.d.M(x,{crossOrigin:j,integrity:typeof y.integrity=="string"?y.integrity:void 0,nonce:typeof y.nonce=="string"?y.nonce:void 0})}}else y==null&&r.d.M(x)},yt.preload=function(x,y){if(typeof x=="string"&&typeof y=="object"&&y!==null&&typeof y.as=="string"){var j=y.as,g=v(j,y.crossOrigin);r.d.L(x,j,{crossOrigin:g,integrity:typeof y.integrity=="string"?y.integrity:void 0,nonce:typeof y.nonce=="string"?y.nonce:void 0,type:typeof y.type=="string"?y.type:void 0,fetchPriority:typeof y.fetchPriority=="string"?y.fetchPriority:void 0,referrerPolicy:typeof y.referrerPolicy=="string"?y.referrerPolicy:void 0,imageSrcSet:typeof y.imageSrcSet=="string"?y.imageSrcSet:void 0,imageSizes:typeof y.imageSizes=="string"?y.imageSizes:void 0,media:typeof y.media=="string"?y.media:void 0})}},yt.preloadModule=function(x,y){if(typeof x=="string")if(y){var j=v(y.as,y.crossOrigin);r.d.m(x,{as:typeof y.as=="string"&&y.as!=="script"?y.as:void 0,crossOrigin:j,integrity:typeof y.integrity=="string"?y.integrity:void 0})}else r.d.m(x)},yt.requestFormReset=function(x){r.d.r(x)},yt.unstable_batchedUpdates=function(x,y){return x(y)},yt.useFormState=function(x,y,j){return m.H.useFormState(x,y,j)},yt.useFormStatus=function(){return m.H.useHostTransitionStatus()},yt.version="19.2.8",yt}var wm;function o0(){if(wm)return Kr.exports;wm=1;function l(){if(!(typeof __REACT_DEVTOOLS_GLOBAL_HOOK__>"u"||typeof __REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE!="function"))try{__REACT_DEVTOOLS_GLOBAL_HOOK__.checkDCE(l)}catch(c){console.error(c)}}return l(),Kr.exports=r0(),Kr.exports}var Tm;function d0(){if(Tm)return Yi;Tm=1;var l=u0(),c=Lo(),o=o0();function r(e){var t="https://react.dev/errors/"+e;if(1<arguments.length){t+="?args[]="+encodeURIComponent(arguments[1]);for(var n=2;n<arguments.length;n++)t+="&args[]="+encodeURIComponent(arguments[n])}return"Minified React error #"+e+"; visit "+t+" for the full message or use the non-minified dev environment for full errors and additional helpful warnings."}function d(e){return!(!e||e.nodeType!==1&&e.nodeType!==9&&e.nodeType!==11)}function f(e){var t=e,n=e;if(e.alternate)for(;t.return;)t=t.return;else{e=t;do t=e,(t.flags&4098)!==0&&(n=t.return),e=t.return;while(e)}return t.tag===3?n:null}function m(e){if(e.tag===13){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function v(e){if(e.tag===31){var t=e.memoizedState;if(t===null&&(e=e.alternate,e!==null&&(t=e.memoizedState)),t!==null)return t.dehydrated}return null}function x(e){if(f(e)!==e)throw Error(r(188))}function y(e){var t=e.alternate;if(!t){if(t=f(e),t===null)throw Error(r(188));return t!==e?null:e}for(var n=e,a=t;;){var s=n.return;if(s===null)break;var u=s.alternate;if(u===null){if(a=s.return,a!==null){n=a;continue}break}if(s.child===u.child){for(u=s.child;u;){if(u===n)return x(s),e;if(u===a)return x(s),t;u=u.sibling}throw Error(r(188))}if(n.return!==a.return)n=s,a=u;else{for(var h=!1,b=s.child;b;){if(b===n){h=!0,n=s,a=u;break}if(b===a){h=!0,a=s,n=u;break}b=b.sibling}if(!h){for(b=u.child;b;){if(b===n){h=!0,n=u,a=s;break}if(b===a){h=!0,a=u,n=s;break}b=b.sibling}if(!h)throw Error(r(189))}}if(n.alternate!==a)throw Error(r(190))}if(n.tag!==3)throw Error(r(188));return n.stateNode.current===n?e:t}function j(e){var t=e.tag;if(t===5||t===26||t===27||t===6)return e;for(e=e.child;e!==null;){if(t=j(e),t!==null)return t;e=e.sibling}return null}var g=Object.assign,S=Symbol.for("react.element"),N=Symbol.for("react.transitional.element"),R=Symbol.for("react.portal"),L=Symbol.for("react.fragment"),P=Symbol.for("react.strict_mode"),J=Symbol.for("react.profiler"),Z=Symbol.for("react.consumer"),F=Symbol.for("react.context"),_=Symbol.for("react.forward_ref"),ge=Symbol.for("react.suspense"),ee=Symbol.for("react.suspense_list"),V=Symbol.for("react.memo"),le=Symbol.for("react.lazy"),W=Symbol.for("react.activity"),Y=Symbol.for("react.memo_cache_sentinel"),ne=Symbol.iterator;function ae(e){return e===null||typeof e!="object"?null:(e=ne&&e[ne]||e["@@iterator"],typeof e=="function"?e:null)}var Q=Symbol.for("react.client.reference");function se(e){if(e==null)return null;if(typeof e=="function")return e.$$typeof===Q?null:e.displayName||e.name||null;if(typeof e=="string")return e;switch(e){case L:return"Fragment";case J:return"Profiler";case P:return"StrictMode";case ge:return"Suspense";case ee:return"SuspenseList";case W:return"Activity"}if(typeof e=="object")switch(e.$$typeof){case R:return"Portal";case F:return e.displayName||"Context";case Z:return(e._context.displayName||"Context")+".Consumer";case _:var t=e.render;return e=e.displayName,e||(e=t.displayName||t.name||"",e=e!==""?"ForwardRef("+e+")":"ForwardRef"),e;case V:return t=e.displayName||null,t!==null?t:se(e.type)||"Memo";case le:t=e._payload,e=e._init;try{return se(e(t))}catch{}}return null}var re=Array.isArray,D=c.__CLIENT_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,te=o.__DOM_INTERNALS_DO_NOT_USE_OR_WARN_USERS_THEY_CANNOT_UPGRADE,G={pending:!1,data:null,method:null,action:null},Ae=[],Ce=-1;function C(e){return{current:e}}function q(e){0>Ce||(e.current=Ae[Ce],Ae[Ce]=null,Ce--)}function I(e,t){Ce++,Ae[Ce]=e.current,e.current=t}var ie=C(null),me=C(null),be=C(null),ye=C(null);function ze(e,t){switch(I(be,t),I(me,e),I(ie,null),t.nodeType){case 9:case 11:e=(e=t.documentElement)&&(e=e.namespaceURI)?qh(e):0;break;default:if(e=t.tagName,t=t.namespaceURI)t=qh(t),e=$h(t,e);else switch(e){case"svg":e=1;break;case"math":e=2;break;default:e=0}}q(ie),I(ie,e)}function oe(){q(ie),q(me),q(be)}function Wt(e){e.memoizedState!==null&&I(ye,e);var t=ie.current,n=$h(t,e.type);t!==n&&(I(me,e),I(ie,n))}function Ea(e){me.current===e&&(q(ie),q(me)),ye.current===e&&(q(ye),Hi._currentValue=G)}var Qn,Vl;function St(e){if(Qn===void 0)try{throw Error()}catch(n){var t=n.stack.trim().match(/\\n( *(at )?)/);Qn=t&&t[1]||"",Vl=-1<n.stack.indexOf(\`
10
10
  at\`)?" (<anonymous>)":-1<n.stack.indexOf("@")?"@unknown:0:0":""}return\`
11
11
  \`+Qn+e+Vl}var kt=!1;function ul(e,t){if(!e||kt)return"";kt=!0;var n=Error.prepareStackTrace;Error.prepareStackTrace=void 0;try{var a={DetermineComponentFrameRoot:function(){try{if(t){var K=function(){throw Error()};if(Object.defineProperty(K.prototype,"props",{set:function(){throw Error()}}),typeof Reflect=="object"&&Reflect.construct){try{Reflect.construct(K,[])}catch(U){var O=U}Reflect.construct(e,[],K)}else{try{K.call()}catch(U){O=U}e.call(K.prototype)}}else{try{throw Error()}catch(U){O=U}(K=e())&&typeof K.catch=="function"&&K.catch(function(){})}}catch(U){if(U&&O&&typeof U.stack=="string")return[U.stack,O.stack]}return[null,null]}};a.DetermineComponentFrameRoot.displayName="DetermineComponentFrameRoot";var s=Object.getOwnPropertyDescriptor(a.DetermineComponentFrameRoot,"name");s&&s.configurable&&Object.defineProperty(a.DetermineComponentFrameRoot,"name",{value:"DetermineComponentFrameRoot"});var u=a.DetermineComponentFrameRoot(),h=u[0],b=u[1];if(h&&b){var w=h.split(\`
12
12
  \`),z=b.split(\`
@@ -45,7 +45,7 @@ Minimum version required to store current data is: \`+ne+\`.
45
45
  hint: \${c.errorHint}\`]}),c.note===void 0?null:i.jsx("p",{className:"note",children:c.note}),i.jsx("div",{className:"label",children:"asked"}),i.jsx("p",{className:"row user",style:{margin:"0 0 12px"},children:c.input}),i.jsx("div",{className:"label",children:"reply"}),c.text===""?i.jsx("p",{className:"empty",children:"no reply text"}):i.jsx("div",{className:"row reply",children:i.jsx(Mc,{text:c.text})}),i.jsx(ix,{turn:c,...l.replay===void 0?{}:{replay:l.replay},...l.onReplay===void 0?{}:{onReplay:l.onReplay}})]}):null]})}function ix(l){const{replay:c}=l;return c===void 0?l.onReplay===void 0?null:i.jsx("button",{type:"button",style:{marginTop:12},onClick:()=>l.onReplay?.(l.turn),children:"replay every step"}):c.state==="loading"?i.jsx("p",{className:"empty",children:"reading the stored steps…"}):c.state==="failed"?i.jsx("p",{className:"note bad",children:c.message}):c.steps.length===0?i.jsx("p",{className:"empty",children:"No stored steps for this turn: its conversation was cleared, or it is older than the last 1,000 messages of it."}):i.jsx("ol",{className:"replay",children:c.steps.map(o=>i.jsxs("li",{children:[i.jsx("div",{className:"label",children:ex(o)}),i.jsx("pre",{className:"snippet",children:(()=>{const r=Pp(o);return r.length>wo?\`\${r.slice(0,wo)}
46
46
  … (\${r.length-wo} more characters)\`:r})()})]},o.id))})}function sx(l,c){if(c<=0)return"";const o=l.replace(/\\s+/g," ").trim();return o.length<=c?o:c===1?"…":\`\${o.slice(0,c-1)}…\`}const Uo="#",Do={A:[".###.","#...#","#####","#...#","#...#"],B:["####.","#...#","####.","#...#","####."],C:[".####","#....","#....","#....",".####"],D:["####.","#...#","#...#","#...#","####."],E:["#####","#....","####.","#....","#####"],F:["#####","#....","####.","#....","#...."],G:[".####","#....","#..##","#...#",".###."],H:["#...#","#...#","#####","#...#","#...#"],I:["#####","..#..","..#..","..#..","#####"],J:["..###","....#","....#","#...#",".###."],K:["#...#","#..#.","###..","#..#.","#...#"],L:["#....","#....","#....","#....","#####"],M:["#...#","##.##","#.#.#","#...#","#...#"],N:["#...#","##..#","#.#.#","#..##","#...#"],O:[".###.","#...#","#...#","#...#",".###."],P:["####.","#...#","####.","#....","#...."],Q:[".###.","#...#","#.#.#","#..#.",".##.#"],R:["####.","#...#","####.","#..#.","#...#"],S:[".####","#....",".###.","....#","####."],T:["#####","..#..","..#..","..#..","..#.."],U:["#...#","#...#","#...#","#...#",".###."],V:["#...#","#...#","#...#",".#.#.","..#.."],W:["#...#","#...#","#.#.#","##.##","#...#"],X:["#...#",".#.#.","..#..",".#.#.","#...#"],Y:["#...#",".#.#.","..#..","..#..","..#.."],Z:["#####","...#.","..#..",".#...","#####"],0:[".###.","#..##","#.#.#","##..#",".###."],1:["..#..",".##..","..#..","..#..",".###."],2:[".###.","#...#","..##.",".#...","#####"],3:["####.","....#",".###.","....#","####."],4:["#..#.","#..#.","#####","...#.","...#."],5:["#####","#....","####.","....#","####."],6:[".###.","#....","####.","#...#",".###."],7:["#####","....#","...#.","..#..",".#..."],8:[".###.","#...#",".###.","#...#",".###."],9:[".###.","#...#",".####","....#",".###."],".":[".....",".....",".....",".....","..#.."],"-":[".....",".....",".###.",".....","....."]," ":[".....",".....",".....",".....","....."]},cx=5,ux=1;function rx(l){return[...l.toUpperCase()].every(c=>Do[c]!==void 0)}function ox(l){const c=[...l.toUpperCase()].map(r=>Do[r]??Do[" "]),o=".".repeat(ux);return Array.from({length:cx},(r,d)=>c.map(f=>f?.[d]??"").join(o))}function Ng(l,c,o){const r=c.repeat(o),d=" ".repeat(o);return l.map(f=>[...f].map(m=>m===Uo?r:d).join(""))}function dx(l){const c=[".".repeat([...l[0]??""].length),...l],o=[];for(let r=0;r<c.length;r+=2){const d=[...c[r]??""],f=[...c[r+1]??""],m=[];for(let v=0;v<Math.max(d.length,f.length);v+=1){const x=d[v]===Uo,y=f[v]===Uo;m.push(x&&y?"█":x?"▀":y?"▄":" ")}o.push(m.join(""))}return o}function wg(l,c){return[sx([...l.toUpperCase()].join(" "),c)]}function To(l){return l.reduce((c,o)=>Math.max(c,[...o].length),0)}function fx(l,c){const o=l.trim();if(o===""||!rx(o)){const m=wg(o,c.columns);return{lines:m,tier:"plain",width:To(m)}}const r=ox(o),d=[{tier:"wide",lines:Ng(r,"█",2)},{tier:"block",lines:Ng(r,"█",1)},{tier:"half",lines:dx(r)}];for(const m of d){const v=m.lines.map(y=>y.replace(/\\s+$/,"")),x=To(v);if(x<=c.columns&&v.length<=c.rows)return{lines:v,tier:m.tier,width:x}}const f=wg(o,c.columns);return{lines:f,tier:"plain",width:To(f)}}function Ig(l,c){const o=fx(l,{columns:c,rows:5});return{width:o.width,height:o.lines.length,cells:o.lines.flatMap((r,d)=>[...r].flatMap((f,m)=>f==="█"?[{x:m,y:d}]:[]))}}const hx=Ig(nt.name,60),Fi=Ig(nt.name.slice(0,1),9);function mx(l){return i.jsx("svg",{role:"img","aria-label":l.label??nt.name,viewBox:\`0 0 \${l.grid.width} \${l.grid.height}\`,height:l.height,className:"wordmark",shapeRendering:"crispEdges",children:l.grid.cells.map(({x:c,y:o})=>i.jsx("rect",{x:c,y:o,width:1,height:1,fill:"currentColor"},\`\${c}:\${o}\`))})}function Pg(l){return i.jsx(mx,{grid:hx,height:l.height??14})}function gx(){const c=Math.max(Fi.width,Fi.height)+4,o=(c-Fi.width)/2,r=(c-Fi.height)/2,d=Fi.cells.map(({x:m,y:v})=>\`<rect x='\${m+o}' y='\${v+r}' width='1' height='1'/>\`).join(""),f=\`<svg xmlns='http://www.w3.org/2000/svg' viewBox='0 0 \${c} \${c}' shape-rendering='crispEdges'><rect width='\${c}' height='\${c}' rx='1.5' fill='#121212'/><g fill='#d75fd7'>\${d}</g></svg>\`;return\`data:image/svg+xml,\${encodeURIComponent(f)}\`}const Eo=\`\${nt.slug}.turn\`;function vx(l){const[c,o]=T.useState(),[r,d]=T.useState();return T.useEffect(()=>{tb(l.baseUrl).then(o).catch(f=>d(f instanceof Error?f.message:String(f)))},[l.baseUrl]),r!==void 0?i.jsxs(Bo,{title:"Cannot reach the server",children:[i.jsx("p",{children:r}),i.jsx("button",{type:"button",onClick:()=>window.location.reload(),children:"Try again"})]}):c===void 0?i.jsx(Bo,{title:"Connecting…"}):c.kind==="needed"?i.jsx(yx,{baseUrl:l.baseUrl,because:c.because}):i.jsx(px,{baseUrl:l.baseUrl,token:c.kind==="key"?c.secret:void 0})}function Bo(l){return i.jsx("div",{className:"gate",children:i.jsxs("div",{className:"card",children:[i.jsx("div",{className:"brand",children:i.jsx(Pg,{height:20})}),i.jsx("h2",{children:l.title}),l.children]})})}function yx(l){const[c,o]=T.useState(""),[r,d]=T.useState(),[f,m]=T.useState(!1),v=async x=>{m(!0),d(void 0);try{const y=x?await _g(l.baseUrl,c.trim()):c.trim();Ho(y),window.location.reload()}catch(y){d(y instanceof Error?y.message:String(y)),m(!1)}};return i.jsxs(Bo,{title:"This server needs a credential",children:[l.because.replace(/\\.$/,"")==="This server needs a credential"?null:i.jsx("p",{children:l.because}),i.jsx("input",{value:c,type:"password",autoComplete:"off",placeholder:"paste a claim or an operator key",onChange:x=>o(x.target.value)}),i.jsxs("p",{className:"hint",style:{margin:"10px 0 16px"},children:[i.jsxs("code",{children:[nt.slug," serve"]})," prints a one-time claim at boot while no key exists; a claim is exchanged for a key this browser keeps. To mint a key instead, run ",i.jsxs("code",{children:[nt.slug," credential create"]})," where the server runs. An agent's own ",i.jsx("code",{children:".env"})," token is not the server's."]}),i.jsx("div",{className:"ask",children:i.jsxs("div",{className:"buttons",children:[i.jsx("button",{type:"button",className:"primary",disabled:f||c.trim()==="",onClick:()=>v(!0),children:"Exchange a claim"}),i.jsx("button",{type:"button",disabled:f||c.trim()==="",onClick:()=>v(!1),children:"Use as a key"})]})}),r===void 0?null:i.jsx("p",{className:"note bad",style:{marginTop:12},children:r})]})}const nl=l=>l instanceof xn&&l.status===404,bx={home:"Overview",team:"Team",models:"Models",turns:"Turns",usage:"Usage","server-usage":"Usage, all agents",api:"API",new:"New agent",tools:"Tools",schedules:"Schedules",channels:"Channels",config:"Settings",keys:"Operator keys",people:"People",rooms:"Rooms",actions:"Actions",memory:"Memory",webhooks:"Webhooks",backup:"Backup",files:"Files"};function px(l){const c=T.useRef(Ug(l.baseUrl,l.token)),[o,r]=T.useState([]),[d,f]=T.useState(),[m,v]=T.useState(),[x,y]=T.useState(),[j,g]=T.useState([]),S=T.useCallback(async()=>{f(void 0),v(void 0),g([]),re("this agent is no longer running on this server — start it from the list");try{r(await c.current.agents())}catch{}},[]),[N,R]=T.useState([]),[L,P]=T.useState(),J=N.find(p=>p.sessionKey===L),[Z,F]=T.useState(!1),[_,ge]=T.useState(()=>{const p=new URL(window.location.href).searchParams;return p.get("agent")===null&&p.get("panel")===null?"home":cb(window.location.href).panel}),[ee,V]=T.useState(al),[le,W]=T.useState(""),[Y,ne]=T.useState([]),[ae,Q]=T.useState(),[se,re]=T.useState(),D=T.useRef(void 0),te=T.useRef(fb());T.useEffect(()=>{const p=new URL(window.location.href).searchParams.get("agent")??void 0;c.current.agents().then(A=>{r(A);const $=A.filter(fe=>fe.status!=="disabled"),X=$.find(fe=>fe.id===p)??$[0];if(X===void 0){new URL(window.location.href).searchParams.get("panel")===null&&ge("new");return}f(X.id),v(X.name),V(fe=>({...fe,filter:Cb(X.dialect??"nlt").filter})),document.title=\`\${X.name} · \${nt.name}\`}).catch(A=>re(Ze(A)))},[]);const G=T.useMemo(()=>d===void 0?void 0:c.current.agent(d),[d]),[Ae,Ce]=T.useState([]);T.useEffect(()=>{if(Ce([]),Q(void 0),G===void 0)return;let p=!1;return G.config().then(A=>{p||Ce(A.settings.filter($=>/^model\\.[^.<]+$/.test($.path)&&$.value!==void 0).map($=>$.path.slice(6)))}).catch(()=>{}),()=>{p=!0}},[G]);const C=T.useMemo(()=>N.filter(p=>!["web","local","api","schedule","room","owner","peer","shared"].includes(p.channel)).map(p=>({channel:p.channel,to:p.peerId,label:\`\${p.channel} → \${p.peerId}\`})),[N]),q=p=>o.find(A=>A.id===p)?.sessionScope,I=T.useCallback(async()=>{if(G!==void 0)try{R((await G.sessions()).filter(p=>!U0(p.sessionKey))),re(void 0)}catch(p){nl(p)?S():re(Ze(p))}},[G,S]);T.useEffect(()=>{I()},[I]);const ie=T.useCallback(async(p,A)=>{const $=te.current,X=$.begin(p);if(X===void 0)return;const fe=A.turn(p);D.current=()=>fe.stop();try{sessionStorage.setItem(Eo,p);for await(const pe of fe.stream({chunks:!0,children:!0,signal:X}))V(Ue=>kb(Ue,pe))}catch(pe){X.aborted||(re(Ze(pe)),V(Ue=>({...Ue,running:!1})))}finally{$.finish(p),sessionStorage.removeItem(Eo),D.current=void 0,X.aborted||I()}},[I]);T.useEffect(()=>{if(G===void 0)return;let p=null;try{p=sessionStorage.getItem(jc)}catch{}const A=d===void 0?void 0:Sb(p,d),$=sessionStorage.getItem(Eo);let X=!1;return(async()=>{const fe=A??await jx(G);if(fe!==void 0&&!X){try{d!==void 0&&sessionStorage.setItem(jc,Lm(d,fe))}catch{}P(fe);try{const pe=await Tg(G,fe);X||V({...al,rows:pe})}catch{}}$===null||X||(V(pe=>({...pe,running:!0})),ie($,G))})(),()=>{X=!0,te.current.abort()}},[G,d,ie]),T.useEffect(()=>{if(G===void 0)return;let p=!0;const A=()=>{G.approvals().then(X=>{p&&g(X)}).catch(X=>{p&&nl(X)&&S()})};A();const $=window.setInterval(A,5e3);return()=>{p=!1,window.clearInterval($)}},[G,S]);const me=async()=>{const p=Y,A=le.trim()===""&&p.length>0?"(image)":le.trim();if(!(A===""||G===void 0)){W(""),ne([]),re(void 0),V($=>Ab($,p.length===0?A:\`\${A}
47
47
  [\${p.length} image\${p.length===1?"":"s"}]\`));try{const $=L===void 0&&Z&&Bg(q(d))?await G.rotateSession():void 0;Z&&F(!1);const X=L??$?.sessionKey??jb(pe=>crypto.getRandomValues(new Uint8Array(pe))),fe=await G.send(A,{sessionKey:X,chunks:!0,...ae===void 0?{}:{role:ae},...p.length===0?{}:{images:p.map(pe=>({data:pe.data,mediaType:pe.mediaType}))}});fe.sessionKey!==L&&(P(fe.sessionKey),ye(fe.sessionKey),I()),await ie(fe.turnId,G)}catch($){re(Ze($)),V(X=>({...X,running:!1}))}}},be=async(p,A)=>{if(G!==void 0)try{await G.approve(p,A)}catch($){$ instanceof xn&&$.code==="approval_not_found"||re(Ze($))}},ye=p=>{try{p===void 0||d===void 0?sessionStorage.removeItem(jc):sessionStorage.setItem(jc,Lm(d,p))}catch{}},ze=async p=>{if(te.current.abort(),ge("chat"),F(!1),P(p),ye(p),V(al),W(""),!(p===void 0||G===void 0))try{const A=await Tg(G,p);V({...al,rows:A})}catch(A){re(Ze(A))}},[oe,Wt]=T.useState({tools:[],schedules:[],channels:[],warnings:[],secrets:[]}),[Ea,Qn]=T.useState(void 0),[Vl,St]=T.useState(void 0),kt=T.useCallback(async p=>{const[A,$,X,fe,pe]=await Promise.all([p.tools(),p.schedules(),p.describe(),p.config(),p.secrets().catch(()=>[])]);Wt({tools:A,schedules:$,channels:X.channels??[],warnings:X.warnings??[],...X.team===void 0?{}:{team:X.team},...X.peers===void 0?{}:{peers:X.peers},ask:X.ask===!0,secrets:pe,...X.catalogueTokens===void 0?{}:{catalogueTokens:X.catalogueTokens},...X.capabilities===void 0?{}:{capabilities:X.capabilities},...X.phases===void 0||X.phases.length===0?{}:{phases:X.phases},config:fe})},[]),ul=T.useCallback(async(p,A)=>{if(G!==void 0){Qn(p),St(void 0);try{const $=await G.setChannel(p,A);St([...$.notes,...$.applied?[]:[\`Not in force yet: \${$.pending?.message??"restart to apply"}\`]].join(" ")),await kt(G)}catch($){St($ instanceof Error?$.message:String($))}finally{Qn(void 0)}}},[G,kt]),zc=T.useCallback(async p=>{if(G!==void 0){Qn(p),St(void 0);try{St((await G.unpairChannel(p)).note),await kt(G)}catch(A){St(A instanceof Error?A.message:String(A))}finally{Qn(void 0)}}},[G,kt]);T.useEffect(()=>{if(G===void 0||_!=="team"&&_!=="models"&&_!=="tools"&&_!=="schedules"&&_!=="channels"&&_!=="config")return;let p=!1;return(async()=>{try{if(await kt(G),p)return}catch(A){if(p)return;nl(A)?S():re(Ze(A))}})(),()=>{p=!0}},[G,_,S,kt]);const[ht,rl]=T.useState(),[Ht,ol]=T.useState(),We=T.useCallback(async(p,A)=>{if(G!==void 0){rl(p),re(void 0),ol(void 0);try{const $=await A(G);ol($),await kt(G)}catch($){nl($)?S():re(Ze($))}finally{rl(void 0)}}},[G,S,kt]),Xn=T.useCallback((p,A,$)=>{We(p,async X=>{const fe=await X.setConfig(p,A,{...$.confirm?{confirm:!0}:{}});return fe.applied?fe.reflowed?\`\${p} saved. The manifest was re-serialised, so its comments have moved — worth a look at the diff.\`:void 0:\`\${p} was written to the manifest and is not in force yet: \${fe.pending?.message??"the agent could not be replaced"}\`})},[We]),[mt,Pi]=T.useState(),[Zl,Jl]=T.useState();T.useEffect(()=>{if(_!=="home")return;let p=!1;return c.current.usage({by:["agent"],from:new Date(Date.now()-7*864e5).toISOString()}).then(A=>{p||Jl(A.buckets)}).catch(()=>{p||Jl(void 0)}),()=>{p=!0}},[_]);const[jn,es]=T.useState("30d"),[Fl,ts]=T.useState(!1);T.useEffect(()=>{const p=_==="server-usage";if(!p&&(_!=="usage"||G===void 0))return;const A=p?c.current:G;if(A===void 0)return;let $=!1;Pi(void 0),ts(!0);const X=qg.find(pe=>pe.key===jn)?.days??30,fe=new Date(Date.now()-X*864e5).toISOString();return Promise.all([A.usage({by:["day"],from:fe}),A.usage({by:["model"],from:fe}),A.usage({by:["sender"],from:fe}),p?A.usage({by:["agent"],from:fe}):Promise.resolve(void 0)]).then(([pe,Ue,Mt,Ha])=>{$||Pi({byDay:pe.buckets,byModel:Ue.buckets,bySender:Mt.buckets,...Ha===void 0?{}:{byAgent:Ha.buckets},...pe.meteredSince===void 0?{}:{meteredSince:pe.meteredSince}})}).catch(pe=>{$||(nl(pe)?S():re(Ze(pe)))}).finally(()=>{$||ts(!1)}),()=>{$=!0}},[_,G,jn,S]);const[Oc,Sn]=T.useState({}),bt=T.useCallback(async(p,A)=>{if(G!==void 0){Sn($=>({...$,[p]:{state:"loading"}}));try{const $=[];let X;for(let fe=0;fe<5;fe+=1){const pe=await G.messages(A,{limit:200,...X===void 0?{}:{before:X}}),Ue=pe.messages.filter(Mt=>Mt.turnId===p);if($.push(...Ue),$.length>0&&Ue.length<pe.messages.length||pe.nextBefore===void 0)break;X=pe.nextBefore}Sn(fe=>({...fe,[p]:{state:"ready",steps:$.reverse()}}))}catch($){Sn(X=>({...X,[p]:{state:"failed",message:Ze($)}}))}}},[G]),[on,gt]=T.useState([]),[ns,as]=T.useState(),[_c,Ca]=T.useState(!1),Vn=T.useCallback(async p=>{if(G!==void 0){Ca(!0);try{const A=await G.turns({limit:50,...p===void 0?{}:{before:p}});gt($=>p===void 0?A.turns:[...$,...A.turns]),as(A.nextBefore)}catch(A){nl(A)?S():re(Ze(A))}finally{Ca(!1)}}},[G,S]);T.useEffect(()=>{_==="turns"&&(gt([]),as(void 0),Vn())},[_,Vn]);const[Nn,It]=T.useState([]),[dl,Aa]=T.useState({}),[ls,fl]=T.useState(),ka=T.useCallback(async p=>{const[A,$]=await Promise.all([p.assignment(),c.current.participants()]);It($),fl(A.assignment?.participantId??null)},[]);T.useEffect(()=>{_!=="team"||G===void 0||(fl(void 0),ka(G).catch(()=>fl(void 0)))},[_,G,ka]);const[Ma,Uc]=T.useState([]),[wn,Wl]=T.useState(),[is,hl]=T.useState([]),[Il,Pl]=T.useState([]),[ss,dn]=T.useState([]),[qe,vt]=T.useState("space"),[Zn,ml]=T.useState(),[cs,Dc]=T.useState([]),[pt,Jn]=T.useState(),[Nt,fn]=T.useState(),xt=T.useMemo(()=>o.filter(p=>p.status!=="disabled").map(p=>({id:p.id,name:p.name})),[o]),qt=T.useCallback(async()=>{const p=c.current,[A,$]=await Promise.all([p.participants(),Promise.all(o.filter(X=>X.status!=="disabled").map(async X=>{try{const fe=await p.agent(X.id).assignment();return[X.id,fe.assignment?.participantId]}catch{return[X.id,void 0]}}))]);It(A),Aa(Object.fromEntries($.filter(([,X])=>X!==void 0)))},[o]),Pt=T.useCallback(async()=>Uc(await c.current.conversations()),[]),Qe=T.useCallback(async()=>dn(await c.current.actions()),[]),hn=T.useCallback(async()=>{const p=c.current,[A,$,X]=await Promise.all([p.notes(qe),p.projects(),p.participants()]);ml(A),Dc($),It(X)},[qe]);T.useEffect(()=>{const p=_==="people"?qt:_==="rooms"?Pt:_==="actions"?Qe:_==="memory"?hn:void 0;if(p===void 0)return;let A=!1;return _==="memory"&&ml(void 0),p().catch($=>{A||re(Ze($))}),()=>{A=!0}},[_,qt,Pt,Qe,hn]),T.useEffect(()=>{if(_!=="rooms"||wn===void 0)return;let p=!1,A;hl([]);const $=async()=>{try{const pe=await c.current.conversationMessages(wn,{...A===void 0?{}:{after:A}});if(p)return;pe.messages.length>0&&hl(Ue=>[...Ue,...pe.messages]),pe.nextAfter!==void 0&&(A=pe.nextAfter)}catch(pe){p||re(Ze(pe))}};$();const X=setInterval(()=>{$()},3e3);Pl([]);const fe=new AbortController;return(async()=>{try{for await(const pe of c.current.events({types:["conversation.skipped"],signal:fe.signal})){if(pe.kind!=="event"||pe.event.type!=="conversation.skipped")continue;const Ue=pe.event.data;Ue.conversationId===wn&&Pl(Mt=>[...Mt,Ue])}}catch{}})(),()=>{p=!0,clearInterval(X),fe.abort()}},[_,wn]);const[us,Tn]=T.useState([]),[En,rs]=T.useState(),[Ra,os]=T.useState(),[Fn,za]=T.useState("answers"),[Oa,en]=T.useState(),st=T.useCallback(async()=>Tn(await c.current.webhooks()),[]);T.useEffect(()=>{_==="webhooks"&&st().catch(p=>re(Ze(p)))},[_,st]),T.useEffect(()=>{_!=="new"||Fn!=="template"||Ra!==void 0||c.current.templates().then(os).catch(p=>re(Ze(p)))},[_,Fn,Ra]);const ei=T.useCallback((p,A)=>{const $=URL.createObjectURL(A),X=document.createElement("a");X.href=$,X.download=p,document.body.appendChild(X),X.click(),X.remove(),URL.revokeObjectURL($)},[]),[Bc,Wn]=T.useState(),[In,_a]=T.useState(),[ds,ct]=T.useState(),[Cn,gl]=T.useState(),Ua=T.useCallback(async p=>{const A=await p.vars().catch(()=>{});if(A===void 0)return gl(void 0);const $=(await c.current.templates().catch(()=>[])).find(X=>X.name===A.template)?.vars;gl({template:A.template,vars:A.vars,...$===void 0?{}:{declared:$}})},[]);T.useEffect(()=>{if(_!=="files"||G===void 0)return;let p=!1;return Wn(void 0),_a(void 0),ct(void 0),gl(void 0),Ua(G),G.workspaceFiles().then(A=>{p||Wn(A.files)}).catch(A=>{p||(nl(A)?S():re(Ze(A)))}),()=>{p=!0}},[_,G,S,Ua]),T.useEffect(()=>{if(_!=="files"||G===void 0||In===void 0)return;let p=!1;return ct(void 0),G.workspaceFile(In).then(A=>{p||ct(A.content)}).catch(A=>{p||re(Ze(A))}),()=>{p=!0}},[_,G,In]);const $e=T.useCallback(async(p,A,$)=>{Jn(p),fn(void 0);try{fn(await A()),await $()}catch(X){fn(Ze(X))}finally{Jn(void 0)}},[]),tn=T.useCallback(p=>oe.config?.settings.find(A=>A.path===p)?.value,[oe.config]),[ti,Pn]=T.useState(),Lc=T.useMemo(()=>{const p=tn("tools.providers");return p!==null&&typeof p=="object"&&!Array.isArray(p)?p:{}},[tn]),fs=T.useMemo(()=>{const p=tn("tools.providers");return p===null||typeof p!="object"||Array.isArray(p)?[]:Object.entries(p).map(([A,$])=>{const X=$!==null&&typeof $=="object"&&typeof $.apiKeyEnv=="string"?$.apiKeyEnv:void 0;return{id:A,...X===void 0?{}:{keyEnv:X,keySet:oe.secrets.find(fe=>fe.name===X)?.set??!1}}})},[tn,oe.secrets]),hs=T.useCallback((p,A)=>{We(p,async $=>{const X=await $.setConfigs(A);return!X.reloaded&&X.applied?"Nothing changed.":X.applied?"Saved — the agent was replaced and runs on it now.":\`Written, not in force yet: \${X.pending?.message??"the agent could not be replaced"}\`})},[We]),ni=T.useCallback((p,A)=>{We(\`secret:\${p}\`,async $=>{const X=await $.setSecrets({[p]:A});return X.shadowed.includes(p)?\`\${p} was written, and the server's own environment sets it too — that value wins.\`:X.applied==="none"?\`\${p} written; \${X.error?.message??"the agent was not reloaded"}\`:\`\${p} saved.\`})},[We]),[$t,ms]=T.useState(),[An,Kt]=T.useState({}),[ai,vl]=T.useState(!1),[kn,nn]=T.useState(!1),[Da,ea]=T.useState();T.useEffect(()=>{if(_!=="new"||$t!==void 0)return;let p=!1;return(async()=>{try{const A=await c.current.provision();if(p)return;ms(A),Kt(gb(A.steps))}catch(A){p||re(Ze(A))}})(),()=>{p=!0}},[_,$t]);const gs=T.useCallback(async()=>{if($t!==void 0&&(vl(!0),!(Dg($t.steps,An).length>0))){nn(!0),re(void 0);try{const p=await c.current.createAgent(bb($t.steps,An));ea(p),r(await c.current.agents())}catch(p){re(Ze(p))}finally{nn(!1)}}},[$t,An]),ut=T.useCallback(p=>{const A=p.panel??_,$=p.agentId??d;ge(A),p.agentId!==void 0&&p.agentId!==d&&(f(p.agentId),v(o.find(X=>X.id===p.agentId)?.name),P(void 0),V(al),W("")),window.history.replaceState(null,"",ub(window.location.href,{...$===void 0?{}:{agentId:$},panel:A}))},[d,o,_]),[an,Ba]=T.useState(!1);T.useEffect(()=>{const p=A=>{(A.metaKey||A.ctrlKey)&&A.key.toLowerCase()==="k"&&(A.preventDefault(),Ba($=>!$))};return window.addEventListener("keydown",p),()=>window.removeEventListener("keydown",p)},[]);const La=T.useMemo(()=>hb({agentPanels:So,serverPanels:Sg,agents:xt,...d===void 0?{}:{current:{id:d,name:m??d}}}),[xt,d,m]),ln=T.useCallback(async p=>{y(p);try{await c.current.agent(p).start(),r(await c.current.agents())}catch(A){re(Ze(A))}finally{y(void 0)}},[]);return i.jsxs("div",{className:"shell",children:[i.jsxs("aside",{className:"side",children:[i.jsxs("header",{children:[i.jsx("div",{className:"brand",children:i.jsx(Pg,{})}),i.jsxs("span",{className:"version",children:[o.length," agent",o.length===1?"":"s"]})]}),i.jsxs("nav",{children:[i.jsx("div",{className:"group",children:"Agents"}),i.jsx(Up,{agents:o,current:_==="home"||_==="keys"||_==="api"||_==="new"?void 0:d,onSelect:p=>ut({agentId:p,panel:"chat"}),onStart:p=>{ln(p)},...x===void 0?{}:{starting:x}}),d===void 0?null:i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"group",children:m??d}),So.map(p=>i.jsx("button",{type:"button",className:"row-button","aria-current":_===p.panel,onClick:()=>p.panel==="chat"?void ze(L):ut({panel:p.panel}),children:p.label},p.panel)),i.jsx("div",{className:"group",children:"Conversations"}),i.jsx("button",{type:"button",className:"row-button","aria-current":_==="chat"&&L===void 0,onClick:()=>{ze(void 0),F(!0)},children:"+ new conversation"}),N.map(p=>i.jsx("button",{type:"button",className:\`row-button session\${wb(p.sessionKey)?" person":""}\`,"aria-current":_==="chat"&&L===p.sessionKey,onClick:()=>{ze(p.sessionKey)},title:p.sessionKey,children:Tb(p)},p.sessionKey))]}),i.jsx("div",{className:"group",children:"Server"}),Sg.map(p=>i.jsx("button",{type:"button",className:"row-button","aria-current":_===p.panel,onClick:()=>ut({panel:p.panel}),children:p.label},p.panel)),i.jsx("button",{type:"button",className:"row-button","aria-current":_==="new",onClick:()=>ut({panel:"new"}),children:"+ New agent"})]}),i.jsxs("footer",{children:[i.jsx("span",{className:\`dot \${ee.running?"busy":"live"}\`}),i.jsx("span",{style:{fontSize:12,color:"var(--dim)"},children:ee.running?"working":"ready"}),l.token===void 0?i.jsx("span",{style:{fontSize:11,color:"var(--warn)",marginLeft:"auto"},children:"unauthenticated"}):i.jsx("button",{type:"button",style:{marginLeft:"auto",padding:"3px 8px",fontSize:11},onClick:()=>{qo(),window.location.reload()},children:"sign out"})]})]}),an?i.jsx(tp,{entries:La,onClose:()=>Ba(!1),onPick:p=>{Ba(!1),ut(p.target)}}):null,i.jsxs("main",{className:"main",children:[i.jsxs("div",{className:"bar",children:[i.jsx("strong",{children:_==="chat"?m??"":bx[_]}),_==="chat"&&L!==void 0&&G!==void 0?i.jsx("button",{type:"button",className:"ghost hide-narrow",disabled:ee.running,onClick:()=>{window.confirm("Clear this conversation's history? The agent's memory files are kept.")&&We(\`clear:\${L}\`,async p=>(await p.clearSession(L),V(al),"History cleared."))},children:"clear history"}):null,_==="chat"&&L!==void 0&&G!==void 0?i.jsx(Lp,{...J===void 0?{}:{session:J},...oe.phases===void 0?{}:{phases:oe.phases},busy:ee.running,onRecall:p=>{We(\`recall:\${L}\`,async A=>(await A.setRecall(L,p),await I(),p?"This conversation is recalled again.":"Kept out of history recall. Its messages stay."))},onPhase:p=>{We(\`phase:\${L}\`,async A=>(await A.setPhase(L,p),await I(),\`Phase set to \${p}.\`))},onCompact:()=>{We(\`compact:\${L}\`,async p=>{const A=await p.compactSession(L);return await I(),\`Compacted: the next turn starts from about \${A.after} tokens instead of \${A.before} (\${A.digest} digest, last \${A.keptTurns} turns kept). Every message is still stored.\`})}}):null,_==="chat"?i.jsx("span",{className:"crumb hide-narrow",children:L??"new conversation"}):null,i.jsx("span",{className:"spacer"}),j.length>0?i.jsxs("span",{style:{color:"var(--warn)"},children:[j.length," waiting on you"]}):null,i.jsx("button",{type:"button",className:"ghost hide-narrow",onClick:()=>ut({panel:"api"}),children:"API"}),i.jsx("a",{href:\`\${l.baseUrl}/docs\`,target:"_blank",rel:"noreferrer",children:"Docs ↗"}),i.jsx(ep,{})]}),_!=="chat"?i.jsx("div",{className:"scroll",children:i.jsxs("div",{className:_==="home"?"pad wide":"pad",children:[se===void 0?null:i.jsx("p",{className:"row note bad",children:se}),So.some(p=>p.panel===_)?i.jsx(Hp,{warnings:oe.warnings}):null,_==="home"?i.jsx(Vb,{agents:o,...Zl===void 0?{}:{week:Zl},onUsage:()=>ut({panel:"server-usage"}),onOpen:p=>ut({agentId:p,panel:"chat"}),onStart:p=>{ln(p)},onNew:()=>ut({panel:"new"}),...x===void 0?{}:{starting:x}}):null,_==="api"?i.jsx(Pb,{baseUrl:l.baseUrl,agentId:d}):null,_==="models"?oe.config===void 0?i.jsx("p",{className:"empty",children:"reading this agent's models…"}):i.jsx(Ob,{settings:oe.config.settings,secrets:oe.secrets,...oe.capabilities===void 0?{}:{resolved:oe.capabilities},...ht===void 0?{}:{busy:ht},...Ht===void 0?{}:{note:Ht},onChange:hs,onSecret:ni}):null,_==="team"&&d!==void 0?i.jsx(Jb,{lead:{id:d,name:m??d},team:oe.team,...oe.peers===void 0?{}:{peers:oe.peers},...oe.ask===void 0?{}:{ask:oe.ask},busy:ht!==void 0,onAsk:p=>Xn("delegation.ask",p?"true":"false",{confirm:!1}),...ls===void 0?{}:{owner:ls},people:Nn,onAssign:p=>{We("assign",async A=>(p===void 0?await A.unassign():await A.assign(p),await ka(A),await kt(A),p===void 0?"Now a shared agent: anyone's agent may ask it.":\`Now works for \${p}.\`))}}):null,_==="new"?i.jsxs(i.Fragment,{children:[i.jsxs("div",{className:"page-head",children:[i.jsx("h1",{children:"New agent"}),i.jsx("p",{children:"Answer the wizard's questions, or start from a template this server holds."})]}),i.jsxs("fieldset",{className:"segmented",style:{marginBottom:18},children:[i.jsx("button",{type:"button","aria-pressed":Fn==="answers",onClick:()=>za("answers"),children:"from answers"}),i.jsx("button",{type:"button","aria-pressed":Fn==="template",onClick:()=>za("template"),children:"from a template"})]})]}):null,_==="new"&&Fn==="template"?Ra===void 0?i.jsx("p",{className:"empty",children:"reading this server's templates…"}):Da!==void 0&&$t!==void 0?i.jsx(Gm,{offer:$t,answers:{},busy:!1,touched:!1,result:Da,onAnswer:()=>{},onSubmit:()=>{},onOpen:p=>{ea(void 0),ut({agentId:p,panel:"chat"})}}):i.jsx(Kb,{templates:Ra,busy:kn,...se===void 0?{}:{error:se},onCreate:p=>{(async()=>{nn(!0),re(void 0);try{ea(await c.current.createAgentFromTemplate(p)),r(await c.current.agents())}catch(A){re(Ze(A))}finally{nn(!1)}})()}}):null,_==="new"&&Fn==="answers"?$t===void 0?i.jsx("p",{className:"empty",children:"reading this server's questions…"}):i.jsx(Gm,{offer:$t,answers:An,busy:kn,touched:ai,...se===void 0?{}:{error:se},...Da===void 0?{}:{result:Da},onAnswer:(p,A)=>Kt($=>({...$,[p]:A})),onSubmit:()=>{gs()},onOpen:p=>{ea(void 0),ms(void 0),vl(!1),ut({agentId:p,panel:"chat"})}}):null,_==="keys"?i.jsx(ab,{client:c.current,baseUrl:l.baseUrl,token:l.token,agents:xt}):null,_==="people"?i.jsx(Qp,{people:Nn,assignments:dl,agents:xt,...pt===void 0?{}:{busy:pt},...Nt===void 0?{}:{note:Nt},onRegister:p=>{$e("register",async()=>{await c.current.registerParticipant(p)},qt)},onRemove:p=>{$e(\`remove:\${p}\`,async()=>{await c.current.deleteParticipant(p)},qt)},onPresence:(p,A)=>{$e(\`presence:\${p}\`,async()=>{await c.current.setPresence(p,A)},qt)},onAssign:(p,A)=>{$e(\`assign:\${p}\`,async()=>{A===void 0?await c.current.agent(p).unassign():await c.current.agent(p).assign(A)},qt)}}):null,_==="rooms"?i.jsx(Vp,{rooms:Ma,people:Nn,agents:xt,...wn===void 0?{}:{selected:wn},messages:is,skips:Il,...pt===void 0?{}:{busy:pt},...Nt===void 0?{}:{note:Nt},onSelect:Wl,onCreate:p=>{$e("room",async()=>{const A=await c.current.createConversation(p);Wl(A.id)},Pt)},onPost:(p,A,$,X)=>{$e(\`post:\${p}\`,async()=>{await c.current.postMessage(p,{text:A,authorId:$,...X.length===0?{}:{mentions:X}})},async()=>{})},onMembers:(p,A)=>{$e(\`members:\${p}\`,async()=>{await c.current.setMembers(p,A)},Pt)}}):null,_==="actions"?i.jsx(Wp,{actions:ss,...pt===void 0?{}:{busy:pt},onDecide:(p,A)=>{$e(p,async()=>(await c.current.decideAction(p,A)).status==="done"?"Ran as the owner's agent; the outcome is in the DM.":void 0,Qe)}}):null,_==="memory"?i.jsx(Ip,{scope:qe,scopes:["space",...Nn.map(p=>\`owner:\${p.id}\`),...cs.map(p=>\`project:\${p.id}\`),...qe.startsWith("owner:")||qe.startsWith("project:")||qe==="space"?[]:[qe]].filter((p,A,$)=>$.indexOf(p)===A),notes:Zn,projects:cs,agents:xt,...pt===void 0?{}:{busy:pt},...Nt===void 0?{}:{note:Nt},onScope:vt,onAdd:(p,A)=>{$e("add",async()=>{await c.current.addNote({scope:p,text:A})},hn)},onDelete:p=>{$e(p,async()=>{await c.current.deleteNote(p)},hn)},onProject:(p,A)=>{$e(\`project:\${p}\`,async()=>{await c.current.putProject(p,A)},hn)},onDeleteProject:p=>{$e(\`project:\${p}\`,async()=>{await c.current.deleteProject(p)},hn)},onSpaceWriter:p=>{$e("space-writer",async()=>(await c.current.setSpaceWriter(p),\`\${p} may write the space.\`),hn)}}):null,_==="webhooks"?i.jsx(qb,{webhooks:us,eventTypes:Cg,agents:xt,...En===void 0?{}:{secret:En},...pt===void 0?{}:{busy:pt},...Nt===void 0?{}:{note:Nt},onCreate:p=>{$e("webhook",async()=>{const A=await c.current.createWebhook(p);rs(A.secret)},st)},onDelete:p=>{$e(p,async()=>{await c.current.deleteWebhook(p)},st)},onDismissSecret:()=>rs(void 0)}):null,_==="backup"?i.jsx($b,{agents:xt,...pt===void 0?{}:{busy:pt},...Nt===void 0?{}:{note:Nt},...Oa===void 0?{}:{lastImport:Oa},onBackup:p=>{$e("backup",async()=>(ei(\`\${nt.slug}-backup-\${new Date().toISOString().slice(0,10)}.tar.gz\`,await c.current.backup(p)),"Backup downloaded."),async()=>{})},onExport:p=>{$e(\`export:\${p}\`,async()=>{const A=await c.current.agent(p).exportBundle();return ei(\`\${p}-bundle.json\`,new Blob([JSON.stringify(A,null,2)],{type:"application/json"})),\`\${p}'s bundle downloaded: \${A.files.length} files.\`},async()=>{})},onImport:(p,A,$)=>{$e(\`import:\${p}\`,async()=>{const X=JSON.parse(await A.text());en(await c.current.agent(p).importBundle(X,$))},async()=>{})}}):null,_==="files"?i.jsx(Yb,{...Cn===void 0?{}:{above:i.jsx(Gb,{template:Cn.template,values:Cn.vars,...Cn.declared===void 0?{}:{declared:Cn.declared},busy:ht==="vars",onSave:p=>{We("vars",async A=>{const $=await A.setVars(p);await Ua(A),Wn(await A.workspaceFiles().then(fe=>fe.files));const X=$.skipped.map(fe=>\`\${fe.file} (\${fe.reason})\`).join(", ");return\`\${$.rendered.length===0?"No file changed":\`Re-rendered \${$.rendered.join(", ")}\`}\${X===""?"":\`; kept \${X}\`}.\${$.reload==="pending"?" The reload waits for the running turn.":""}\`})}})},files:Bc,...In===void 0?{}:{selected:In},...ds===void 0?{}:{content:ds},...ht===void 0?{}:{busy:ht},...Ht===void 0?{}:{note:Ht},onSelect:_a,onSave:(p,A)=>{We(p,async $=>{const X=await $.putWorkspaceFile(p,A);return ct(A),Wn(await $.workspaceFiles().then(fe=>fe.files)),X.loads?X.applied?\`\${p} saved and in force.\`:\`\${p} written; not in force yet: \${X.pending?.message??""}\`:\`\${p} written, but the agent would not load with it: \${X.error?.message??""}\`})}}):null,_==="usage"?i.jsx(Ym,{report:mt,range:jn,onRange:es,loading:Fl,...m===void 0?{}:{agentName:m}}):null,_==="server-usage"?i.jsx(Ym,{report:mt,range:jn,onRange:es,loading:Fl}):null,_==="turns"?i.jsx(ax,{turns:on,hasMore:ns!==void 0,loading:_c,onMore:()=>{Vn(ns)},onOpenSession:p=>{ze(p)},replays:Oc,onReplay:p=>{bt(p.turnId,p.sessionKey)}}):null,_==="tools"?i.jsx(Op,{tools:oe.tools,...oe.catalogueTokens===void 0?{}:{catalogueTokens:oe.catalogueTokens},pinned:Co(tn("tools.pinned")),allow:Co(tn("tools.policy.allow")),deny:Co(tn("tools.policy.deny")),providers:fs,providerConfig:Lc,onProviders:p=>Xn("tools.providers",JSON.stringify(p),{confirm:!1}),...ht===void 0?{}:{busy:ht},...Ht===void 0?{}:{note:Ht},...ti===void 0?{}:{lastRefresh:ti},onPin:p=>Xn("tools.pinned",JSON.stringify(p),{confirm:!1}),onRules:(p,A)=>Xn(\`tools.policy.\${p}\`,JSON.stringify(A),{confirm:!1}),onRefresh:()=>{We("tools.refresh",async p=>{const A=await p.refreshTools();return Pn(A),A.reload==="pending"?"Catalogue fetched; the reload lands when the running turn ends.":void 0})}}):null,_==="schedules"?i.jsx(Ap,{schedules:oe.schedules,now:Date.now(),roles:Ae,recipients:C,onPreview:p=>G===void 0?Promise.reject(new Error("no agent")):G.previewSchedule(p),...ht===void 0?{}:{busy:ht},onCreate:p=>{We(String(p.id),A=>A.createSchedule(p).then(()=>{}))},onDelete:p=>{We(p,A=>A.deleteSchedule(p).then(()=>{}))},onRun:p=>{We(p,async A=>{const $=await A.runSchedule(p);return\`\${p} fired out of band as \${$.turnId} — its next scheduled run has not moved.\`})},onToggle:(p,A)=>{We(p,$=>$.updateSchedule(p,{enabled:A}).then(()=>{}))}}):null,_==="config"?oe.config===void 0?i.jsx("p",{className:"empty",children:"reading this agent's settings…"}):i.jsx(Dp,{settings:oe.config.settings,editable:oe.config.editable,...oe.config.file===void 0?{}:{file:oe.config.file},...ht===void 0?{}:{busy:ht},...Ht===void 0?{}:{note:Ht},onSet:Xn}):null,_==="channels"?i.jsx(qp,{channels:oe.channels,now:Date.now(),...d===void 0?{}:{agentUrl:\`\${l.baseUrl}/v1/agents/\${encodeURIComponent(d)}\`},actions:{onConnect:(p,A)=>{ul(p,{enabled:A})},onCredential:(p,A)=>{ul(p,{credential:A})},onUnpair:p=>{zc(p)},...Ea===void 0?{}:{busy:Ea},...Vl===void 0?{}:{note:Vl}}}):null,_==="channels"?i.jsx(Qb,{existing:oe.channels.map(p=>p.id),busy:ht==="channels",onAdd:p=>{const A=tn("channels"),$=Array.isArray(A)?A:[];Xn("channels",JSON.stringify([...$,p]),{confirm:!1})}}):null]})}):i.jsxs(i.Fragment,{children:[i.jsx("div",{className:"scroll",children:i.jsxs("div",{className:"pad",children:[se===void 0?null:i.jsx("p",{className:"row note bad",children:se}),i.jsx(V0,{state:ee,onAnswer:(p,A)=>{be(p,A)}}),i.jsx(xx,{state:ee})]})}),i.jsx(I0,{value:le,busy:ee.running,onChange:W,onSend:()=>{me()},onStop:()=>{D.current?.()},roles:Ae,...ae===void 0?{}:{role:ae},onRole:Q,images:Y,onImages:ne})]})]})]})}function xx(l){const c=T.useRef(null),o=T.useRef(!0);T.useEffect(()=>{const f=c.current?.closest(".scroll");if(f==null)return;const m=()=>{o.current=db(f)};return f.addEventListener("scroll",m,{passive:!0}),()=>f.removeEventListener("scroll",m)},[]);const r=l.state.rows.length+l.state.live.length+l.state.liveReasoning.length,d=T.useRef(0);return T.useLayoutEffect(()=>{const f=c.current,m=d.current===0;d.current=r,f!==null&&(m&&(o.current=!0),o.current&&f.scrollIntoView({block:"end"}))},[r]),i.jsx("div",{ref:c})}async function Tg(l,c){return[...(await l.messages(c,{limit:200})).messages??[]].reverse().filter(r=>r.origin===void 0&&(r.role==="user"||r.role==="assistant")&&(r.content??"")!=="").map((r,d)=>({kind:r.role==="user"?"user":"reply",id:\`h\${d}\`,text:r.content??""}))}function Co(l){return Array.isArray(l)?l.filter(c=>typeof c=="string"):[]}function Ze(l){return l instanceof xn||l instanceof Error?l.message:String(l)}async function jx(l){try{return Bg((await l.describe()).sessionScope)?(await l.sessions()).find(c=>c.head!==!1&&c.sessionKey.startsWith("owner:"))?.sessionKey:void 0}catch{return}}Yg(Gg());document.querySelector("link[rel=icon]")?.setAttribute("href",gx());const ev=document.getElementById("root");if(ev===null)throw new Error("no #root in the document");h0.createRoot(ev).render(i.jsx(T.StrictMode,{children:i.jsx(vx,{baseUrl:window.location.origin})}));
48
- `;var Qn=`<!doctype html>
48
+ `;var Gr=`<!doctype html>
49
49
  <html lang="en">
50
50
  <head>
51
51
  <meta charset="utf-8" />
@@ -72,7 +72,7 @@ hint: \${c.errorHint}\`]}),c.note===void 0?null:i.jsx("p",{className:"note",chil
72
72
  <div id="root"></div>
73
73
  </body>
74
74
  </html>
75
- `;function Yn(a){let e=2166136261;for(let d=0;d<a.length;d+=1)e^=a.charCodeAt(d),e=Math.imul(e,16777619)>>>0;return`"${e.toString(36)}-${a.length.toString(36)}"`}function Ae(a,e){return{body:a,contentType:e,etag:Yn(a)}}var cn={"/":Ae(Qn,"text/html; charset=utf-8"),"/assets/app.js":Ae(Vn,"text/javascript; charset=utf-8"),"/assets/app.css":Ae(Wn,"text/css; charset=utf-8")},Jn=Object.keys(cn);function Xn(a,e){let d=cn[a];if(d===void 0)return;let u={"content-type":d.contentType,etag:d.etag,"cache-control":"no-cache"};if(e.headers.get("if-none-match")===d.etag)return new Response(null,{status:304,headers:u});return new Response(d.body,{status:200,headers:u})}var Zn=1e6,ea=25000000,st=256,ta=128,Pe=255,na=`<!doctype html>
75
+ `;function Qr(s){let e=2166136261;for(let d=0;d<s.length;d+=1)e^=s.charCodeAt(d),e=Math.imul(e,16777619)>>>0;return`"${e.toString(36)}-${s.length.toString(36)}"`}function Ke(s,e){return{body:s,contentType:e,etag:Qr(s)}}var Qn={"/":Ke(Gr,"text/html; charset=utf-8"),"/assets/app.js":Ke(Hr,"text/javascript; charset=utf-8"),"/assets/app.css":Ke(Kr,"text/css; charset=utf-8")},Jr=Object.keys(Qn);function es(s,e){let d=Qn[s];if(d===void 0)return;let p={"content-type":d.contentType,etag:d.etag,"cache-control":"no-cache"};if(e.headers.get("if-none-match")===d.etag)return new Response(null,{status:304,headers:p});return new Response(d.body,{status:200,headers:p})}var as=1e6,rs=25000000,It=256,ss=128,He=255,is=`<!doctype html>
76
76
  <html lang="en">
77
77
  <head>
78
78
  <meta charset="utf-8">
@@ -92,19 +92,19 @@ hint: \${c.errorHint}\`]}),c.note===void 0?null:i.jsx("p",{className:"note",chil
92
92
  </script>
93
93
  </body>
94
94
  </html>
95
- `;function aa(a){let{runtime:e}=a,d=a.token,u=a.now??(()=>Date.now()),p=u();if(d===void 0&&a.allowUnauthenticated!==!0)throw new te({code:"server_token_missing",message:"createHandler was called with no token and no allowUnauthenticated.",hint:"Pass token, or pass allowUnauthenticated: true to state that this handler is mounted somewhere already protected. Defaulting to open would make the safe configuration the one you have to remember."});let m=a.running??new Map,b=a.approvals??Yr(),N=()=>a.origin!==void 0&&Se(a.origin.host),V=(i)=>N()||i.kind!=="open"&&Ce(i,"admin"),F=(i)=>{if(a.origin===void 0)return;let t=Ne(i,a.origin);return t===void 0?void 0:f(t,403)},j=(i,t)=>{if(a.origin===void 0)return t;let o=Mn(i,a.origin);if(Object.keys(o).length===0)return t;let l=new Headers(t.headers);for(let[c,h]of Object.entries(o))l.set(c,h);return new Response(t.body,{status:t.status,statusText:t.statusText,headers:l})},Z=!1,M=async()=>{if(d!==void 0||Z)return!0;return Z=await e.store.operatorKeys.liveCount()>0,Z},K=async(i,t,o)=>{if(ra(t)||!await M())return{kind:"open"};let l=await Sn({request:i,expected:d,keys:e.store.operatorKeys,claim:a.claim,pathname:t,at:u()});if(l instanceof Response)return l;if(l.kind==="claim")return l;if(o!=="open"&&!Ce(l,o))return kn(o,`${i.method} ${t}`);return l},g=new sn;g.add("GET","/v1/health",()=>w({status:"ok",version:xe,uptimeMs:u()-p,agents:e.list().length}),{capability:"open"}),g.add("GET","/v1/ready",()=>{if(e.ready)return w({status:"ready",agents:e.list().length});if(e.draining)return w({status:"draining",agents:e.list().length},503);return w({status:"starting",agents:e.list().length},503)},{capability:"open"}),g.add("GET","/v1/activity",async(i)=>{let t=i.principal;if(t.kind==="key"&&t.scope!==void 0&&(t.scope.agents!==void 0||t.scope.sessions!==void 0))return f({code:"activity_needs_unscoped_key",message:"Activity covers every agent on this server, and this key is scoped.",hint:"Call this with the server token or an operator key minted with no agents or sessions scope — it is meant for whatever suspends and wakes the process, not for a tenant."},403);return w(await e.activity(u()))},{capability:"admin"}),g.add("GET","/v1/agents",async(i)=>{let t=await Promise.all(e.list().map(async(c)=>({...xt(e,c),assignee:(await e.store.conversations.assignment(c.id))?.participantId??null}))),o=new Set(t.map((c)=>c.id)),l=(await e.store.agentState.list()).filter((c)=>!c.enabled&&!o.has(c.agentId)).map(vt);return w(oa(i.principal,[...t,...l]))},{capability:"read"}),g.add("GET","/v1/agents/:id",async(i)=>{let t=i.params.id??"";if(!e.list().some((o)=>o.id===t)&&X(i.principal,t)){let o=await e.store.agentState.get(t);if(o!==void 0&&!o.enabled)return w(vt(o));let l=a.resolveAgent?.(t);if(l!==void 0){let c=await e.diagnose(l);return w({id:t,status:c===void 0?"not_running":"failed",...c===void 0?{}:{error:c}})}}return I(e,i,async(o)=>{let l=await o.store.schedules.list(o.id),c=e.team(o.id),h=await e.store.conversations.assignment(o.id),v=await e.askPeers(o.id);return w({...xt(e,o),...h===void 0?{}:{assignedTo:{participantId:h.participantId,...h.assignedBy===void 0?{}:{assignedBy:h.assignedBy},assignedAt:h.assignedAt}},dialect:o.describe().dialect,window:o.window,capabilities:o.roles.main.capabilities,tools:o.tools.size,catalogueTokens:o.describe().catalogueTokens,skills:o.skills?.skills.length??0,schedules:l.length,...v.length===0?{}:{peers:v},...c.length===0?{}:{team:c.map((y)=>({id:y.id,task:y.task,artifact:Object.keys(y.artifact.properties)}))},warnings:[...o.warnings,...o.tools.warnings]})})},{capability:"read"}),g.add("GET","/v1/backup",async(i)=>{if(i.principal.kind==="key"&&i.principal.scope?.agents!==void 0)return f({code:"backup_requires_unscoped_key",message:"This key reaches only some agents, and a backup holds every agent's data.",hint:"Take backups with a key that has admin and no agents scope."},403);let t=(i.url.searchParams.get("include")??"").split(",").map((A)=>A.trim()).filter((A)=>A!==""),o=t.filter((A)=>A!=="home"&&!Object.hasOwn(De,A));if(o.length>0)return f({code:"backup_include_invalid",message:`include names ${o.join(", ")}, which a backup cannot add.`,hint:`Accepted: ${[...Object.keys(De),"home"].join(", ")}, comma-separated. env adds each agent's .env (its secrets), git its .git directories, home everything else in the state directory.`,field:"include"},400);let l=a.home;if(t.includes("home")&&l===void 0)return f({code:"backup_home_unavailable",message:"include=home asks for the state directory, and this server was not given one.",hint:"`serve` passes it; a handler embedded elsewhere sets HandlerOptions.home. The store and agent directories are backed up without it.",field:"include"},400);let c=new Set(fa);for(let A of t)for(let q of De[A]??[])c.delete(q);let h=await gn(Ue(bn(),"backup-")),v=Ue(h,"store.db");await e.store.snapshot(v);let y=[{name:"store.db",source:{path:v}}],k=[];for(let A of e.list()){let q=await jt(A.dir,c);for(let P of q)y.push({name:`agents/${A.id}/${P.name}`,source:{bytes:await Le(P.path)}});k.push({id:A.id,dir:A.dir,files:q.length})}let _;if(t.includes("home")&&l!==void 0){let A=new Set(e.list().map((W)=>he(W.dir))),q=(...W)=>he(l,...W),P=new Set([...A,q("logs"),q("sources"),...["","-wal","-shm","-journal"].map((W)=>q(`store.db${W}`))]),Q=await jt(l,c,P);for(let W of Q)y.push({name:`home/${W.name}`,source:{path:W.path}});_=Q.length}let C={createdAt:new Date().toISOString(),version:xe,agents:k,included:t,..._===void 0?{}:{home:{dir:l,files:_}},excluded:[...c]};y.unshift({name:"backup.json",source:{bytes:new TextEncoder().encode(`${JSON.stringify(C,null,2)}
96
- `)}});let U=C.createdAt.replace(/[:.]/g,"-");return new Response(qn(y,()=>yn(h,{recursive:!0,force:!0})),{headers:{"content-type":"application/gzip","content-disposition":`attachment; filename="backup-${U}.tar.gz"`}})},{capability:"admin"}),g.add("GET","/v1/agents/:id/export",(i)=>I(e,i,async(t)=>{let o=await ee(i.principal);if(o!==void 0)return o;let l=i.url.searchParams.get("paths");try{let c=_s(l===null?void 0:l.split(",").map((h)=>h.trim()));return w(ks(t,c))}catch(c){return O(c)}}),{capability:"admin"}),g.add("POST","/v1/agents/:id/import",(i)=>I(e,i,async(t)=>{let o=await ee(i.principal);if(o!==void 0)return o;let l=await z(i.request,ea);if(l.kind==="error")return f(l.error,400);let c=B(Xt,l.value);if(!c.ok)return f(c.error,400);try{let h=await vs({agent:t,bundle:c.value.bundle,...c.value.mode===void 0?{}:{mode:c.value.mode},reload:async()=>(await e.reload(t.id)).status});return w({id:t.id,...h})}catch(h){return O(h)}}),{capability:"admin"}),g.add("GET","/v1/agents/:id/vars",(i)=>ue(e,a,i,async(t)=>{let o=a.provision?.templateOf;if(o===void 0)return f({code:"rerender_not_supported",message:"This server cannot read an agent's template record.",hint:"`serve` provides it; an embedder mounting this handler has no templates directory."},501);let l=o(t.agent?.dir??be(t.file??""));if(l===void 0)return f({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0 or later carries one. Edit its files directly instead."},409);return w({id:t.id,template:l.template,vars:l.vars})}),{capability:"admin"}),g.add("PATCH","/v1/agents/:id/vars",(i)=>ue(e,a,i,async(t)=>{let o=a.provision?.rerender;if(o===void 0)return f({code:"rerender_not_supported",message:"This server cannot re-render an agent's template.",hint:"`serve` provides it; an embedder mounting this handler has no templates directory. Edit the files and POST /reload instead."},501);if(!V(i.principal))return f({code:"provisioning_not_local",message:"Re-rendering an agent's files needs either a loopback bind or a credential with the admin capability.",hint:"It writes the agent's files, like creating one. Present the server's token or an operator key minted with `can: [admin]`."},403);let l=await z(i.request);if(l.kind==="error")return f(l.error,400);let c=B(Ct,l.value);if(!c.ok)return f(c.error,400);let h;try{h=o({agentDir:t.agent?.dir??be(t.file??""),vars:c.value.vars})}catch(y){if(T(y))return f(y.toDetail(),y.code==="agent_not_from_template"?409:400);throw y}let v=(y,k=200)=>w({id:t.id,rendered:h.rendered,skipped:h.skipped,reload:y},k);if(h.rendered.length===0)return v("none");if(t.agent===void 0)return v("none");try{let y=await e.reload(t.id);return v(y.status,y.status==="pending"?202:200)}catch(y){if(h.undo(),T(y))return f(y.toDetail(),400);throw y}}),{capability:"admin"}),g.add("GET","/v1/agents/:id/workspace",(i)=>ue(e,a,i,async(t)=>{let o=t.file;if(o===void 0)return w({id:t.id,files:[]});let l=await Oe(t.id,o);if(l instanceof Response)return l;return w({id:t.id,files:l.declared.map((c)=>({name:ye(c.path),tier:c.tier,field:c.field,exists:fe(c.path),bytes:fe(c.path)?mn(c.path).size:0}))})}),{capability:"admin"}),g.add("GET","/v1/agents/:id/workspace/:file",(i)=>ue(e,a,i,async(t)=>{let o=t.file,l=i.params.file??"";if(o===void 0)return ze(t.id,l,[]);let c=await Oe(t.id,o);if(c instanceof Response)return c;let h=wt(c.declared,c.workspaceDir,l);if(h===void 0)return ze(t.id,l,c.declared);let v=c.declared.find((y)=>y.path===h);return w({id:t.id,file:ye(h),...v===void 0?{}:{tier:v.tier,field:v.field},exists:fe(h),content:fe(h)?Ve(h,"utf8"):""})}),{capability:"admin"}),g.add("PUT","/v1/agents/:id/workspace/:file",(i)=>ue(e,a,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Et,o.value);if(!l.ok)return f(l.error,400);let c=t.file;if(c===void 0)return f({code:"config_not_editable",message:`"${t.id}" was loaded from an object, so it has no files to write.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt()."},409);let h=await Oe(t.id,c);if(h instanceof Response)return h;let{workspaceDir:v,declared:y}=h,k=i.params.file??"",_=wt(y,v,k);if(_===void 0)return ze(t.id,k,y);let C=fe(_)?Ve(_,"utf8"):void 0;hn(be(_),{recursive:!0}),Qe(_,l.value.content,"utf8");let U=ye(_);if(t.agent===void 0){let A=await e.diagnose(c);return w({id:t.id,file:U,written:!0,loads:A===void 0,...A===void 0?{}:{error:A},applied:!1,pending:yt(t.id)})}try{let A=await e.reload(t.id);return w({id:t.id,file:U,written:!0,loads:!0,...A.status==="pending"?{applied:!1,pending:ke(A)}:{applied:!0}})}catch(A){if(C===void 0)fn(_,{force:!0});else Qe(_,C,"utf8");if(T(A))return f(A.toDetail(),400);throw A}}),{capability:"admin"}),g.add("POST","/v1/agents/:id/tools/refresh",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(_t,o.value);if(!l.ok)return f(l.error,400);try{let c=await e.refreshTools(t.id,{...l.value.providers===void 0?{}:{providers:l.value.providers}});return w({id:t.id,...c},c.reload==="pending"?202:200)}catch(c){if(T(c))return f(c.toDetail(),c.code==="agent_turn_in_flight"?409:400);throw c}}),{capability:"admin"}),g.add("POST","/v1/agents/:id/reload",(i)=>I(e,i,async(t)=>{try{let o=await e.reload(t.id);if(o.status==="pending")return w({id:t.id,status:"pending",adopted:[],running:o.running,holdAfterMs:o.holdAfterMs},202);return w({id:t.id,status:"loaded",adopted:o.adopted.map((l)=>l.id)})}catch(o){if(T(o))return f({code:o.code,message:o.message,hint:o.hint,...o.field===void 0?{}:{field:o.field}},o.code==="agent_turn_in_flight"?409:400);throw o}}),{capability:"admin"}),g.add("GET","/v1/openapi.json",(i)=>w(zn({routes:g.routes(),serverUrl:`${i.url.protocol}//${i.url.host}`})),{capability:"open"}),g.add("GET","/docs",()=>new Response(na,{status:200,headers:{"content-type":"text/html; charset=utf-8"}}),{capability:"open"}),g.add("GET","/v1/provision",(i)=>w({available:a.provision!==void 0,local:N(),allowed:V(i.principal),steps:a.provision?.steps()??[]}),{capability:"read"}),g.add("POST","/v1/agents",async(i)=>{let t=a.provision;if(t===void 0)return f({code:"provisioning_not_supported",message:"This server cannot create agents.",hint:"Creating one writes a directory of files from a question set this process was not given — an embedder mounting this handler over its own agent store is the case that lands here. Run `init` where the sandbox is, or mount an agent directory."},501);if(!V(i.principal))return f({code:"provisioning_not_local",message:"Creating an agent needs either a loopback bind or a credential with the admin capability.",hint:"This route writes files and starts an agent. A token-less loopback server is a supported configuration, so on a non-loopback bind it asks for a credential instead — set server.tokenEnv (the container's DISPACH_API_TOKEN does this) or present an operator key minted with `can: [admin]`. What is refused is provisioning on a server that required no credential at all and is reachable from the network."},403);let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Mt,o.value);if(!l.ok)return f(l.error,400);let{answers:c,template:h}=l.value;if(c!==void 0&&h!==void 0)return f({code:"provision_body_ambiguous",message:"The body has both answers and a template.",hint:"Send answers to create an agent the way init does, or template with name and vars to create one from a template in this server's sandbox. Not both.",field:"template"},400);if(c===void 0&&h===void 0)return f({code:"provision_answers_required",message:"The body has neither answers nor a template.",hint:'Send { "answers": { "name": "milo", … } } (GET /v1/provision lists the steps), or { "template": "…", "name": "…", "vars": {…} } (GET /v1/templates lists the templates).',field:"answers"},400);let v;try{v=h===void 0?t.create(c??{}):t.createFromTemplate({template:h,name:l.value.name??"",vars:l.value.vars??{}})}catch(y){if(T(y))return f(y.toDetail(),400);throw y}try{if(h===void 0)await t.claim?.(v.manifestPath);let y=await e.adopt(v.manifestPath);return w({id:v.agentId,dir:v.dir,files:v.files,adopted:y.map((k)=>k.id)},201)}catch(y){return w({id:v.agentId,dir:v.dir,files:v.files,adopted:[],error:T(y)?y.toDetail():je("provision_adopt_failed","The agent was written and is not running. Fix what the server's log names and `start` it, or restart the host.",y)},201)}},{capability:"admin"}),g.add("GET","/v1/templates",()=>w({templates:a.provision?.templates()??[]}),{capability:"read"}),g.add("GET","/v1/agents/:id/secrets",async(i)=>{let t=dt(e,a,i);if(t.kind==="response")return t.response;return w({id:t.id,secrets:t.admin.status(t.manifestPath)})},{capability:"admin"}),g.add("PUT","/v1/agents/:id/secrets",async(i)=>{let t=dt(e,a,i);if(t.kind==="response")return t.response;let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(tn,o.value);if(!l.ok)return f(l.error,400);let c;try{c=t.admin.write(t.manifestPath,l.value.values)}catch(k){if(T(k))return f(k.toDetail(),400);throw k}let h={id:t.id,written:c.written,shadowed:c.shadowed},v=e.list().some((k)=>k.id===t.id),y=await e.store.agentState.get(t.id);if(!v&&y?.enabled===!1)return w({...h,applied:"none",adopted:[],stopped:!0});try{if(v){let _=await e.reload(t.id);if(_.status==="pending")return w({...h,applied:"pending",adopted:[]});return w({...h,applied:"reloaded",adopted:_.adopted.map((C)=>C.id)})}let k=await e.adopt(t.manifestPath);return w({...h,applied:"adopted",adopted:k.map((_)=>_.id)})}catch(k){return w({...h,applied:"none",adopted:[],error:T(k)?k.toDetail():je("secrets_apply_failed","The values were written and the agent is not running on them yet. Fix what the server's log names and reload or start it.",k)})}},{capability:"admin"}),g.add("POST","/v1/agents/:id/stop",async(i)=>{let t=i.params.id??"";if(!X(i.principal,t))return H("agent",t);let o=e.list().some((k)=>k.id===t),l=await e.store.agentState.get(t);if(!o&&l===void 0)return H("agent",t);let c=await z(i.request);if(c.kind==="error")return f(c.error,400);let h=B(Rt,c.value);if(!h.ok)return f(h.error,400);let v=h.value.reason?.trim(),y=await e.store.agentState.disable(t,new Date(a.now?.()??Date.now()).toISOString(),v===void 0||v===""?void 0:v);if(o)try{await e.dispose(t,"stopped")}catch(k){if(T(k)&&k.code==="agent_turn_in_flight")return f(k.toDetail(),409);throw k}return w({id:t,status:"disabled",...Re(y)})},{capability:"admin"}),g.add("POST","/v1/agents/:id/start",async(i)=>{let t=i.params.id??"";if(!X(i.principal,t))return H("agent",t);if(e.list().some((h)=>h.id===t)){let h=await e.store.agentState.enable(t);return w({id:t,status:"loaded",...Re(h)})}let o=a.resolveAgent;if(o===void 0)return f({code:"start_not_supported",message:"This server cannot look up a manifest for an agent it is not hosting.",hint:"Starting a stopped agent needs its manifest, which lives wherever agents live — the sandbox for the CLI, a mounted path for a container. This process was built without that lookup, so pass the agent to `serve` and restart it instead."},501);let l=o(t);if(l===void 0)return H("agent",t);let c=await e.store.agentState.enable(t);try{let h=await e.adopt(l);return w({id:t,status:"loaded",...Re(c),adopted:h.map((v)=>v.id)})}catch(h){if(await e.store.agentState.disable(t,new Date(a.now?.()??Date.now()).toISOString(),"start failed"),T(h))return f(h.toDetail(),400);throw h}},{capability:"admin"}),g.add("DELETE","/v1/agents/:id",async(i)=>{let t=i.params.id??"";if(!X(i.principal,t))return H("agent",t);let o=e.list().some((y)=>y.id===t),l=await e.store.agentState.get(t),c=a.remover;if(c===void 0)return f({code:"agent_remove_unsupported",message:"This server cannot delete agents.",hint:"`serve` provides deletion; an embedded handler has no sandbox to delete from. Use the CLI's `remove`."},501);if(i.url.searchParams.get("confirm")!==t)return f({code:"agent_remove_unconfirmed",message:`Deleting ${t} needs ?confirm=${t}.`,hint:"It deletes the agent's conversations, memory and files for good, so the request names the agent twice. POST /v1/agents/:id/stop switches one off and keeps everything.",field:"confirm"},400);let h=c.locate(t);if(!h.ok){if(!o&&l===void 0&&h.status===404)return H("agent",t);return f(h.error,h.status)}if(o)try{await e.dispose(t,"stopped")}catch(y){if(T(y))return f(y.toDetail(),409);throw y}let v=await e.store.purgeAgent(t);return await c.deleteDir(h.dir),w({id:t,removed:!0,dir:h.dir,...v})},{capability:"admin"}),g.add("POST","/v1/agents/:id/deliveries",async(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(At,o.value);if(!l.ok)return f(l.error,400);let c=l.value;if(!e.channels.hasChannel(t.id,c.channel))return f({code:"delivery_channel_unknown",message:`${t.id} has no running channel "${c.channel}".`,hint:"Name a channel id from the agent's manifest (GET /v1/agents/:id lists them with their status). A disabled channel is not running and cannot send.",field:"channel"},404);let h=qr({channel:c.channel,peerId:c.to}),v=le(i,h);if(v!==void 0)return v;let{inserted:y}=await e.channels.deliver({agentId:t.id,sessionKey:h,channelId:c.channel,recipient:c.to,text:c.text,key:c.key});if(y)await t.recordDelivered(c.text,{sessionKey:h});return w({sessionKey:h,key:c.key,duplicate:!y},202)}),{capability:"admin"}),g.add("POST","/v1/agents/:id/messages",async(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Tt,o.value);if(!l.ok)return f(l.error,400);let c=l.value,h=c.chunks===!0,v=c.text,y=c.sessionKey??"api:default",k=le(i,y);if(k!==void 0)return k;let _=ua(c.deliver);if(_.kind==="error")return f(_.error,400);let C=Me(c.from);if(C.kind==="error")return f(C.error,400);let U=we(i.principal,C.from);if(!U.ok)return f(U.error,403);let A=await Be(t,i.principal,y,U.from,c.peerAsk),q=ca(i.request);if(q.kind==="error")return f(q.error,400);if(c.runtimeNote!==void 0&&U.from?.kind==="agent")return f({code:"message_note_untrusted",message:"A message from an agent cannot carry a runtimeNote.",hint:"A note is trusted framing outside the fence a peer's text is shown in. Put what the peer has to say in text.",field:"runtimeNote"},400);if(c.role!==void 0)try{t.roles.byName(c.role)}catch(ae){if(T(ae))return f({...ae.toDetail(),field:"role"},400);throw ae}let P=[];if(c.images!==void 0&&c.images.length>0){let ae=t.refusesImages(c.role);if(ae!==void 0)return f(ae.toDetail(),400);try{P=await ms(t.dir,c.images)}catch(oe){if(T(oe))return f(oe.toDetail(),400);throw oe}}let Q=await t.admit();if(!Q.ok)return f(Q.error.toDetail(),429);let W=so();if(q.key!==void 0){let ae=await t.store.turns.claimInboundKey({agentId:t.id,key:q.key,turnId:W,inputHash:await da(A,P.length===0?v:`${v}
97
- ${P.map((oe)=>oe.data).join(`
98
- `)}`),now:new Date});if(ae.kind!=="claimed")Q.release();if(ae.kind==="replay")return w({turnId:ae.turnId,sessionKey:A,replayed:!0},200);if(ae.kind==="mismatch")return f({code:"idempotency_key_reused",message:`Idempotency-Key "${q.key}" was already used for a different message.`,hint:`It belongs to turn ${ae.turnId}, whose text or session differed from this request's. Nothing was run. Use a fresh key for a new message, or resend the original text byte for byte to get that turn back. A key is remembered for 24 hours.`,field:"Idempotency-Key"},409)}let qe=new AbortController;m.set(W,qe),e.streams.open(W,{chunks:h});let va=t.send(v,{admission:Q,sessionKey:A,sessionResolved:!0,turnId:W,source:"api",...U.from===void 0?{}:{from:U.from},...P.length===0?{}:{images:P},...c.runtimeNote===void 0?{}:{turnNote:c.runtimeNote},...c.role===void 0?{}:{role:c.role},...c.peerAsk===void 0?{}:{peerAsk:c.peerAsk},signal:qe.signal}).then(async(ae)=>{let oe=ae.attachments??[];if(_.target===void 0||ae.text.trim()===""&&oe.length===0)return;await e.channels.deliver({agentId:t.id,sessionKey:A,channelId:_.target.channel,recipient:_.target.to,turnId:W,text:ae.text,...oe.length===0?{}:{attachments:oe}})}).catch(()=>{}).finally(()=>{m.delete(W)});if(c.stream!==!0)return w({turnId:W,sessionKey:A},202);return kt(e,W,{accepted:{turnId:W,sessionKey:A},status:202,chunks:h,children:c.children===!0})}),{capability:"chat"}),g.add("GET","/v1/agents/:id/turns/:turnId/stream",(i)=>I(e,i,async(t)=>{let o=i.params.turnId??"",l=await t.store.turns.get(o);if(bt(i,l))return H("turn",o);if(e.streams.state(o)===void 0){if(l===void 0)return H("turn",o,"No turn with this id has ever run on this agent. A turn id is the `turnId` from POST /v1/agents/:id/messages — check the agent in the path too, since a turn belongs to one.");return pa(l)}return kt(e,o,{chunks:i.url.searchParams.get("chunks")==="true",children:i.url.searchParams.get("children")==="true"})}),{capability:"read",streaming:!0}),g.add("POST","/v1/agents/:id/turns/:turnId/stop",(i)=>I(e,i,async(t)=>{let o=i.params.turnId??"";if(bt(i,await t.store.turns.get(o)))return H("turn",o);let l=m.get(o);if(l===void 0)return f({code:"turn_not_running",message:`No cancel handle for turn ${o} on this API.`,hint:"This surface can stop a turn it started. A turn that has already finished cannot be stopped at all — read its final state from GET /v1/agents/:id/turns/:turnId. A turn started by a channel, a schedule, or another process is running without a handle here."},409);return l.abort(),w({turnId:o,stopping:!0},202)}),{capability:"chat"}),g.add("GET","/v1/agents/:id/approvals",(i)=>I(e,i,async(t)=>w({approvals:$e(i.principal,b.pending(t.id))})),{capability:"read"}),g.add("POST","/v1/agents/:id/approvals/:approvalId",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Pt,o.value);if(!l.ok)return f(l.error,400);let c=l.value,h=i.params.approvalId??"";if(!$e(i.principal,b.pending(t.id)).some((y)=>y.approvalId===h)||!b.resolve(h,c.granted))return f({code:"approval_not_found",message:`No approval with id ${h} is waiting.`,hint:'It was answered already, or its turn ended while it waited — a stopped or timed-out turn abandons its question, and `approval.resolved` reports that as `by: "abandoned"`. GET /v1/agents/:id/approvals lists what is actually waiting. Nothing about a settled approval is kept, so this is also the answer for an id that was never real.'},404);return w({approvalId:h,granted:c.granted})}),{capability:"chat"}),g.add("GET","/",(i)=>Ie("/",i),{capability:"open"}),g.add("GET","/assets/app.js",(i)=>Ie("/assets/app.js",i),{capability:"open"}),g.add("GET","/assets/app.css",(i)=>Ie("/assets/app.css",i),{capability:"open"}),g.add("POST","/v1/keys",async(i)=>{let t=a.claim!==void 0&&ia(i.request)===a.claim.token,o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(It,o.value);if(!l.ok)return f(l.error,400);let c=l.value,h=ys(c.label);if(h!==void 0)return f({code:"key_label_invalid",message:h,hint:`A label is shown in a listing and in the UI, so it is at most ${Br} printable characters on one line. It is a display name, not a description.`,field:"label"},400);if(t&&a.claim?.spend()!==!0)return St();let v=c.scope;if(v?.agents!==void 0){let U=new Set(e.list().map((q)=>q.id));for(let q of await e.store.agentState.list())U.add(q.agentId);let A=v.agents.filter((q)=>!U.has(q));if(A.length>0)return f({code:"key_scope_agent_unknown",message:`No agent ${A.map((q)=>JSON.stringify(q)).join(", ")} on this server.`,hint:"A key scoped to an agent that does not exist authenticates and then reaches nothing, which looks exactly like a working credential until it is used. GET /v1/agents lists what this server holds, stopped agents included.",field:"scope.agents"},400)}let y=v?.expiresIn===void 0?void 0:new Date(u()+v.expiresIn*1000).toISOString(),k=v===void 0?void 0:{...v.agents===void 0?{}:{agents:v.agents},...v.sessions===void 0?{}:{sessions:v.sessions},...v.can===void 0?{}:{can:v.can},...v.participant===void 0?{}:{participant:v.participant}},_=fr(),C=await e.store.operatorKeys.issue({keyId:ws(u()),label:c.label.trim(),fingerprint:await hr(_),createdAt:new Date(u()).toISOString(),...k===void 0||Object.keys(k).length===0?{}:{scope:k},...y===void 0?{}:{expiresAt:y}});return w({...C,secret:_},201)},{capability:"admin"}),g.add("GET","/v1/keys",async()=>{let i=await e.store.operatorKeys.list();return w({keys:i,scope:"A key with no scope authenticates every route for every agent this server holds. A scope narrows an already-authenticated caller — it names agents, a session prefix and capabilities, and it is not an identity: there are no users, teams or roles here."})},{capability:"admin"}),g.add("DELETE","/v1/keys/:keyId",async(i)=>{let t=i.params.keyId??"",o=await e.store.operatorKeys.revoke(t,new Date(u()).toISOString());if(o===void 0)return H("key",t,"The id is the `keyId` from POST /v1/keys, not the secret — GET /v1/keys lists them. An already-revoked key is a 200 carrying its original stamp, so this really does mean no such key exists.");return w(o)},{capability:"admin"}),g.add("POST","/v1/webhooks",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(en,t.value);if(!o.ok)return f(o.error,400);let l=o.value,c=l.types.filter((C)=>!Jt.includes(C)||!Ps(C));if(c.length>0)return f({code:"webhook_type_invalid",message:`Cannot deliver ${c.join(", ")}.`,hint:"Any type from the event stream except model.chunk, which is one request per token. The wire spec's event table lists them.",field:"types"},400);let h=ve(i.principal);if(l.agents!==void 0){let C=new Set([...e.list().map((A)=>A.id),...(await e.store.agentState.list()).map((A)=>A.agentId)]),U=l.agents.filter((A)=>!X(i.principal,A)||!C.has(A));if(U.length>0)return f({code:"webhook_scope_invalid",message:`This credential cannot subscribe to ${U.join(", ")}.`,hint:"A subscription hears at most what the key creating it reaches, and only agents this server holds. GET /v1/agents lists them.",field:"agents"},400)}let v=l.agents??h.agentIds,y={...v===void 0?{}:{agents:[...v]},...h.sessionPrefix===void 0?{}:{sessionPrefix:h.sessionPrefix}};try{await e.webhooks.check(l.url)}catch(C){if(T(C))return f(C.toDetail(),400);throw C}let k=Ls(),_=await e.store.webhooks.create({subscriptionId:`wh_${crypto.randomUUID().replaceAll("-","").slice(0,20)}`,url:l.url,secret:k,types:[...new Set(l.types)],...Object.keys(y).length===0?{}:{scope:y},createdAt:new Date(a.now?.()??Date.now()).toISOString()});return await e.webhooks.changed(),w({...ut(_),secret:k},201)},{capability:"admin"}),g.add("GET","/v1/webhooks",async(i)=>{let t=await e.store.webhooks.list();return w({webhooks:t.filter((o)=>ht(i.principal,o)).map(ut)})},{capability:"admin"}),g.add("DELETE","/v1/webhooks/:webhookId",async(i)=>{let t=i.params.webhookId??"",o=await e.store.webhooks.get(t);if(o===void 0||!ht(i.principal,o))return f({code:"webhook_not_found",message:`No webhook with id "${t}".`,hint:"GET /v1/webhooks lists the subscriptions this credential can see."},404);return await e.store.webhooks.delete(t),await e.webhooks.changed(),w({id:t,deleted:!0})},{capability:"admin"});let L=(i)=>i.kind==="key"?i.scope?.participant:void 0,Y=(i,t)=>{let o=L(i);if(o!==void 0&&!t.members.includes(o))return!1;return t.members.every((l)=>{let c=ni(l);return c===void 0||X(i,c)})},re=(i)=>f({code:"conversation_not_found",message:`No conversation "${i}".`,hint:"GET /v1/conversations lists the ones this credential can see."},404),J=async(i,t)=>{let o=i.params.conversationId??"",l=await e.store.conversations.get(o);if(l===void 0||!Y(i.principal,l))return re(o);return t(l)},O=(i)=>{if(!T(i))throw i;return f(i.toDetail(),i.code.endsWith("_not_found")?404:i.code.endsWith("_forbidden")?403:400)};g.add("POST","/v1/participants",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(Lt,t.value);if(!o.ok)return f(o.error,400);try{let l=o.value;return w(await e.conversations.registerParticipant({id:l.id,...l.name===void 0?{}:{name:l.name},...l.role===void 0?{}:{role:l.role},...l.title===void 0?{}:{title:l.title},...l.timezone===void 0?{}:{timezone:l.timezone},...l.channelIds===void 0?{}:{channelIds:l.channelIds}}),201)}catch(l){return O(l)}},{capability:"admin"}),g.add("GET","/v1/participants",async()=>w({participants:await e.store.conversations.participants()}),{capability:"read"}),g.add("DELETE","/v1/participants/:participantId",async(i)=>{let t=i.params.participantId??"";if(!await e.store.conversations.deleteParticipant(t))return f({code:"participant_not_found",message:`No participant "${t}".`,hint:"GET /v1/participants lists them."},404);return w({id:t,deleted:!0})},{capability:"admin"}),g.add("POST","/v1/conversations",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(Ut,t.value);if(!o.ok)return f(o.error,400);let l=L(i.principal);if(l!==void 0&&!o.value.members.includes(l))return f({code:"conversation_creator_not_member",message:`This key speaks for ${l}, who is not among the members.`,hint:`Include "${l}" in members. A backend creating rooms for others needs a key minted without scope.participant.`,field:"members"},403);let c=o.value.members.map((h)=>ni(h)).filter((h)=>h!==void 0&&!X(i.principal,h));if(c.length>0)return f({code:"conversation_member_unknown",message:`No participant "agent:${c[0]}".`,hint:"That agent is not hosted here. GET /v1/agents lists the ones that are.",field:"members"},400);try{return w(await e.conversations.create({kind:o.value.kind,members:o.value.members,...o.value.title===void 0?{}:{title:o.value.title}}),201)}catch(h){return O(h)}},{capability:"admin"}),g.add("GET","/v1/conversations",async(i)=>{let t=await e.store.conversations.list();return w({conversations:t.filter((o)=>Y(i.principal,o))})},{capability:"read"}),g.add("GET","/v1/conversations/:conversationId",(i)=>J(i,async(t)=>w(t)),{capability:"read"}),g.add("PATCH","/v1/conversations/:conversationId/members",(i)=>J(i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Bt,o.value);if(!l.ok)return f(l.error,400);try{return w(await e.conversations.setMembers(t.id,l.value.add??[],l.value.remove??[]))}catch(c){return O(c)}}),{capability:"admin"}),g.add("POST","/v1/conversations/:conversationId/messages",(i)=>J(i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Ft,o.value);if(!l.ok)return f(l.error,400);let c=L(i.principal),h=l.value.authorId;if(c!==void 0&&h!==void 0&&h!==c)return f({code:"sender_not_bound_participant",message:`This key speaks for ${c}, and the message names ${h}.`,hint:`Omit authorId (it is filled in), or send "${c}". A backend that posts for others needs a key minted without scope.participant.`,field:"authorId"},403);let v=c??h;if(v===void 0)return f({code:"conversation_author_required",message:"A message needs an author.",hint:"Send authorId, the human member who said it. A key bound to a participant fills it in.",field:"authorId"},400);try{let y=await e.conversations.post({conversationId:t.id,authorId:v,text:l.value.text,...l.value.mentions===void 0?{}:{mentions:l.value.mentions}});return w(y,202)}catch(y){return O(y)}}),{capability:"chat"}),g.add("GET","/v1/conversations/:conversationId/messages",(i)=>J(i,async(t)=>{let o=Number(i.url.searchParams.get("after")??0),l=Number(i.url.searchParams.get("limit")??200),c=await e.store.conversations.messages(t.id,{after:Number.isFinite(o)&&o>0?o:0,limit:Number.isFinite(l)&&l>0?Math.min(l,500):200});return w({conversationId:t.id,messages:c,...c.length===0?{}:{nextAfter:c.at(-1)?.seq}})}),{capability:"read"}),g.add("PUT","/v1/participants/:participantId/presence",async(i)=>{let t=i.params.participantId??"",o=L(i.principal);if(o!==void 0&&o!==t)return f({code:"sender_not_bound_participant",message:`This key speaks for ${o}, and the presence names ${t}.`,hint:"A key bound to a participant sets only that participant's presence. The embedder's backend, holding an unbound key, sets anyone's."},403);let l=await z(i.request);if(l.kind==="error")return f(l.error,400);let c=B(qt,l.value);if(!c.ok)return f(c.error,400);try{return w(await e.conversations.setPresence(t,c.value.presence))}catch(h){return O(h)}},{capability:"chat"}),g.add("GET","/v1/actions",async(i)=>{let t=i.url.searchParams.get("status"),o=L(i.principal),l=await e.store.conversations.actions({...o===void 0?{}:{ownerId:o},...t==="pending"||t==="done"||t==="failed"||t==="denied"?{status:t}:{}});return w({actions:l.filter((c)=>X(i.principal,c.agentId))})},{capability:"read"}),g.add("POST","/v1/actions/:actionId",async(i)=>{let t=i.params.actionId??"",o=await e.store.conversations.action(t),l=L(i.principal);if(o===void 0||!X(i.principal,o.agentId)||l!==void 0&&l!==o.ownerId)return f({code:"action_not_found",message:`No action "${t}".`,hint:"GET /v1/actions lists the ones waiting on you."},404);let c=await z(i.request);if(c.kind==="error")return f(c.error,400);let h=B(Zt,c.value);if(!h.ok)return f(h.error,400);try{return w(await e.conversations.decideAction(t,h.value.approve))}catch(v){if(T(v)&&v.code==="action_already_decided")return f(v.toDetail(),409);return O(v)}},{capability:"chat"}),g.add("PUT","/v1/agents/:id/assignee",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Gt,o.value);if(!l.ok)return f(l.error,400);let c=L(i.principal);if(c!==void 0){if((await e.store.conversations.participant(c))?.role!=="admin")return f({code:"assignment_requires_admin",message:`${c} is not an admin participant.`,hint:'Only a participant registered with role "admin" assigns agents to members.'},403)}try{let h=await e.conversations.assign({agentId:t.id,participantId:l.value.participantId,...c===void 0?{}:{assignedBy:c},...l.value.channelIds===void 0?{}:{channelIds:l.value.channelIds}});return await t.checkSessionScope(),w(h)}catch(h){return O(h)}}),{capability:"admin"}),g.add("GET","/v1/agents/:id/assignee",(i)=>I(e,i,async(t)=>w({id:t.id,assignment:await e.store.conversations.assignment(t.id)??null})),{capability:"read"}),g.add("DELETE","/v1/agents/:id/assignee",(i)=>I(e,i,async(t)=>{let o=await e.store.conversations.unassign(t.id);if(o)e.schedulePeerCheck();return await t.checkSessionScope(),w({id:t.id,unassigned:o})}),{capability:"admin"});let se=(i)=>{let t=L(i);if(t!==void 0||Ce(i,"admin"))return{ok:!0,actor:t};return{ok:!1,response:f({code:"memory_write_requires_admin",message:"This key is bound to no participant and does not carry admin.",hint:"A member writes through a key minted with scope.participant; the embedder's backend writes shared scopes with an admin key."},403)}};g.add("POST","/v1/memory/notes",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(Wt,t.value);if(!o.ok)return f(o.error,400);let l=se(i.principal);if(!l.ok)return l.response;try{return w(await e.conversations.addNote({scope:o.value.scope,text:o.value.text,...l.actor===void 0?{}:{authorId:l.actor}}),201)}catch(c){return O(c)}},{capability:"chat"}),g.add("GET","/v1/memory/notes",async(i)=>{let t=i.url.searchParams.get("scope")??"";try{return w({notes:await e.conversations.notes(t,L(i.principal))})}catch(o){return O(o)}},{capability:"read"}),g.add("DELETE","/v1/memory/notes/:noteId",async(i)=>{let t=se(i.principal);if(!t.ok)return t.response;try{return await e.conversations.deleteNote(i.params.noteId??"",t.actor),w({id:i.params.noteId,deleted:!0})}catch(o){return O(o)}},{capability:"chat"}),g.add("GET","/v1/participants/:participantId/memory/reads",async(i)=>{try{return w({reads:await e.conversations.reads(i.params.participantId??"",L(i.principal))})}catch(t){return O(t)}},{capability:"read"});let ee=async(i)=>{let t=L(i);if(t===void 0)return;if((await e.store.conversations.participant(t))?.role==="admin")return;return f({code:"memory_scope_forbidden",message:`${t} is not an admin participant.`,hint:'Only a participant registered with role "admin" defines projects and names the space writer.'},403)};g.add("GET","/v1/projects",async()=>w({projects:await e.store.conversations.projects()}),{capability:"read"}),g.add("PUT","/v1/projects/:projectId",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(Vt,t.value);if(!o.ok)return f(o.error,400);let l=await ee(i.principal);if(l!==void 0)return l;let c=(o.value.agents??[]).find((h)=>!X(i.principal,h));if(c!==void 0)return f({code:"agent_not_found",message:`No agent "${c}".`,hint:"GET /v1/agents lists the ones hosted here."},404);try{return w(await e.conversations.upsertProject({id:i.params.projectId??"",...o.value.name===void 0?{}:{name:o.value.name},...o.value.agents===void 0?{}:{agents:o.value.agents}}))}catch(h){return O(h)}},{capability:"admin"}),g.add("DELETE","/v1/projects/:projectId",async(i)=>{let t=await ee(i.principal);if(t!==void 0)return t;let o=i.params.projectId??"";return w({id:o,deleted:await e.store.conversations.deleteProject(o)})},{capability:"admin"}),g.add("PUT","/v1/memory/space/writer",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o=B(Qt,t.value);if(!o.ok)return f(o.error,400);let l=await ee(i.principal);if(l!==void 0)return l;let c=L(i.principal);try{return await e.conversations.setSpaceWriter(o.value.writer,c),w({writer:o.value.writer})}catch(h){return O(h)}},{capability:"admin"}),g.add("GET","/v1/usage",async(i)=>{let t=gt(i.url);if(t.kind==="error")return f(t.error,400);let o=ve(i.principal);return w(await e.store.usage.report({...t.value,...o}))},{capability:"read"}),g.add("GET","/v1/agents/:id/usage",(i)=>I(e,i,async(t)=>{let o=gt(i.url);if(o.kind==="error")return f(o.error,400);let l=ve(i.principal).sessionPrefix;return w({id:t.id,...await e.store.usage.report({...o.value,agentIds:[t.id],...l===void 0?{}:{sessionPrefix:l}})})}),{capability:"read"}),g.add("GET","/v1/agents/:id/turns",(i)=>I(e,i,async(t)=>{let o=mt(i.url,"limit"),l=mt(i.url,"before");if(o===null||l===null)return f({code:"turns_page_invalid",message:"`limit` and `before` must be positive whole numbers.",hint:"Pass `before` exactly as the previous page's `nextBefore` returned it, and a `limit` up to 200."},400);let c=ve(i.principal).sessionPrefix,h=await e.store.turns.listForAgent(t.id,{limit:Math.min(o??50,200),...l===void 0?{}:{before:l},...c===void 0?{}:{sessionPrefix:c}});return w({id:t.id,...h})}),{capability:"read"}),g.add("GET","/v1/agents/:id/turns/:turnId",(i)=>I(e,i,async(t)=>{let o=await t.store.turns.get(i.params.turnId??"");if(o===void 0||!de(i.principal,o.sessionKey))return H("turn",i.params.turnId??"");return w(o)}),{capability:"read"}),g.add("GET","/v1/agents/:id/sessions",(i)=>I(e,i,async(t)=>{let o=await t.store.sessions.list(t.id),l=await t.store.sessions.heads(t.id);return w($e(i.principal,o.map((c)=>({...c,head:Qs(c.sessionKey,l)}))))}),{capability:"read"}),g.add("POST","/v1/agents/:id/sessions/resolve",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Kt,o.value);if(!l.ok)return f(l.error,400);let c=l.value.sessionKey,h=le(i,c);if(h!==void 0)return h;let v=Me(l.value.from);if(v.kind==="error")return f(v.error,400);let y=we(i.principal,v.from);if(!y.ok)return f(y.error,403);return w({requested:c,sessionKey:await Be(t,i.principal,c,y.from)})}),{capability:"chat"}),g.add("POST","/v1/agents/:id/sessions/rotate",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Ht,o.value);if(!l.ok)return f(l.error,400);let c=Me(l.value.from);if(c.kind==="error")return f(c.error,400);let h=we(i.principal,c.from);if(!h.ok)return f(h.error,403);let v={source:"api",...h.from===void 0?{}:{from:h.from}},y="api:-",k=await t.resolveSessionKey(y,v),_=k===y||!de(i.principal,k)?void 0:await t.rotateSession(v);if(_===void 0)return f({code:"session_not_rotatable",message:`Agent "${t.id}" has no conversation of yours to start afresh.`,hint:`Rotation is for sessions.scope owner or peer, for the owner or a registered participant, by a key that reaches that conversation; this agent's scope is "${t.manifest.sessions?.scope??"channel-peer"}". Otherwise a new conversation is a new sessionKey of your own on the next message.`},409);return w(_)}),{capability:"chat"}),g.add("GET","/v1/agents/:id/sessions/:key",(i)=>I(e,i,async(t)=>{let o=i.params.key??"",l=le(i,o);if(l!==void 0)return l;let c=await t.store.sessions.get(t.id,o);if(c===void 0)return H("session",o);return w(c)}),{capability:"read"}),g.add("GET","/v1/agents/:id/sessions/:key/messages",(i)=>I(e,i,async(t)=>{let o=i.url.searchParams.get("before"),l=i.url.searchParams.get("limit"),c=le(i,i.params.key??"");if(c!==void 0)return c;let h=await t.store.messages.page(t.id,i.params.key??"",{...o===null?{}:{before:Number.parseInt(o,10)},...l===null?{}:{limit:Number.parseInt(l,10)}});return w(h)}),{capability:"read"}),g.add("DELETE","/v1/agents/:id/sessions/:key",(i)=>I(e,i,async(t)=>{let o=le(i,i.params.key??"");if(o!==void 0)return o;return await t.store.sessions.clear(t.id,i.params.key??""),w({cleared:i.params.key??"",memoryFilesKept:!0})}),{capability:"write"}),g.add("POST","/v1/agents/:id/sessions/:key/phase",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B($t,o.value);if(!l.ok)return f(l.error,400);let c=l.value.phase;if(typeof c!=="string"&&c!==null)return f({code:"phase_invalid",message:"phase must be a string, or null to clear it.",hint:'Send { "phase": "triage" }. Phase-scoped tool visibility arrives in Phase 7; the column is written now so a session carries the value across a restart.',field:"phase"},400);let h=le(i,i.params.key??"");if(h!==void 0)return h;let v=i.params.key??"";if(c===null)await t.store.sessions.setPhase(t.id,v,void 0);else await t.setPhase(v,c);return w({sessionKey:v,phase:c})}),{capability:"write"}),g.add("POST","/v1/agents/:id/sessions/:key/recall",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(zt,o.value);if(!l.ok)return f(l.error,400);let c=i.params.key??"",h=le(i,c);if(h!==void 0)return h;if(await t.store.sessions.get(t.id,c)===void 0)return H("session",c);return await t.store.sessions.setRecall(t.id,c,l.value.recall),w({sessionKey:c,recall:l.value.recall})}),{capability:"write"}),g.add("POST","/v1/agents/:id/sessions/:key/compact",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(Ot,o.value);if(!l.ok)return f(l.error,400);let c=i.params.key??"",h=le(i,c);if(h!==void 0)return h;if(await t.store.sessions.get(t.id,c)===void 0)return H("session",c);try{return w(await t.compactSession(c,{...l.value.keepTurns===void 0?{}:{keepTurns:l.value.keepTurns},signal:i.request.signal}))}catch(v){if(T(v)&&v.code==="session_too_short")return f(v.toDetail(),409);throw v}}),{capability:"write"}),g.add("GET","/v1/agents/:id/schedules",(i)=>I(e,i,async(t)=>{let o=i.url.searchParams.get("enabled"),l=await t.store.schedules.list(t.id,o===null?{}:{enabled:o==="true"});return w({schedules:l})}),{capability:"read"}),g.add("POST","/v1/agents/:id/schedules",(i)=>I(e,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);return ot(e,t,o.value,void 0)}),{capability:"write"}),g.add("GET","/v1/agents/:id/schedules/preview",(i)=>I(e,i,async()=>{let t=i.url.searchParams,o=t.get("kind")??"",l=t.get("expr")??"",c=t.get("timezone")??void 0,h=Math.min(10,Math.max(1,Number(t.get("count")??"3")||3));if(o!=="cron"&&o!=="every"&&o!=="at")return f({code:"schedule_invalid",message:`kind must be cron, every or at; got ${JSON.stringify(o)}.`,hint:"Send ?kind=cron&expr=0 8 * * *&timezone=Asia/Dhaka, or kind=every&expr=15m, or kind=at&expr=<ISO instant>.",field:"kind"},400);let v=Date.now(),y;try{y=yr({id:"preview",kind:o,expr:l,timezone:c,now:v,field:"expr"})}catch(C){if(T(C))return f(C.toDetail(),400);throw C}let k=[];if(y.kind==="at")k.push(y.at);else if(y.kind==="every")for(let C=1;C<=h;C+=1)k.push(v+C*y.every.ms);else{let C=v;for(let U=0;U<h;U+=1){let A=PA(y.spec,C,y.zone);if(A===void 0)break;k.push(A),C=A}}let _=y.kind==="every"?y.every.ms:y.kind==="cron"&&k.length>1?(k[1]??0)-(k[0]??0):void 0;return w({kind:y.kind,zone:y.zone,next:k.map((C)=>new Date(C).toISOString()),jitterMs:_===void 0?0:$r("preview",_)})}),{capability:"read"}),g.add("GET","/v1/agents/:id/schedules/:sid",(i)=>I(e,i,async(t)=>{let o=i.params.sid??"",l=await t.store.schedules.get(t.id,o);return l===void 0?H("schedule",o):w(l)}),{capability:"read"}),g.add("PATCH","/v1/agents/:id/schedules/:sid",(i)=>I(e,i,async(t)=>{let o=i.params.sid??"",l=await t.store.schedules.get(t.id,o);if(l===void 0)return H("schedule",o);let c=it(l);if(c!==void 0)return c;let h=await z(i.request);if(h.kind==="error")return f(h.error,400);let v=h.value===null||typeof h.value!=="object"||Array.isArray(h.value)?{}:h.value,{id:y,...k}=v,_={kind:l.kind,expr:l.expr,task:l.task,deliver:l.deliverChannel===void 0||l.deliverTo===void 0?"none":{channel:l.deliverChannel,to:l.deliverTo},session:l.sessionMode,enabled:l.enabled,...l.timezone===void 0?{}:{timezone:l.timezone},...l.role===void 0?{}:{role:l.role},...l.toolsAllow===void 0?{}:{tools:{allow:l.toolsAllow}},...l.timeoutMs===void 0?{}:{timeoutMs:l.timeoutMs},...l.maxSteps===void 0?{}:{maxSteps:l.maxSteps},...k,id:l.id};return ot(e,t,_,l)}),{capability:"write"}),g.add("DELETE","/v1/agents/:id/schedules/:sid",(i)=>I(e,i,async(t)=>{let o=i.params.sid??"",l=await t.store.schedules.get(t.id,o);if(l===void 0)return H("schedule",o);let c=it(l);if(c!==void 0)return c;if(!await t.store.schedules.remove(t.id,o))return H("schedule",o);return e.scheduler.changed(),w({removed:o})}),{capability:"write"}),g.add("POST","/v1/agents/:id/schedules/:sid/run",(i)=>I(e,i,async(t)=>{let o=i.params.sid??"",l=await t.store.schedules.get(t.id,o);if(l===void 0)return H("schedule",o);let c=await t.admit();if(!c.ok)return f(c.error.toDetail(),429);let h=Ss(),v=Gs(l.sessionMode,l.id,h),y=so();return e.streams.open(y),t.send(l.task,{admission:c,sessionKey:v,turnId:y,source:`schedule:${l.id}:manual`,...Us(l)}).catch(()=>{}),w({scheduleId:l.id,turnId:y,sessionKey:v,outOfBand:!0},202)}),{capability:"write"}),g.add("GET","/v1/agents/:id/config",(i)=>ue(e,a,i,async(t)=>{let o=t.file,l=o===void 0?void 0:await Le(o,"utf8");return w({running:t.agent!==void 0,...o===void 0?{editable:!1}:{editable:!0,file:o},settings:[...sA.filter((c)=>GA.includes(c.path)||c.path==="model.<role>").map((c)=>({path:c.path,means:c.means,...c.confirm===void 0?{}:{confirm:c.confirm},...l===void 0?{}:{value:ei(l,c.path.split("."))}})),...la(l)]})}),{capability:"admin"}),g.add("PATCH","/v1/agents/:id/config",(i)=>ue(e,a,i,async(t)=>{let o=await z(i.request);if(o.kind==="error")return f(o.error,400);let l=B(_n,o.value);if(!l.ok)return f(l.error,400);let c=l.value.changes===void 0;if(c===(l.value.path===void 0))return f({code:c?"config_path_unknown":"config_changes_invalid",message:c?"A request named no path.":"A request named both a path and changes.",hint:'Send { "path", "value" } for one change, or { "changes": [{ "path", "value" }, ...] } for several in one reload.',field:c?"path":"changes"},400);let h=l.value.changes??[{...l.value,path:l.value.path??""}],v=t.file;if(typeof v!=="string")return f({code:"config_not_editable",message:`"${t.id}" was loaded from an object, not from a file, so it has no manifest to change.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt(). This route edits a manifest on disk."},409);let y=h.map((P,Q)=>({change:P,index:Q})).filter(({change:P})=>(co(P.path)??un(P.path))?.via===void 0&&co(P.path)===void 0);if(!c&&y.length>0){let P=y[0];return f({code:"config_path_unknown",message:`${y.map(({change:Q,index:W})=>`"${Q.path}" (changes.${W}.path)`).join(", ")} ${y.length===1?"is not a field":"are not fields"} this surface sets. Nothing was written.`,hint:`GET /v1/agents/:id/config lists every one. Nearest to "${P?.change.path}": ${Yt(P?.change.path??"",GA)??GA.join(", ")}.`,field:`changes.${P?.index??0}.path`},400)}let k=[];for(let P of h){let Q=co(P.path)??un(P.path);if(Q===void 0||co(P.path)===void 0)return f({code:"config_path_unknown",message:Q?.via===void 0?`"${P.path}" is not a field this surface sets.`:`"${P.path}" is set by \`${Q.via}\`, not by a dotted path.`,hint:Q?.via===void 0?`GET /v1/agents/:id/config lists every one. Nearest: ${Yt(P.path,GA)??GA.join(", ")}.`:"It is a key inside a list entry, and the source editor matches a key at an indent — it cannot index a sequence. That action also validates the handle against the service that issues it.",field:"path"},400);let W=P.remove===!0;if(W===(P.value!==void 0))return f({code:W?"config_remove_invalid":"config_value_unreadable",message:W?"A request named both a value and remove: true.":"A request named neither a value nor remove: true.",hint:'Send { "path", "value" } to set a field, or { "path", "remove": true } to take it out.',field:W?"remove":"value"},400);if(Q.confirm!==void 0&&P.confirm!==!0)return f({code:"config_confirm_required",message:Q.confirm,hint:'Send { "confirm": true } beside the value to make this change anyway. Nothing has been written.',field:"confirm"},409);k.push(Q)}let _;try{_=await Xr(v,h.map((P)=>({path:P.path.split("."),value:P.value===void 0?void 0:go(P.value),...P.remove===!0?{remove:!0}:{},providers:e.toolProviderFactories,mediaProviders:e.mediaProviderFactories})))}catch(P){if(T(P))return f(P.toDetail(),400);throw P}let C;if(_.written&&t.agent===void 0)C=yt(t.id);else if(_.written)try{C=ke(await e.reload(t.id))}catch(P){if(!T(P))throw P;C=P.toDetail()}let A=h.some((P,Q)=>P.path==="delegation.offer"&&_.edits[Q]?.changed===!0)?await ha(e,t.id,C===void 0):void 0,q=_.edits.map((P,Q)=>({path:k[Q]?.path??"",before:P.before,after:P.after,reflowed:P.reflowed,changed:P.changed}));return w({...c?q[0]:{changes:q},reloaded:_.written&&C===void 0,...C===void 0?{applied:!0}:{applied:!1,pending:C},...A===void 0?{}:{peers:A}})}),{capability:"admin"}),g.add("PATCH","/v1/agents/:id/channels/:channelId",(i)=>I(e,i,async(t)=>{let o=a.channels;if(o===void 0)return f({code:"channels_not_supported",message:"This server cannot change a channel.",hint:"The host did not supply the channel actions — a library caller embedding this handler has to pass them. `dispach serve` does."},501);let l=e.sourceOf(t.id);if(typeof l!=="string")return f({code:"config_not_editable",message:`Agent "${t.id}" was loaded from an object, so it has no manifest to edit.`,hint:"Only an agent loaded from a file can be changed here."},409);let c=await z(i.request);if(c.kind==="error")return f(c.error,400);let h=B(An,c.value);if(!h.ok)return f(h.error,400);let{enabled:v,credential:y}=h.value;if(v===void 0&&y===void 0)return f({code:"channel_patch_empty",message:"Nothing to change.",hint:'Send { "enabled": true | false } to connect or disconnect it, { "credential": "…" } to set its token, or both.'},400);let k=i.params.channelId??"",_=[];try{if(y!==void 0)_.push(o.setCredential(l,k,y).note);if(v!==void 0)_.push((await o.setEnabled(l,k,v)).note)}catch(U){if(!T(U))throw U;return f(U.toDetail(),400)}let C;try{C=ke(await e.reload(t.id))}catch(U){if(!T(U))throw U;C=U.toDetail()}return w({channelId:k,notes:_,...C===void 0?{applied:!0}:{applied:!1,pending:C}})}),{capability:"admin"}),g.add("POST","/v1/agents/:id/channels/:channelId/unpair",(i)=>I(e,i,async(t)=>{let o=i.params.channelId??"",l=await e.channels.reset(t.id,o);if(l==="reset")return w({channelId:o,note:"Pairing forgotten. The channel offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.",restarted:!1});let c=a.channels,h=e.sourceOf(t.id);if(c===void 0||typeof h!=="string")return f({code:l==="unsupported"?"channel_has_no_pairing":"channel_unknown",message:l==="unsupported"?`Channel "${o}" stores no pairing.`:`Agent "${t.id}" has no channel "${o}" registered.`,hint:"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with PATCH on this channel, and a channel is switched off with { enabled: false }.",field:"channelId"},l==="unsupported"?409:404);try{return w({channelId:o,...c.unpair(h,o),restarted:!1})}catch(v){if(!T(v))throw v;return f(v.toDetail(),v.code==="channel_unknown"?404:409)}}),{capability:"admin"}),g.add("GET","/v1/agents/:id/tools",(i)=>I(e,i,(t)=>{let o=t.manifest.phases,l=Wr(o);return w(t.tools.specs().map((c)=>({slug:c.slug,summary:c.summary,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},provider:c.provider??"local",tags:c.tags,...l?{phases:bs(o,c)}:{}})))}),{capability:"read"}),g.add("GET","/v1/agents/:id/skills",(i)=>I(e,i,(t)=>{let o=t.skills;if(o===void 0)return w({skills:[],configured:!1});return w({configured:!0,maxActive:o.maxActive,threshold:o.threshold,cached:o.cached,skills:o.skills.map((l)=>({name:l.name,description:l.frontmatter.description,tokens:l.tokens,...l.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:l.frontmatter.whenNotToUse},scripts:l.scripts.map((c)=>c.slug),trusted:t.manifest.skills?.trusted===void 0||t.manifest.skills.trusted.includes(l.name)}))})}),{capability:"read"}),g.add("GET","/v1/agents/:id/context",(i)=>I(e,i,async(t)=>{let o=i.url.searchParams.get("sessionKey"),l=i.url.searchParams.get("input");return w(await t.previewContext({...o===null?{}:{sessionKey:o},...l===null?{}:{input:l}}))}),{capability:"read"}),g.add("POST","/v1/channels/:channelId/webhook/:agentId",async(i)=>{let t=await z(i.request);if(t.kind==="error")return f(t.error,400);let o={};i.request.headers.forEach((c,h)=>{o[h.toLowerCase()]=c});let l=await e.channels.handleWebhook(i.params.agentId??"",i.params.channelId??"",{body:t.value,headers:o});return new Response(l.detail??"",{status:l.status,headers:{"content-type":"text/plain; charset=utf-8"}})},{capability:"open"}),g.add("GET","/v1/events",(i)=>{let t=i.url.searchParams.get("agentId");if(t!==null&&!X(i.principal,t))return H("agent",t);let o=i.url.searchParams.get("types")?.split(",").filter(Boolean),l=i.url.searchParams.get("chunks")==="true",c=o?.includes("model.chunk")===!0,h=l||c,v=o?.filter((y)=>!Jt.includes(y));if(v!==void 0&&v.length>0){let y=Yt(v[0]??"",Jt);return f({code:"unknown_event_type",message:`No such event type: ${v.join(", ")}.`,hint:y===void 0?"The full catalogue is the event table in docs/04-SPEC-WIRE.md. Omit ?types= to receive every event.":`Did you mean "${y}"? The full catalogue is the event table in docs/04-SPEC-WIRE.md.`,field:"types"},400)}return Ge({...i.request.signal===void 0?{}:{signal:i.request.signal},start:({send:y})=>(y({event:"stream.subscribed",data:{agentId:t??null,types:o??null,chunks:h,...h&&!l?{implied:"types names model.chunk"}:{}}}),e.bus.on("*",(k)=>{if(t!==null&&k.agentId!==t)return;if(k.agentId!==void 0&&!X(i.principal,k.agentId))return;if(!rn(i.principal,k))return;if(o!==void 0&&o.length>0&&!o.includes(k.type))return;y({event:k.type,data:k})},{chunks:h}))})},{capability:"read",streaming:!0});let ce=async(i)=>{let t;try{t=new URL(i.url)}catch{return f({code:"bad_request_url",message:"The request URL could not be parsed.",hint:"This usually means the server was handed a relative URL. A handler mounted inside another framework needs an absolute request.url."},400)}let o=i.method.toUpperCase();if(o==="OPTIONS"){let y=g.match("OPTIONS",t.pathname);if(y.kind==="method"){let _=g.match("HEAD",t.pathname).kind==="method"&&sa(g,t.pathname),C=[...y.allowed,...y.allowed.includes("GET")&&!_?["HEAD"]:[],"OPTIONS"];return j(i,new Response(null,{status:204,headers:{allow:C.join(", "),...a.origin===void 0?{}:Dn(i,C)}}))}}if(o==="HEAD"){let y=g.match("GET",t.pathname);if(y.kind==="found"){if(y.streaming)return f({code:"method_not_allowed",message:`HEAD is not allowed on ${t.pathname}.`,hint:"This path answers with an open event stream. A HEAD would have to start one and then throw the body away, leaving a subscription nothing ever closes — so it is refused rather than leaked. Use GET, or GET /v1/health to check the server is up."},405,{allow:"GET, OPTIONS"});let k=F(i);if(k!==void 0)return k;let _=await K(i,t.pathname,y.capability);if(_ instanceof Response)return _;let C=await lt(y.handler,{request:i,url:t,params:y.params,principal:_});return j(i,new Response(null,{status:C.status,headers:C.headers}))}}let l=G(o,t.pathname);if(l!==void 0){let y=F(i);if(y!==void 0)return y;return j(i,await ne(i,t,l))}let c=g.match(o,t.pathname);if(c.kind==="method")return f({code:"method_not_allowed",message:`${o} is not allowed on ${t.pathname}.`,hint:`This path accepts ${c.allowed.join(", ")}.`},405,{allow:c.allowed.join(", ")});if(c.kind==="none")return ct(i.method,t.pathname);let h=F(i);if(h!==void 0)return h;let v=await K(i,t.pathname,c.capability);if(v instanceof Response)return v;return j(i,await lt(c.handler,{request:i,url:t,params:c.params,principal:v}))},G=(i,t)=>{let o=/^\/v1\/agents\/([^/]+)\/plugins\/([^/]+)(\/.*)?$/.exec(t);if(o!==null){let c=e.list().find((k)=>k.id===decodeURIComponent(o[1]??"")),h=o[2]??"",v=o[3]??"/",y=c?.pluginRoutes.find((k)=>k.plugin===h&&k.method===i&&k.path===v);return c===void 0||y===void 0?void 0:{agent:c,route:y,path:v}}let l=e.list().flatMap((c)=>c.pluginRoutes.filter((h)=>h.root===t&&h.method===i).map((h)=>({agent:c,route:h,path:h.path})));return l.length===1?l[0]:void 0},ne=async(i,t,o)=>{let{agent:l,route:c,path:h}=o,v=c.capability==="open"?{kind:"open"}:await K(i,t.pathname,c.capability);if(v instanceof Response)return v;if(v.kind==="claim"||!X(v,l.id))return ct(i.method,t.pathname);let y=v.kind==="key"?{kind:"key",keyId:v.keyId,label:v.label??""}:c.capability==="open"?{kind:"anonymous"}:{kind:"operator"};try{return await c.handler({request:i,url:t,path:h,caller:y})}catch(k){return f({code:"plugin_route_failed",message:`Plugin "${c.plugin}" failed answering ${i.method} ${t.pathname}: ${k instanceof Error?k.message:String(k)}`,hint:"This is the plugin's error, not the runtime's. The agent's own routes are unaffected."},500)}};return Object.assign(ce,{authenticate:(i)=>K(i,"/v1/ws","read")})}function it(a){if(a.origin!=="manifest")return;return f({code:"schedule_manifest_owned",message:`Schedule "${a.id}" is declared in this agent's manifest, so the manifest decides it.`,hint:"Writing it here would last until the next start — reconciliation restores every field from the file, enabled included. Change the `schedules:` entry instead, with PATCH /v1/agents/:id/config, or create a separate schedule through this route."},409)}async function ot(a,e,d,u){if(d===null||typeof d!=="object"||Array.isArray(d))return f({code:"schedule_invalid",message:"A schedule must be a JSON object.",hint:"Send { id, kind, expr, task, deliver } — see docs/02-SPEC-MANIFEST.md."},400);try{let p=Fs({agentId:e.id,body:d,channelIds:e.manifest.channels.map((b)=>b.id),roleNames:Object.keys(e.manifest.model),toolSpecs:e.tools.specs(),now:Date.now(),origin:"api",...u===void 0?{}:{existing:u}}),m=await e.store.schedules.upsert(p);return a.scheduler.changed(),w(m,u===void 0?201:200)}catch(p){let m=T(p)?p.toDetail():je("schedule_invalid","See docs/02-SPEC-MANIFEST.md for the schedule fields; the server's log has the cause.",p);return f(m,400)}}function Ie(a,e){let d=Xn(a,e.request);if(d===void 0)throw new te({code:"web_asset_missing",message:`No web asset for ${a}.`,hint:"The routes in handler.ts and the table in web.ts have diverged, which spec.test.ts asserts cannot happen — so this build is inconsistent. Rebuild with `bun run build`."});return d}function je(a,e,d){return process.stderr.write(`${a}: ${d instanceof Error?d.stack??d.message:String(d)}
99
- `),{code:a,message:"An unexpected failure; the server's log has the cause.",hint:e}}function w(a,e=200){return new Response(JSON.stringify(a),{status:e,headers:{"content-type":"application/json; charset=utf-8"}})}function ra(a){return a==="/v1/health"||a==="/v1/ready"||a.startsWith("/v1/channels/")||Jn.includes(a)||a==="/docs"||a==="/v1/openapi.json"}function sa(a,e){let d=a.match("GET",e);return d.kind==="found"&&d.streaming}async function lt(a,e){try{return await a(e)}catch(d){if(T(d))return f(d.toDetail(),400);return f(je("internal_error","Not caused by the request. The server's log has the cause, and the runtime's event stream carries what happened around it.",d),500)}}function ct(a,e){return f({code:"not_found",message:`No route for ${a} ${e}.`,hint:"Every path is under /v1. See docs/04-SPEC-WIRE.md for the surface."},404)}function H(a,e,d){return f({code:`${a}_not_found`,message:`No ${a} "${e}".`,hint:d??"Check the id — it is case-sensitive, and a session key includes its channel segment."},404)}function ia(a){let e=a.headers.get("authorization")??"";if(!e.startsWith("Bearer "))return;let d=e.slice(7);return d===""?void 0:d}function dt(a,e,d){let u=d.params.id??"";if(!X(d.principal,u))return{kind:"response",response:H("agent",u)};let p=e.secrets;if(p===void 0)return{kind:"response",response:f({code:"secrets_not_supported",message:"This server cannot write an agent's credentials.",hint:"Credentials go into the .env beside an agent's manifest, and this process was built without a writer for it. Set them where the agent lives, with `config env`, and reload it."},501)};let m=a.sourceOf(u),b=typeof m==="string"?m:e.resolveAgent?.(u);if(b===void 0)return{kind:"response",response:H("agent",u)};return{kind:"found",id:u,manifestPath:b,admin:p}}function ut(a){return{...a,failing:a.consecutiveFailures>0}}function ht(a,e){let d=ve(a);if(d.agentIds!==void 0){let u=e.scope?.agents;if(u===void 0||!u.every((p)=>d.agentIds?.includes(p)))return!1}if(d.sessionPrefix!==void 0){let u=e.scope?.sessionPrefix;if(u===void 0||!u.startsWith(d.sessionPrefix))return!1}return!0}function mt(a,e){let d=a.searchParams.get(e);if(d===null)return;let u=Number(d);return Number.isSafeInteger(u)&&u>0?u:null}function gt(a){let e=a.searchParams.get("by"),d=e===null?["agent","model"]:e.split(",").filter((m)=>m!==""),u=d.filter((m)=>!Ai.includes(m));if(u.length>0)return{kind:"error",error:{code:"usage_group_invalid",message:`Cannot group usage by ${u.join(", ")}.`,hint:`Group by any of ${Ai.join(", ")}, comma-separated, or pass by= for one total.`,field:"by"}};let p={};for(let m of["from","to"]){let b=a.searchParams.get(m);if(b===null)continue;let N=Date.parse(b);if(Number.isNaN(N))return{kind:"error",error:{code:"usage_range_invalid",message:`${m} is ${JSON.stringify(b)}, which is not a date.`,hint:"Send ISO-8601, like 2026-09-01 or 2026-09-01T00:00:00Z. `from` is inclusive and `to` exclusive, so a month is from=2026-09-01&to=2026-10-01.",field:m}};p[m]=new Date(N).toISOString()}return{kind:"ok",value:{by:d,...p}}}function vt(a){return{id:a.agentId,name:a.agentId,status:"disabled",...a.reason===void 0?{}:{reason:a.reason},...a.disabledAt===void 0?{}:{disabledAt:a.disabledAt}}}function ue(a,e,d,u){let p=d.params.id??"";if(!X(d.principal,p))return H("agent",p);let m=a.list().find((N)=>N.id===p);if(m!==void 0){let N=a.sourceOf(p);return u({id:p,agent:m,file:typeof N==="string"?N:void 0})}let b=e.resolveAgent?.(p);if(b===void 0)return H("agent",p);return u({id:p,agent:void 0,file:b})}function yt(a){return{code:"agent_not_running",message:`${a} is not running, so the change is on disk and not yet in force.`,hint:`POST /v1/agents/${a}/start loads it from the files as they are now. GET /v1/agents/${a} says whether they load.`}}function I(a,e,d){let u=e.params.id??"",p=a.list().find((m)=>m.id===u);if(p===void 0)return H("agent",u);if(!X(e.principal,u))return H("agent",u);return d(p)}function oa(a,e){if(!Ke(a))return e;return e.filter((d)=>X(a,d.id))}function $e(a,e){if(!Ke(a))return e;return e.filter((d)=>de(a,d.sessionKey))}function le(a,e){return de(a.principal,e)?void 0:H("session",e)}function bt(a,e){if(e===void 0)return Ke(a.principal);return!de(a.principal,e.sessionKey)}function la(a){if(a===void 0)return[];let e=ei(a,["model"]);if(e===null||typeof e!=="object"||Array.isArray(e))return[];let d=un("model.<role>")?.means??"a named model role";return Object.entries(e).filter(([u])=>u!=="main").map(([u,p])=>({path:`model.${u}`,means:d,value:p}))}async function Oe(a,e){let d=Zr.safeParse(Rs(await Le(e,"utf8")));if(!d.success)return f({code:"workspace_manifest_invalid",message:`${a}'s manifest does not parse, so its workspace files cannot be named.`,hint:"Fix the manifest first: PATCH /v1/agents/:id/config, and GET /v1/agents/:id for what is wrong."},409);let u=be(e),p=d.data.context,m=he(u,p.workspace),b=p.soul,N=[...Os(p,u).refs.map((V)=>({path:V.path,tier:V.tier,field:V.field})),...b?.file===void 0?[]:[{path:he(m,b.file),tier:"soul",field:"context.soul.file"}],...b?.distilled===void 0?[]:[{path:he(m,b.distilled),tier:"soul",field:"context.soul.distilled"}]];return{workspaceDir:m,declared:N}}function wt(a,e,d){return a.find((u)=>u.path===he(e,d)||ye(u.path)===d)?.path}function ze(a,e,d){return f({code:"workspace_file_unknown",message:`${e} is not one of ${a}'s workspace files.`,hint:`Declared: ${d.map((u)=>ye(u.path)).join(", ")||"none"}. A new file is added to context.static or context.volatile with PATCH /config first.`,field:"file"},404)}function xt(a,e){let d=e.manifest.phases,u=Wr(d);return{id:e.id,name:e.manifest.name??e.id,...e.manifest.description===void 0?{}:{description:e.manifest.description},ask:e.manifest.delegation?.ask===!0,status:"loaded",model:e.manifest.model.main.id,channels:e.manifest.channels.map((p)=>{let m=a.channels.statusOf(e.id).find((N)=>N.id===p.id),b=typeof p.tokenEnv==="string"?p.tokenEnv:void 0;return{...m??{},id:p.id,type:p.type,enabled:p.enabled,...b===void 0?{}:{credentialEnv:b,credentialSet:e.hasEnv(b)}}}),entryPhase:u?Ds(d)??null:null,...u?{phases:Object.keys(d)}:{},sessionScope:e.manifest.sessions?.scope??"channel-peer"}}function Re(a){return{...a.disabledAt===void 0?{}:{disabledAt:a.disabledAt},...a.reason===void 0?{}:{reason:a.reason}}}async function z(a,e=Zn){let d=Number.parseInt(a.headers.get("content-length")??"0",10);if(Number.isFinite(d)&&d>e)return{kind:"error",error:{code:"body_too_large",message:`The request body declares ${d} bytes; the limit is ${e}.`,hint:"This cap is enforced before a channel plugin sees anything, so a plugin never has to defend against a large POST."}};let u=await a.text();if(u.length>e)return{kind:"error",error:{code:"body_too_large",message:`The request body is ${u.length} bytes; the limit is ${e}.`,hint:"Send less. A message longer than this is not a message."}};if(u==="")return{kind:"ok",value:{}};try{return{kind:"ok",value:JSON.parse(u)}}catch{return{kind:"error",error:{code:"body_not_json",message:"The request body is not valid JSON.",hint:"Send application/json. A shell quoting mistake is the usual cause — check for unescaped quotes inside the payload."}}}}function Me(a){if(a===void 0||a===null)return{kind:"ok",from:void 0};let e=(u,p,m="from")=>({kind:"error",error:{code:"sender_invalid",message:u,hint:p,field:m}});if(typeof a!=="object")return e("from must be an object.",'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.');let d=a;if(typeof d.id!=="string"||d.id.trim()==="")return e("from.id is required and must be a non-empty string.","Use a stable identity in your own namespace — `agent:ops-bot`, `user:018f…`, an email address. It is opaque to this runtime and is recorded on the turn so an audit can answer who asked.","from.id");if(d.id.length>st)return e(`from.id is ${d.id.length} characters, over the ${st} limit.`,"A sender id is an identifier, not a payload. It is rendered into the prompt's fence label, so an unbounded one spends the context window the message needs.","from.id");if(typeof d.kind!=="string"||!iA.includes(d.kind)){let u=typeof d.kind==="string"?Yt(d.kind,iA):void 0;return e(`from.kind must be one of: ${iA.join(", ")}.`,`${u===void 0?"":`Did you mean "${u}"? `}This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".`,"from.kind")}if(d.name!==void 0&&typeof d.name!=="string")return e("from.name must be a string when present.","It is a display name only and is rendered inside the fence, never above it. Omit it if you have none.","from.name");return{kind:"ok",from:{id:d.id,kind:d.kind,...d.name===void 0?{}:{name:d.name.slice(0,ta)}}}}function ca(a){let e=a.headers.get("idempotency-key");if(e===null)return{kind:"ok",key:void 0};let d=e.trim(),u=(p)=>({kind:"error",error:{code:"idempotency_key_invalid",message:p,hint:`Send 1-${Pe} printable ASCII characters that are unique per logical request — a UUID is the usual choice. Omit the header entirely to accept that a retry runs the turn again. Printable ASCII because the key is a database key, and node:sqlite truncates a bound string at a NUL byte where bun:sqlite stores it whole.`,field:"Idempotency-Key"}});if(d==="")return u("Idempotency-Key is present but empty.");if(d.length>Pe)return u(`Idempotency-Key is ${d.length} characters, over the ${Pe} limit.`);if(!/^[\x20-\x7e]+$/.test(d))return u("Idempotency-Key contains characters that are not printable ASCII.");return{kind:"ok",key:d}}async function da(a,e){let d=new TextEncoder().encode(`${a}\x00${e}`),u=await crypto.subtle.digest("SHA-256",d);return Array.from(new Uint8Array(u)).map((p)=>p.toString(16).padStart(2,"0")).join("")}function ua(a){if(a===void 0||a===null||a==="none")return{kind:"ok",target:void 0};if(typeof a==="object"){let e=a;if(typeof e.channel==="string"&&typeof e.to==="string")return{kind:"ok",target:{channel:e.channel,to:e.to}}}return{kind:"error",error:{code:"deliver_invalid",message:'deliver must be "none" or { channel, to }.',hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',field:"deliver"}}}function pa(a){let e=a.status==="running";return Ge({start:({send:d,close:u})=>{d({event:e?"stream.unavailable":"stream.ended",data:{turnId:a.turnId,status:a.status,sessionKey:a.sessionKey,...e?{reason:"no buffer for this turn in this process",hint:"The turn is recorded as running but is not observable here — its events are buffered in whichever process is executing it, and buffers are in-memory and per-process. Poll GET /v1/agents/:id/turns/:turnId for the outcome."}:{steps:a.steps,...a.errorCode===void 0?{}:{errorCode:a.errorCode},hint:"This turn finished before you attached and its buffer has been evicted. Its full text is in GET /v1/agents/:id/turns/:turnId."}}}),u();return}})}function kt(a,e,d){return Ge({...d?.status===void 0?{}:{status:d.status},start:({send:u,close:p})=>{if(d?.accepted!==void 0)u({event:"turn.accepted",data:d.accepted});let m=a.streams.attach(e,(b)=>{if(u({event:b.type,data:b}),b.type==="turn.end"&&b.turnId===e)p()},{chunks:d?.chunks===!0,children:d?.children===!0});if(m===void 0){u({event:"stream.unavailable",data:{turnId:e,reason:"no buffer for this turn in this process",hint:"Read the final state from GET /v1/agents/:id/turns/:turnId. Buffers are in-memory and are evicted after a turn ends."}}),p();return}u({event:"stream.replay",data:{turnId:e,state:m.state,events:m.replay.length,truncated:m.truncated,dropped:m.dropped,chunks:m.chunks,...m.truncated?{hint:`The oldest ${m.dropped} event(s) of this turn were discarded to stay under the buffer cap, so this replay starts mid-turn. The turn's final text is complete in GET /v1/agents/:id/turns/:turnId.`}:{}}});for(let b of m.replay)u({event:b.type,data:b});if(m.state==="ended")p();return()=>m.unsubscribe()}})}async function ha(a,e,d){let u=a.list().filter((m)=>{let b=m.manifest.delegation?.to;return m.id!==e&&(b==="*"||(b?.includes(e)??!1))}),p=[];for(let m of u){if(!d){p.push({id:m.id,applied:!1,pending:{code:"reload_pending",message:`${e}'s own reload is waiting for running turns, so ${m.id} still lists its old offer.`,hint:`POST /v1/agents/${m.id}/reload once ${e}'s agent.reloaded event arrives.`}});continue}try{let b=ke(await a.reload(m.id));p.push(b===void 0?{id:m.id,applied:!0}:{id:m.id,applied:!1,pending:b})}catch(b){if(!T(b))throw b;p.push({id:m.id,applied:!1,pending:b.toDetail()})}}return p}function ke(a){if(a.status!=="pending")return;return{code:"reload_pending",message:`It applies when the ${a.running} running turn(s) finish; they complete on the settings they started with.`,hint:`New turns keep the old settings for ${a.holdAfterMs} ms, then wait and start on the new ones. The agent.reloaded event says when it is in force.`}}var fa=new Set([".env",".api-token",".venv","node_modules",".git"]),De={env:[".env",".api-token"],git:[".git"]};async function jt(a,e,d=new Set){let u=[],p=async(m)=>{for(let b of await vn(m,{withFileTypes:!0})){if(e.has(b.name))continue;let N=Ue(m,b.name);if(d.has(he(N)))continue;if(b.isDirectory())await p(N);else if(b.isFile())u.push({name:wn(a,N).split(xn).join("/"),path:N})}};return await p(a),u}function As(){let a=fr(),e=!1;return{token:a,live:()=>!e,spend:()=>{if(e)return!1;return e=!0,!0}}}function an(a){let e=a.startsWith("[")&&a.endsWith("]")?a.slice(1,-1):a,d=e==="0.0.0.0"||e==="::"||e===""?"127.0.0.1":e;return d.includes(":")?`[${d}]`:d}function ns(a,e,d){return`http://${an(a)}:${e}/?claim=${d}`}function os(a,e,d){return`curl -sX POST http://${an(a)}:${e}/v1/keys -H 'Authorization: Bearer ${d}' -H 'content-type: application/json' -d '{"label":"my browser"}'`}function dn(a,e,d=new Map){let u=new Set,p,m=0,b,N=(j)=>{let Z=j.type==="model.chunk";for(let M of u){if(M.data.agentId!==void 0&&j.agentId!==M.data.agentId)continue;if(j.agentId!==void 0&&!X(M.data.principal,j.agentId))continue;if(!rn(M.data.principal,j))continue;if(Z&&!M.data.chunks)continue;try{M.send(JSON.stringify(j))}catch{}}},V=()=>{if(m+=1,b===void 0)b=a.bus.on("model.chunk",N)},F=()=>{if(m===0)return;if(m-=1,m===0)b?.(),b=void 0};return{async accept(j){let Z=new URL(j.url),M=Nn(j),K=Z.searchParams.get("token"),L=await e(Tn(j,M??K??""));if(L instanceof Response)return{kind:"reject",response:L};let Y=Z.searchParams.get("agentId");if(Y!==null&&!X(L,Y))return{kind:"reject",response:new Response(JSON.stringify({error:{code:"agent_not_found",message:`No agent "${Y}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}),{status:404,headers:{"content-type":"application/json"}})};return{kind:"accept",session:{agentId:Y??void 0,chunks:Z.searchParams.get("chunks")==="true",principal:L},...M===void 0?{}:{protocol:Nt}}},handlers:{open(j){if(u.add(j),p===void 0)p=a.bus.on("*",N);if(j.data.chunks)V();j.send(JSON.stringify({type:"ws.open",agentId:j.data.agentId??null,chunks:j.data.chunks}))},message(j,Z){let M;try{M=JSON.parse(typeof Z==="string"?Z:new TextDecoder().decode(Z))}catch{j.send(JSON.stringify({type:"ws.error",code:"frame_not_json"}));return}if(M.type==="ping"){j.send(JSON.stringify({type:"pong"}));return}if(M.type==="subscribe"){if(M.agentId===void 0&&M.sessionKey!==void 0){j.send(JSON.stringify({type:"ws.error",code:"subscribe_needs_agent_id",hint:"Send { type: 'subscribe', agentId: '<agent>' }. A socket filters on the agent an event carries; sessionKey names a conversation and can never match one, so a socket pointed with it receives nothing."}));return}let G=typeof M.chunks==="boolean"?M.chunks:j.data.chunks;if(G&&!j.data.chunks)V();else if(!G&&j.data.chunks)F();let ne=M.agentId??j.data.agentId;if(ne!==void 0&&!X(j.data.principal,ne)){j.send(JSON.stringify({type:"ws.error",error:{code:"agent_not_found",message:`No agent "${ne}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}));return}j.data={agentId:ne,chunks:G,principal:j.data.principal},j.send(JSON.stringify({type:"ws.subscribed",agentId:j.data.agentId??null,chunks:j.data.chunks}));return}if(M.type==="stop"){let G=M.turnId===void 0?void 0:d.get(M.turnId);G?.abort(),j.send(JSON.stringify({type:"ws.stopping",turnId:M.turnId??null,found:G!==void 0}));return}if(M.type!=="message"){j.send(JSON.stringify({type:"ws.error",code:"unknown_frame_type"}));return}let K=j.data.agentId,g=a.list().find((G)=>G.id===K);if(g===void 0){j.send(JSON.stringify({type:"ws.error",code:"agent_not_found"}));return}let L=M.text??"";if(L.trim()===""){j.send(JSON.stringify({type:"ws.error",code:"message_text_required"}));return}let Y=we(j.data.principal,void 0),re=Y.ok?Y.from:void 0,J=M.sessionKey??"api:default",O=(G,ne)=>{let i=so(),t=new AbortController;d.set(i,t),j.send(JSON.stringify({type:"ws.accepted",turnId:i,sessionKey:ne})),g.send(L,{admission:G,sessionKey:ne,sessionResolved:!0,turnId:i,source:"ws",...re===void 0?{}:{from:re},signal:t.signal}).catch(()=>{}).finally(()=>d.delete(i))},se=(g.manifest.sessions?.scope??"channel-peer")!=="channel-peer",ee=(G)=>{if(!G.ok){j.send(JSON.stringify({type:"ws.error",...G.error.toDetail()}));return}if(!se){O(G,J);return}Be(g,j.data.principal,J,re).then((ne)=>O(G,ne),(ne)=>{G.release(),process.stderr.write(`internal: ${ne instanceof Error?ne.stack??ne.message:String(ne)}
100
- `),j.send(JSON.stringify({type:"ws.error",code:"internal_error",message:"The conversation for this message could not be read."}))})},ce=g.admitNow();if(ce!==void 0){ee(ce);return}g.admit().then(ee,(G)=>{process.stderr.write(`internal: ${G instanceof Error?G.stack??G.message:String(G)}
101
- `),j.send(JSON.stringify({type:"ws.error",code:"internal_error",message:"The turn budget could not be read."}))})},close(j){if(u.delete(j)&&j.data.chunks)F();if(u.size===0)p?.(),p=void 0}},closeAll(){for(let j of u)try{j.close(1001,"server stopping")}catch{}u.clear(),p?.(),p=void 0,b?.(),b=void 0,m=0}}}async function rs(a){let{host:e,port:d,runtime:u}=a;if(!Se(e)&&a.token===void 0)throw new te({code:"server_public_without_token",message:`Refusing to bind ${e}:${d} with no API token.`,hint:"Set the variable named by server.tokenEnv, or bind 127.0.0.1. A public bind with no token exposes every endpoint — including the ones that start a turn — to anyone who can reach the port, and behaves identically to a safe one until someone finds it.",field:"server.host"});let p=new Map,m=aa({runtime:u,...a.token===void 0?{}:{token:a.token},...a.token===void 0?{allowUnauthenticated:!0}:{},...a.now===void 0?{}:{now:a.now},running:p,...a.approvals===void 0?{}:{approvals:a.approvals},...a.claim===void 0?{}:{claim:a.claim},...a.resolveAgent===void 0?{}:{resolveAgent:a.resolveAgent},...a.provision===void 0?{}:{provision:a.provision},...a.channels===void 0?{}:{channels:a.channels},...a.remover===void 0?{}:{remover:a.remover},...a.secrets===void 0?{}:{secrets:a.secrets},...a.home===void 0?{}:{home:a.home},origin:{host:a.host,...a.allowedOrigins===void 0?{}:{allowedOrigins:a.allowedOrigins},...a.allowedHosts===void 0?{}:{allowedHosts:a.allowedHosts}}});if(a.engine==="bun"||a.engine===void 0&&typeof Bun<"u"&&typeof Bun.serve==="function")return ma(m,a,p);return ga(m,a,p)}function ma(a,e,d){let u=dn(e.runtime,a.authenticate,d),p=Bun.serve({port:e.port,hostname:e.host,idleTimeout:Math.min(255,Math.ceil(on/1000*3)),fetch:async(m,b)=>{if(new URL(m.url).pathname!=="/v1/ws")return a(m);let V=Ne(m,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(V!==void 0)return new Response(JSON.stringify({error:V}),{status:403,headers:{"content-type":"application/json; charset=utf-8"}});let F=await u.accept(m);if(F.kind==="reject")return F.response;if(b.upgrade(m,{data:F.session,...F.protocol===void 0?{}:{headers:{"sec-websocket-protocol":F.protocol}}}))return;return new Response("upgrade failed",{status:400})},websocket:{open:(m)=>u.handlers.open(m),message:(m,b)=>u.handlers.message(m,b),close:(m)=>u.handlers.close(m)}});return{url:`http://${e.host}:${p.port}`,port:p.port??e.port,host:e.host,websocket:!0,stop:async()=>{u.closeAll(),await p.stop(!0)}}}async function ga(a,e,d){let{createServer:u}=await import("node:http"),{WebSocketServer:p}=await import("./wrapper-f662ny3r.js"),m=dn(e.runtime,a.authenticate,d),b=(K,g)=>{let L=`http://${K.headers.host??`${e.host}:${e.port}`}${K.url??"/"}`,Y=new Headers;for(let[J,O]of Object.entries(K.headers))if(typeof O==="string")Y.set(J,O);else if(Array.isArray(O))Y.set(J,O.join(", "));let re=K.method??"GET";return new Request(L,{method:re,headers:Y,...re==="GET"||re==="HEAD"||g===void 0?{}:{body:g}})},N=u((K,g)=>{(async()=>{let L=[];for await(let O of K)L.push(O);let Y=await a(b(K,Buffer.concat(L))),re={};if(Y.headers.forEach((O,se)=>{re[se]=O}),g.writeHead(Y.status,re),Y.body===null){g.end();return}let J=Y.body.getReader();g.on("close",()=>void J.cancel().catch(()=>{}));for(;;){let{done:O,value:se}=await J.read();if(O)break;g.write(Buffer.from(se))}g.end()})().catch(()=>{if(!g.headersSent)g.writeHead(500);g.end()})}),V=new WeakMap,F=new p({noServer:!0,handleProtocols:(K,g)=>V.get(g)??!1}),j=(K,g,L)=>{K.end(`HTTP/1.1 ${g} Refused\r
95
+ `;function ls(s){let{runtime:e}=s,d=s.token,p=s.now??(()=>Date.now()),b=p();if(d===void 0&&s.allowUnauthenticated!==!0)throw new ne({code:"server_token_missing",message:"createHandler was called with no token and no allowUnauthenticated.",hint:"Pass token, or pass allowUnauthenticated: true to state that this handler is mounted somewhere already protected. Defaulting to open would make the safe configuration the one you have to remember."});let w=s.running??new Map,N=s.approvals??Yr(),A=()=>s.origin!==void 0&&Me(s.origin.host),U=(o)=>A()||o.kind!=="open"&&Be(o,"admin"),H=(o)=>{if(s.origin===void 0)return;let n=Le(o,s.origin);return n===void 0?void 0:v(n,403)},C=(o,n)=>{if(s.origin===void 0)return n;let l=Ir(o,s.origin);if(Object.keys(l).length===0)return n;let c=new Headers(n.headers);for(let[u,m]of Object.entries(l))c.set(u,m);return new Response(n.body,{status:n.status,statusText:n.statusText,headers:c})},ae=!1,M=async()=>{if(d!==void 0||ae)return!0;return ae=await e.store.operatorKeys.liveCount()>0,ae},D=async(o,n,l)=>{if(cs(n)||!await M())return{kind:"open"};let c=await la({request:o,expected:d,keys:e.store.operatorKeys,claim:s.claim,pathname:n,at:p()});if(c instanceof Response)return c;if(c.kind==="claim")return c;if(l!=="open"&&!Be(c,l))return ia(l,`${o.method} ${n}`);return c},k=new Gn;k.add("GET","/v1/health",()=>T({status:"ok",version:Ye,uptimeMs:p()-b,agents:e.list().length}),{capability:"open"}),k.add("GET","/v1/ready",()=>{if(e.ready)return T({status:"ready",agents:e.list().length});if(e.draining)return T({status:"draining",agents:e.list().length},503);return T({status:"starting",agents:e.list().length},503)},{capability:"open"}),k.add("GET","/v1/activity",async(o)=>{let n=o.principal;if(n.kind==="key"&&n.scope!==void 0&&(n.scope.agents!==void 0||n.scope.sessions!==void 0))return v({code:"activity_needs_unscoped_key",message:"Activity covers every agent on this server, and this key is scoped.",hint:"Call this with the server token or an operator key minted with no agents or sessions scope — it is meant for whatever suspends and wakes the process, not for a tenant."},403);return T(await e.activity(p()))},{capability:"admin"}),k.add("GET","/v1/agents",async(o)=>{let n=await Promise.all(e.list().map(async(u)=>({...Wt(e,u),assignee:(await e.store.conversations.assignment(u.id))?.participantId??null}))),l=new Set(n.map((u)=>u.id)),c=(await e.store.agentState.list()).filter((u)=>!u.enabled&&!l.has(u.agentId)).map(Ft);return T(ps(o.principal,[...n,...c]))},{capability:"read"}),k.add("GET","/v1/agents/:id",async(o)=>{let n=o.params.id??"";if(!e.list().some((l)=>l.id===n)&&se(o.principal,n)){let l=await e.store.agentState.get(n);if(l!==void 0&&!l.enabled)return T(Ft(l));let c=s.resolveAgent?.(n);if(c!==void 0){let u=await e.diagnose(c);return T({id:n,status:u===void 0?"not_running":"failed",...u===void 0?{}:{error:u}})}}return L(e,o,async(l)=>{let c=await l.store.schedules.list(l.id),u=e.team(l.id),m=await e.store.conversations.assignment(l.id),j=await e.askPeers(l.id);return T({...Wt(e,l),...m===void 0?{}:{assignedTo:{participantId:m.participantId,...m.assignedBy===void 0?{}:{assignedBy:m.assignedBy},assignedAt:m.assignedAt}},dialect:l.describe().dialect,window:l.window,capabilities:l.roles.main.capabilities,tools:l.tools.size,catalogueTokens:l.describe().catalogueTokens,skills:l.skills?.skills.length??0,schedules:c.length,...j.length===0?{}:{peers:j},...u.length===0?{}:{team:u.map((S)=>({id:S.id,task:S.task,artifact:Object.keys(S.artifact.properties)}))},warnings:[...l.warnings,...l.tools.warnings]})})},{capability:"read"}),k.add("GET","/v1/backup",async(o)=>{if(o.principal.kind==="key"&&o.principal.scope?.agents!==void 0)return v({code:"backup_requires_unscoped_key",message:"This key reaches only some agents, and a backup holds every agent's data.",hint:"Take backups with a key that has admin and no agents scope."},403);let n=(o.url.searchParams.get("include")??"").split(",").map((z)=>z.trim()).filter((z)=>z!==""),l=n.filter((z)=>z!=="home"&&!Object.hasOwn(Ze,z));if(l.length>0)return v({code:"backup_include_invalid",message:`include names ${l.join(", ")}, which a backup cannot add.`,hint:`Accepted: ${[...Object.keys(Ze),"home"].join(", ")}, comma-separated. env adds each agent's .env (its secrets), git its .git directories, home everything else in the state directory.`,field:"include"},400);let c=s.home;if(n.includes("home")&&c===void 0)return v({code:"backup_home_unavailable",message:"include=home asks for the state directory, and this server was not given one.",hint:"`serve` passes it; a handler embedded elsewhere sets HandlerOptions.home. The store and agent directories are backed up without it.",field:"include"},400);let u=new Set(Es);for(let z of n)for(let X of Ze[z]??[])u.delete(X);let m=await ea(tt(aa(),"backup-")),j=tt(m,"store.db");await e.store.snapshot(j);let S=[{name:"store.db",source:{path:j}}],E=[];for(let z of e.list()){let X=await Qt(z.dir,u);for(let R of X)S.push({name:`agents/${z.id}/${R.name}`,source:{bytes:await et(R.path)}});E.push({id:z.id,dir:z.dir,files:X.length})}let O;if(n.includes("home")&&c!==void 0){let z=new Set(e.list().map((Z)=>we(Z.dir))),X=(...Z)=>we(c,...Z),R=new Set([...z,X("logs"),X("sources"),...["","-wal","-shm","-journal"].map((Z)=>X(`store.db${Z}`))]),ee=await Qt(c,u,R);for(let Z of ee)S.push({name:`home/${Z.name}`,source:{path:Z.path}});O=ee.length}let I={createdAt:new Date().toISOString(),version:Ye,agents:E,included:n,...O===void 0?{}:{home:{dir:c,files:O}},excluded:[...u]};S.unshift({name:"backup.json",source:{bytes:new TextEncoder().encode(`${JSON.stringify(I,null,2)}
96
+ `)}});let q=I.createdAt.replace(/[:.]/g,"-");return new Response(Fr(S,()=>na(m,{recursive:!0,force:!0})),{headers:{"content-type":"application/gzip","content-disposition":`attachment; filename="backup-${q}.tar.gz"`}})},{capability:"admin"}),k.add("GET","/v1/agents/:id/export",(o)=>L(e,o,async(n)=>{let l=await ie(o.principal);if(l!==void 0)return l;let c=o.url.searchParams.get("paths");try{let u=_s(c===null?void 0:c.split(",").map((m)=>m.trim()));return T(ks(n,u))}catch(u){return B(u)}}),{capability:"admin"}),k.add("POST","/v1/agents/:id/import",(o)=>L(e,o,async(n)=>{let l=await ie(o.principal);if(l!==void 0)return l;let c=await K(o.request,rs);if(c.kind==="error")return v(c.error,400);let u=G(Cn,c.value);if(!u.ok)return v(u.error,400);try{let m=await vs({agent:n,bundle:u.value.bundle,...u.value.mode===void 0?{}:{mode:u.value.mode},reload:async()=>(await e.reload(n.id)).status});return T({id:n.id,...m})}catch(m){return B(m)}}),{capability:"admin"}),k.add("GET","/v1/agents/:id/vars",(o)=>ye(e,s,o,async(n)=>{let l=s.provision?.templateOf;if(l===void 0)return v({code:"rerender_not_supported",message:"This server cannot read an agent's template record.",hint:"`serve` provides it; an embedder mounting this handler has no templates directory."},501);let c=l(n.agent?.dir??Ae(n.file??""));if(c===void 0)return v({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0 or later carries one. Edit its files directly instead."},409);return T({id:n.id,template:c.template,vars:c.vars})}),{capability:"admin"}),k.add("PATCH","/v1/agents/:id/vars",(o)=>ye(e,s,o,async(n)=>{let l=s.provision?.rerender;if(l===void 0)return v({code:"rerender_not_supported",message:"This server cannot re-render an agent's template.",hint:"`serve` provides it; an embedder mounting this handler has no templates directory. Edit the files and POST /reload instead."},501);if(!U(o.principal))return v({code:"provisioning_not_local",message:"Re-rendering an agent's files needs either a loopback bind or a credential with the admin capability.",hint:"It writes the agent's files, like creating one. Present the server's token or an operator key minted with `can: [admin]`."},403);let c=await K(o.request);if(c.kind==="error")return v(c.error,400);let u=G(tn,c.value);if(!u.ok)return v(u.error,400);let m;try{m=l({agentDir:n.agent?.dir??Ae(n.file??""),vars:u.value.vars})}catch(S){if(_(S))return v(S.toDetail(),S.code==="agent_not_from_template"?409:400);throw S}let j=(S,E=200)=>T({id:n.id,rendered:m.rendered,skipped:m.skipped,reload:S},E);if(m.rendered.length===0)return j("none");if(n.agent===void 0)return j("none");try{let S=await e.reload(n.id);return j(S.status,S.status==="pending"?202:200)}catch(S){if(m.undo(),_(S))return v(S.toDetail(),400);throw S}}),{capability:"admin"}),k.add("GET","/v1/agents/:id/workspace",(o)=>ye(e,s,o,async(n)=>{let l=n.file;if(l===void 0)return T({id:n.id,files:[]});let c=await We(n.id,l);if(c instanceof Response)return c;return T({id:n.id,files:c.declared.map((u)=>({name:Te(u.path),tier:u.tier,field:u.field,exists:ke(u.path),bytes:ke(u.path)?Zn(u.path).size:0}))})}),{capability:"admin"}),k.add("GET","/v1/agents/:id/workspace/:file",(o)=>ye(e,s,o,async(n)=>{let l=n.file,c=o.params.file??"";if(l===void 0)return Ve(n.id,c,[]);let u=await We(n.id,l);if(u instanceof Response)return u;let m=Gt(u.declared,u.workspaceDir,c);if(m===void 0)return Ve(n.id,c,u.declared);let j=u.declared.find((S)=>S.path===m);return T({id:n.id,file:Te(m),...j===void 0?{}:{tier:j.tier,field:j.field},exists:ke(m),content:ke(m)?ht(m,"utf8"):""})}),{capability:"admin"}),k.add("PUT","/v1/agents/:id/workspace/:file",(o)=>ye(e,s,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(en,l.value);if(!c.ok)return v(c.error,400);let u=n.file;if(u===void 0)return v({code:"config_not_editable",message:`"${n.id}" was loaded from an object, so it has no files to write.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt()."},409);let m=await We(n.id,u);if(m instanceof Response)return m;let{workspaceDir:j,declared:S}=m,E=o.params.file??"",O=Gt(S,j,E);if(O===void 0)return Ve(n.id,E,S);let I=ke(O)?ht(O,"utf8"):void 0;Jn(Ae(O),{recursive:!0}),ft(O,c.value.content,"utf8");let q=Te(O);if(n.agent===void 0){let z=await e.diagnose(u);return T({id:n.id,file:q,written:!0,loads:z===void 0,...z===void 0?{}:{error:z},applied:!1,pending:Kt(n.id)})}try{let z=await e.reload(n.id);return T({id:n.id,file:q,written:!0,loads:!0,...z.status==="pending"?{applied:!1,pending:$e(z)}:{applied:!0}})}catch(z){if(I===void 0)Xn(O,{force:!0});else ft(O,I,"utf8");if(_(z))return v(z.toDetail(),400);throw z}}),{capability:"admin"}),k.add("POST","/v1/agents/:id/tools/refresh",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(nn,l.value);if(!c.ok)return v(c.error,400);try{let u=await e.refreshTools(n.id,{...c.value.providers===void 0?{}:{providers:c.value.providers}});return T({id:n.id,...u},u.reload==="pending"?202:200)}catch(u){if(_(u))return v(u.toDetail(),u.code==="agent_turn_in_flight"?409:400);throw u}}),{capability:"admin"}),k.add("POST","/v1/agents/:id/reload",(o)=>L(e,o,async(n)=>{try{let l=await e.reload(n.id);if(l.status==="pending")return T({id:n.id,status:"pending",adopted:[],running:l.running,holdAfterMs:l.holdAfterMs},202);return T({id:n.id,status:"loaded",adopted:l.adopted.map((c)=>c.id)})}catch(l){if(_(l))return v({code:l.code,message:l.message,hint:l.hint,...l.field===void 0?{}:{field:l.field}},l.code==="agent_turn_in_flight"?409:400);throw l}}),{capability:"admin"}),k.add("GET","/v1/openapi.json",(o)=>T(_r({routes:k.routes(),serverUrl:`${o.url.protocol}//${o.url.host}`})),{capability:"open"}),k.add("GET","/docs",()=>new Response(is,{status:200,headers:{"content-type":"text/html; charset=utf-8"}}),{capability:"open"}),k.add("GET","/v1/provision",(o)=>T({available:s.provision!==void 0,local:A(),allowed:U(o.principal),steps:s.provision?.steps()??[]}),{capability:"read"}),k.add("POST","/v1/agents",async(o)=>{let n=s.provision;if(n===void 0)return v({code:"provisioning_not_supported",message:"This server cannot create agents.",hint:"Creating one writes a directory of files from a question set this process was not given — an embedder mounting this handler over its own agent store is the case that lands here. Run `init` where the sandbox is, or mount an agent directory."},501);if(!U(o.principal))return v({code:"provisioning_not_local",message:"Creating an agent needs either a loopback bind or a credential with the admin capability.",hint:"This route writes files and starts an agent. A token-less loopback server is a supported configuration, so on a non-loopback bind it asks for a credential instead — set server.tokenEnv (the container's DISPACH_API_TOKEN does this) or present an operator key minted with `can: [admin]`. What is refused is provisioning on a server that required no credential at all and is reachable from the network."},403);let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(mn,l.value);if(!c.ok)return v(c.error,400);let{answers:u,template:m}=c.value;if(u!==void 0&&m!==void 0)return v({code:"provision_body_ambiguous",message:"The body has both answers and a template.",hint:"Send answers to create an agent the way init does, or template with name and vars to create one from a template in this server's sandbox. Not both.",field:"template"},400);if(u===void 0&&m===void 0)return v({code:"provision_answers_required",message:"The body has neither answers nor a template.",hint:'Send { "answers": { "name": "milo", … } } (GET /v1/provision lists the steps), or { "template": "…", "name": "…", "vars": {…} } (GET /v1/templates lists the templates).',field:"answers"},400);let j;try{j=m===void 0?n.create(u??{}):n.createFromTemplate({template:m,name:c.value.name??"",vars:c.value.vars??{}})}catch(S){if(_(S))return v(S.toDetail(),400);throw S}try{if(m===void 0)await n.claim?.(j.manifestPath);let S=await e.adopt(j.manifestPath);return T({id:j.agentId,dir:j.dir,files:j.files,adopted:S.map((E)=>E.id)},201)}catch(S){return T({id:j.agentId,dir:j.dir,files:j.files,adopted:[],error:_(S)?S.toDetail():Re("provision_adopt_failed","The agent was written and is not running. Fix what the server's log names and `start` it, or restart the host.",S)},201)}},{capability:"admin"}),k.add("GET","/v1/templates",()=>T({templates:s.provision?.templates()??[]}),{capability:"read"}),k.add("GET","/v1/agents/:id/secrets",async(o)=>{let n=Mt(e,s,o);if(n.kind==="response")return n.response;return T({id:n.id,secrets:n.admin.status(n.manifestPath)})},{capability:"admin"}),k.add("PUT","/v1/agents/:id/secrets",async(o)=>{let n=Mt(e,s,o);if(n.kind==="response")return n.response;let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(Pn,l.value);if(!c.ok)return v(c.error,400);let u;try{u=n.admin.write(n.manifestPath,c.value.values)}catch(E){if(_(E))return v(E.toDetail(),400);throw E}let m={id:n.id,written:u.written,shadowed:u.shadowed},j=e.list().some((E)=>E.id===n.id),S=await e.store.agentState.get(n.id);if(!j&&S?.enabled===!1)return T({...m,applied:"none",adopted:[],stopped:!0});try{if(j){let O=await e.reload(n.id);if(O.status==="pending")return T({...m,applied:"pending",adopted:[]});return T({...m,applied:"reloaded",adopted:O.adopted.map((I)=>I.id)})}let E=await e.adopt(n.manifestPath);return T({...m,applied:"adopted",adopted:E.map((O)=>O.id)})}catch(E){return T({...m,applied:"none",adopted:[],error:_(E)?E.toDetail():Re("secrets_apply_failed","The values were written and the agent is not running on them yet. Fix what the server's log names and reload or start it.",E)})}},{capability:"admin"}),k.add("POST","/v1/agents/:id/stop",async(o)=>{let n=o.params.id??"";if(!se(o.principal,n))return Q("agent",n);let l=e.list().some((E)=>E.id===n),c=await e.store.agentState.get(n);if(!l&&c===void 0)return Q("agent",n);let u=await K(o.request);if(u.kind==="error")return v(u.error,400);let m=G(pn,u.value);if(!m.ok)return v(m.error,400);let j=m.value.reason?.trim(),S=await e.store.agentState.disable(n,new Date(s.now?.()??Date.now()).toISOString(),j===void 0||j===""?void 0:j);if(l)try{await e.dispose(n,"stopped")}catch(E){if(_(E)&&E.code==="agent_turn_in_flight")return v(E.toDetail(),409);throw E}return T({id:n,status:"disabled",...Qe(S)})},{capability:"admin"}),k.add("POST","/v1/agents/:id/start",async(o)=>{let n=o.params.id??"";if(!se(o.principal,n))return Q("agent",n);if(e.list().some((m)=>m.id===n)){let m=await e.store.agentState.enable(n);return T({id:n,status:"loaded",...Qe(m)})}let l=s.resolveAgent;if(l===void 0)return v({code:"start_not_supported",message:"This server cannot look up a manifest for an agent it is not hosting.",hint:"Starting a stopped agent needs its manifest, which lives wherever agents live — the sandbox for the CLI, a mounted path for a container. This process was built without that lookup, so pass the agent to `serve` and restart it instead."},501);let c=l(n);if(c===void 0)return Q("agent",n);let u=await e.store.agentState.enable(n);try{let m=await e.adopt(c);return T({id:n,status:"loaded",...Qe(u),adopted:m.map((j)=>j.id)})}catch(m){if(await e.store.agentState.disable(n,new Date(s.now?.()??Date.now()).toISOString(),"start failed"),_(m))return v(m.toDetail(),400);throw m}},{capability:"admin"}),k.add("DELETE","/v1/agents/:id",async(o)=>{let n=o.params.id??"";if(!se(o.principal,n))return Q("agent",n);let l=e.list().some((S)=>S.id===n),c=await e.store.agentState.get(n),u=s.remover;if(u===void 0)return v({code:"agent_remove_unsupported",message:"This server cannot delete agents.",hint:"`serve` provides deletion; an embedded handler has no sandbox to delete from. Use the CLI's `remove`."},501);if(o.url.searchParams.get("confirm")!==n)return v({code:"agent_remove_unconfirmed",message:`Deleting ${n} needs ?confirm=${n}.`,hint:"It deletes the agent's conversations, memory and files for good, so the request names the agent twice. POST /v1/agents/:id/stop switches one off and keeps everything.",field:"confirm"},400);let m=u.locate(n);if(!m.ok){if(!l&&c===void 0&&m.status===404)return Q("agent",n);return v(m.error,m.status)}if(l)try{await e.dispose(n,"stopped")}catch(S){if(_(S))return v(S.toDetail(),409);throw S}let j=await e.store.purgeAgent(n);return await u.deleteDir(m.dir),T({id:n,removed:!0,dir:m.dir,...j})},{capability:"admin"}),k.add("POST","/v1/agents/:id/deliveries",async(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(rn,l.value);if(!c.ok)return v(c.error,400);let u=c.value;if(!e.channels.hasChannel(n.id,u.channel))return v({code:"delivery_channel_unknown",message:`${n.id} has no running channel "${u.channel}".`,hint:"Name a channel id from the agent's manifest (GET /v1/agents/:id lists them with their status). A disabled channel is not running and cannot send.",field:"channel"},404);let m=qr({channel:u.channel,peerId:u.to}),j=fe(o,m);if(j!==void 0)return j;let{inserted:S}=await e.channels.deliver({agentId:n.id,sessionKey:m,channelId:u.channel,recipient:u.to,text:u.text,key:u.key});if(S)await n.recordDelivered(u.text,{sessionKey:m});return T({sessionKey:m,key:u.key,duplicate:!S},202)}),{capability:"admin"}),k.add("POST","/v1/agents/:id/messages",async(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(Zt,l.value);if(!c.ok)return v(c.error,400);let u=c.value,m=u.chunks===!0,j=u.text,S=u.sessionKey??"api:default",E=fe(o,S);if(E!==void 0)return E;let O=js(u.deliver);if(O.kind==="error")return v(O.error,400);let I=Je(u.from);if(I.kind==="error")return v(I.error,400);let q=Oe(o.principal,I.from);if(!q.ok)return v(q.error,403);let z=await rt(n,o.principal,S,q.from,u.peerAsk),X=fs(o.request);if(X.kind==="error")return v(X.error,400);if(u.runtimeNote!==void 0&&q.from?.kind==="agent")return v({code:"message_note_untrusted",message:"A message from an agent cannot carry a runtimeNote.",hint:"A note is trusted framing outside the fence a peer's text is shown in. Put what the peer has to say in text.",field:"runtimeNote"},400);if(u.role!==void 0)try{n.roles.byName(u.role)}catch(le){if(_(le))return v({...le.toDetail(),field:"role"},400);throw le}let R=[];if(u.images!==void 0&&u.images.length>0){let le=n.refusesImages(u.role);if(le!==void 0)return v(le.toDetail(),400);try{R=await Qs(n.dir,u.images)}catch(he){if(_(he))return v(he.toDetail(),400);throw he}}let ee=await n.admit();if(!ee.ok)return v(ee.error.toDetail(),429);let Z=so();if(X.key!==void 0){let le=await n.store.turns.claimInboundKey({agentId:n.id,key:X.key,turnId:Z,inputHash:await gs(z,R.length===0?j:`${j}
97
+ ${R.map((he)=>he.data).join(`
98
+ `)}`),now:new Date});if(le.kind!=="claimed")ee.release();if(le.kind==="replay")return T({turnId:le.turnId,sessionKey:z,replayed:!0},200);if(le.kind==="mismatch")return v({code:"idempotency_key_reused",message:`Idempotency-Key "${X.key}" was already used for a different message.`,hint:`It belongs to turn ${le.turnId}, whose text or session differed from this request's. Nothing was run. Use a fresh key for a new message, or resend the original text byte for byte to get that turn back. A key is remembered for 24 hours.`,field:"Idempotency-Key"},409)}let ut=new AbortController;w.set(Z,ut),e.streams.open(Z,{chunks:m});let Os=n.send(j,{admission:ee,sessionKey:z,sessionResolved:!0,turnId:Z,source:"api",...q.from===void 0?{}:{from:q.from},...R.length===0?{}:{images:R},...u.runtimeNote===void 0?{}:{turnNote:u.runtimeNote},...u.role===void 0?{}:{role:u.role},...u.peerAsk===void 0?{}:{peerAsk:u.peerAsk},signal:ut.signal}).then(async(le)=>{let he=le.attachments??[];if(O.target===void 0||le.text.trim()===""&&he.length===0)return;await e.channels.deliver({agentId:n.id,sessionKey:z,channelId:O.target.channel,recipient:O.target.to,turnId:Z,text:le.text,...he.length===0?{}:{attachments:he}})}).catch(()=>{}).finally(()=>{w.delete(Z)});if(u.stream!==!0)return T({turnId:Z,sessionKey:z},202);return Vt(e,Z,{accepted:{turnId:Z,sessionKey:z},status:202,chunks:m,children:u.children===!0})}),{capability:"chat"}),k.add("GET","/v1/agents/:id/turns/:turnId/stream",(o)=>L(e,o,async(n)=>{let l=o.params.turnId??"",c=await n.store.turns.get(l);if(Ht(o,c))return Q("turn",l);if(e.streams.state(l)===void 0){if(c===void 0)return Q("turn",l,"No turn with this id has ever run on this agent. A turn id is the `turnId` from POST /v1/agents/:id/messages — check the agent in the path too, since a turn belongs to one.");return Ns(c)}return Vt(e,l,{chunks:o.url.searchParams.get("chunks")==="true",children:o.url.searchParams.get("children")==="true"})}),{capability:"read",streaming:!0}),k.add("POST","/v1/agents/:id/turns/:turnId/stop",(o)=>L(e,o,async(n)=>{let l=o.params.turnId??"";if(Ht(o,await n.store.turns.get(l)))return Q("turn",l);let c=w.get(l);if(c===void 0)return v({code:"turn_not_running",message:`No cancel handle for turn ${l} on this API.`,hint:"This surface can stop a turn it started. A turn that has already finished cannot be stopped at all — read its final state from GET /v1/agents/:id/turns/:turnId. A turn started by a channel, a schedule, or another process is running without a handle here."},409);return c.abort(),T({turnId:l,stopping:!0},202)}),{capability:"chat"}),k.add("GET","/v1/agents/:id/approvals",(o)=>L(e,o,async(n)=>T({approvals:Ge(o.principal,N.pending(n.id))})),{capability:"read"}),k.add("POST","/v1/agents/:id/approvals/:approvalId",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(sn,l.value);if(!c.ok)return v(c.error,400);let u=c.value,m=o.params.approvalId??"";if(!Ge(o.principal,N.pending(n.id)).some((S)=>S.approvalId===m)||!N.resolve(m,u.granted))return v({code:"approval_not_found",message:`No approval with id ${m} is waiting.`,hint:'It was answered already, or its turn ended while it waited — a stopped or timed-out turn abandons its question, and `approval.resolved` reports that as `by: "abandoned"`. GET /v1/agents/:id/approvals lists what is actually waiting. Nothing about a settled approval is kept, so this is also the answer for an id that was never real.'},404);return T({approvalId:m,granted:u.granted})}),{capability:"chat"}),k.add("GET","/",(o)=>qe("/",o),{capability:"open"}),k.add("GET","/assets/app.js",(o)=>qe("/assets/app.js",o),{capability:"open"}),k.add("GET","/assets/app.css",(o)=>qe("/assets/app.css",o),{capability:"open"}),k.add("POST","/v1/keys",async(o)=>{let n=s.claim!==void 0&&us(o.request)===s.claim.token,l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(on,l.value);if(!c.ok)return v(c.error,400);let u=c.value,m=Bs(u.label);if(m!==void 0)return v({code:"key_label_invalid",message:m,hint:`A label is shown in a listing and in the UI, so it is at most ${Br} printable characters on one line. It is a display name, not a description.`,field:"label"},400);if(n&&s.claim?.spend()!==!0)return Xt();let j=u.scope;if(j?.agents!==void 0){let q=new Set(e.list().map((X)=>X.id));for(let X of await e.store.agentState.list())q.add(X.agentId);let z=j.agents.filter((X)=>!q.has(X));if(z.length>0)return v({code:"key_scope_agent_unknown",message:`No agent ${z.map((X)=>JSON.stringify(X)).join(", ")} on this server.`,hint:"A key scoped to an agent that does not exist authenticates and then reaches nothing, which looks exactly like a working credential until it is used. GET /v1/agents lists what this server holds, stopped agents included.",field:"scope.agents"},400)}let S=j?.expiresIn===void 0?void 0:new Date(p()+j.expiresIn*1000).toISOString(),E=j===void 0?void 0:{...j.agents===void 0?{}:{agents:j.agents},...j.sessions===void 0?{}:{sessions:j.sessions},...j.can===void 0?{}:{can:j.can},...j.participant===void 0?{}:{participant:j.participant}},O=Cr(),I=await e.store.operatorKeys.issue({keyId:Ss(p()),label:u.label.trim(),fingerprint:await hr(O),createdAt:new Date(p()).toISOString(),...E===void 0||Object.keys(E).length===0?{}:{scope:E},...S===void 0?{}:{expiresAt:S}});return T({...I,secret:O},201)},{capability:"admin"}),k.add("GET","/v1/keys",async()=>{let o=await e.store.operatorKeys.list();return T({keys:o,scope:"A key with no scope authenticates every route for every agent this server holds. A scope narrows an already-authenticated caller — it names agents, a session prefix and capabilities, and it is not an identity: there are no users, teams or roles here."})},{capability:"admin"}),k.add("DELETE","/v1/keys/:keyId",async(o)=>{let n=o.params.keyId??"",l=await e.store.operatorKeys.revoke(n,new Date(p()).toISOString());if(l===void 0)return Q("key",n,"The id is the `keyId` from POST /v1/keys, not the secret — GET /v1/keys lists them. An already-revoked key is a 200 carrying its original stamp, so this really does mean no such key exists.");return T(l)},{capability:"admin"}),k.add("POST","/v1/webhooks",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(_n,n.value);if(!l.ok)return v(l.error,400);let c=l.value,u=c.types.filter((I)=>!Jt.includes(I)||!Ps(I));if(u.length>0)return v({code:"webhook_type_invalid",message:`Cannot deliver ${u.join(", ")}.`,hint:"Any type from the event stream except model.chunk, which is one request per token. The wire spec's event table lists them.",field:"types"},400);let m=Ne(o.principal);if(c.agents!==void 0){let I=new Set([...e.list().map((z)=>z.id),...(await e.store.agentState.list()).map((z)=>z.agentId)]),q=c.agents.filter((z)=>!se(o.principal,z)||!I.has(z));if(q.length>0)return v({code:"webhook_scope_invalid",message:`This credential cannot subscribe to ${q.join(", ")}.`,hint:"A subscription hears at most what the key creating it reaches, and only agents this server holds. GET /v1/agents lists them.",field:"agents"},400)}let j=c.agents??m.agentIds,S={...j===void 0?{}:{agents:[...j]},...m.sessionPrefix===void 0?{}:{sessionPrefix:m.sessionPrefix}};try{await e.webhooks.check(c.url)}catch(I){if(_(I))return v(I.toDetail(),400);throw I}let E=Ls(),O=await e.store.webhooks.create({subscriptionId:`wh_${crypto.randomUUID().replaceAll("-","").slice(0,20)}`,url:c.url,secret:E,types:[...new Set(c.types)],...Object.keys(S).length===0?{}:{scope:S},createdAt:new Date(s.now?.()??Date.now()).toISOString()});return await e.webhooks.changed(),T({...Lt(O),secret:E},201)},{capability:"admin"}),k.add("GET","/v1/webhooks",async(o)=>{let n=await e.store.webhooks.list();return T({webhooks:n.filter((l)=>Dt(o.principal,l)).map(Lt)})},{capability:"admin"}),k.add("DELETE","/v1/webhooks/:webhookId",async(o)=>{let n=o.params.webhookId??"",l=await e.store.webhooks.get(n);if(l===void 0||!Dt(o.principal,l))return v({code:"webhook_not_found",message:`No webhook with id "${n}".`,hint:"GET /v1/webhooks lists the subscriptions this credential can see."},404);return await e.store.webhooks.delete(n),await e.webhooks.changed(),T({id:n,deleted:!0})},{capability:"admin"});let F=(o)=>o.kind==="key"?o.scope?.participant:void 0,J=(o,n)=>{let l=F(o);if(l!==void 0&&!n.members.includes(l))return!1;return n.members.every((c)=>{let u=oi(c);return u===void 0||se(o,u)})},ce=(o)=>v({code:"conversation_not_found",message:`No conversation "${o}".`,hint:"GET /v1/conversations lists the ones this credential can see."},404),re=async(o,n)=>{let l=o.params.conversationId??"",c=await e.store.conversations.get(l);if(c===void 0||!J(o.principal,c))return ce(l);return n(c)},B=(o)=>{if(!_(o))throw o;return v(o.toDetail(),o.code.endsWith("_not_found")?404:o.code.endsWith("_forbidden")?403:400)};k.add("POST","/v1/participants",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(vn,n.value);if(!l.ok)return v(l.error,400);try{let c=l.value;return T(await e.conversations.registerParticipant({id:c.id,...c.name===void 0?{}:{name:c.name},...c.role===void 0?{}:{role:c.role},...c.title===void 0?{}:{title:c.title},...c.timezone===void 0?{}:{timezone:c.timezone},...c.channelIds===void 0?{}:{channelIds:c.channelIds}}),201)}catch(c){return B(c)}},{capability:"admin"}),k.add("GET","/v1/participants",async()=>T({participants:await e.store.conversations.participants()}),{capability:"read"}),k.add("DELETE","/v1/participants/:participantId",async(o)=>{let n=o.params.participantId??"";if(!await e.store.conversations.deleteParticipant(n))return v({code:"participant_not_found",message:`No participant "${n}".`,hint:"GET /v1/participants lists them."},404);return T({id:n,deleted:!0})},{capability:"admin"}),k.add("POST","/v1/conversations",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(yn,n.value);if(!l.ok)return v(l.error,400);let c=F(o.principal);if(c!==void 0&&!l.value.members.includes(c))return v({code:"conversation_creator_not_member",message:`This key speaks for ${c}, who is not among the members.`,hint:`Include "${c}" in members. A backend creating rooms for others needs a key minted without scope.participant.`,field:"members"},403);let u=l.value.members.map((m)=>oi(m)).filter((m)=>m!==void 0&&!se(o.principal,m));if(u.length>0)return v({code:"conversation_member_unknown",message:`No participant "agent:${u[0]}".`,hint:"That agent is not hosted here. GET /v1/agents lists the ones that are.",field:"members"},400);try{return T(await e.conversations.create({kind:l.value.kind,members:l.value.members,...l.value.title===void 0?{}:{title:l.value.title}}),201)}catch(m){return B(m)}},{capability:"admin"}),k.add("GET","/v1/conversations",async(o)=>{let n=await e.store.conversations.list();return T({conversations:n.filter((l)=>J(o.principal,l))})},{capability:"read"}),k.add("GET","/v1/conversations/:conversationId",(o)=>re(o,async(n)=>T(n)),{capability:"read"}),k.add("PATCH","/v1/conversations/:conversationId/members",(o)=>re(o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(bn,l.value);if(!c.ok)return v(c.error,400);try{return T(await e.conversations.setMembers(n.id,c.value.add??[],c.value.remove??[]))}catch(u){return B(u)}}),{capability:"admin"}),k.add("POST","/v1/conversations/:conversationId/messages",(o)=>re(o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(wn,l.value);if(!c.ok)return v(c.error,400);let u=F(o.principal),m=c.value.authorId;if(u!==void 0&&m!==void 0&&m!==u)return v({code:"sender_not_bound_participant",message:`This key speaks for ${u}, and the message names ${m}.`,hint:`Omit authorId (it is filled in), or send "${u}". A backend that posts for others needs a key minted without scope.participant.`,field:"authorId"},403);let j=u??m;if(j===void 0)return v({code:"conversation_author_required",message:"A message needs an author.",hint:"Send authorId, the human member who said it. A key bound to a participant fills it in.",field:"authorId"},400);try{let S=await e.conversations.post({conversationId:n.id,authorId:j,text:c.value.text,...c.value.mentions===void 0?{}:{mentions:c.value.mentions}});return T(S,202)}catch(S){return B(S)}}),{capability:"chat"}),k.add("GET","/v1/conversations/:conversationId/messages",(o)=>re(o,async(n)=>{let l=Number(o.url.searchParams.get("after")??0),c=Number(o.url.searchParams.get("limit")??200),u=await e.store.conversations.messages(n.id,{after:Number.isFinite(l)&&l>0?l:0,limit:Number.isFinite(c)&&c>0?Math.min(c,500):200});return T({conversationId:n.id,messages:u,...u.length===0?{}:{nextAfter:u.at(-1)?.seq}})}),{capability:"read"}),k.add("PUT","/v1/participants/:participantId/presence",async(o)=>{let n=o.params.participantId??"",l=F(o.principal);if(l!==void 0&&l!==n)return v({code:"sender_not_bound_participant",message:`This key speaks for ${l}, and the presence names ${n}.`,hint:"A key bound to a participant sets only that participant's presence. The embedder's backend, holding an unbound key, sets anyone's."},403);let c=await K(o.request);if(c.kind==="error")return v(c.error,400);let u=G(Sn,c.value);if(!u.ok)return v(u.error,400);try{return T(await e.conversations.setPresence(n,u.value.presence))}catch(m){return B(m)}},{capability:"chat"}),k.add("GET","/v1/actions",async(o)=>{let n=o.url.searchParams.get("status"),l=F(o.principal),c=await e.store.conversations.actions({...l===void 0?{}:{ownerId:l},...n==="pending"||n==="done"||n==="failed"||n==="denied"?{status:n}:{}});return T({actions:c.filter((u)=>se(o.principal,u.agentId))})},{capability:"read"}),k.add("POST","/v1/actions/:actionId",async(o)=>{let n=o.params.actionId??"",l=await e.store.conversations.action(n),c=F(o.principal);if(l===void 0||!se(o.principal,l.agentId)||c!==void 0&&c!==l.ownerId)return v({code:"action_not_found",message:`No action "${n}".`,hint:"GET /v1/actions lists the ones waiting on you."},404);let u=await K(o.request);if(u.kind==="error")return v(u.error,400);let m=G(An,u.value);if(!m.ok)return v(m.error,400);try{return T(await e.conversations.decideAction(n,m.value.approve))}catch(j){if(_(j)&&j.code==="action_already_decided")return v(j.toDetail(),409);return B(j)}},{capability:"chat"}),k.add("PUT","/v1/agents/:id/assignee",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(jn,l.value);if(!c.ok)return v(c.error,400);let u=F(o.principal);if(u!==void 0){if((await e.store.conversations.participant(u))?.role!=="admin")return v({code:"assignment_requires_admin",message:`${u} is not an admin participant.`,hint:'Only a participant registered with role "admin" assigns agents to members.'},403)}try{let m=await e.conversations.assign({agentId:n.id,participantId:c.value.participantId,...u===void 0?{}:{assignedBy:u},...c.value.channelIds===void 0?{}:{channelIds:c.value.channelIds}});return await n.checkSessionScope(),T(m)}catch(m){return B(m)}}),{capability:"admin"}),k.add("GET","/v1/agents/:id/assignee",(o)=>L(e,o,async(n)=>T({id:n.id,assignment:await e.store.conversations.assignment(n.id)??null})),{capability:"read"}),k.add("DELETE","/v1/agents/:id/assignee",(o)=>L(e,o,async(n)=>{let l=await e.store.conversations.unassign(n.id);if(l)e.schedulePeerCheck();return await n.checkSessionScope(),T({id:n.id,unassigned:l})}),{capability:"admin"});let ue=(o)=>{let n=F(o);if(n!==void 0||Be(o,"admin"))return{ok:!0,actor:n};return{ok:!1,response:v({code:"memory_write_requires_admin",message:"This key is bound to no participant and does not carry admin.",hint:"A member writes through a key minted with scope.participant; the embedder's backend writes shared scopes with an admin key."},403)}};k.add("POST","/v1/memory/notes",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(Nn,n.value);if(!l.ok)return v(l.error,400);let c=ue(o.principal);if(!c.ok)return c.response;try{return T(await e.conversations.addNote({scope:l.value.scope,text:l.value.text,...c.actor===void 0?{}:{authorId:c.actor}}),201)}catch(u){return B(u)}},{capability:"chat"}),k.add("GET","/v1/memory/notes",async(o)=>{let n=o.url.searchParams.get("scope")??"";try{return T({notes:await e.conversations.notes(n,F(o.principal))})}catch(l){return B(l)}},{capability:"read"}),k.add("DELETE","/v1/memory/notes/:noteId",async(o)=>{let n=ue(o.principal);if(!n.ok)return n.response;try{return await e.conversations.deleteNote(o.params.noteId??"",n.actor),T({id:o.params.noteId,deleted:!0})}catch(l){return B(l)}},{capability:"chat"}),k.add("GET","/v1/participants/:participantId/memory/reads",async(o)=>{try{return T({reads:await e.conversations.reads(o.params.participantId??"",F(o.principal))})}catch(n){return B(n)}},{capability:"read"});let ie=async(o)=>{let n=F(o);if(n===void 0)return;if((await e.store.conversations.participant(n))?.role==="admin")return;return v({code:"memory_scope_forbidden",message:`${n} is not an admin participant.`,hint:'Only a participant registered with role "admin" defines projects and names the space writer.'},403)};k.add("GET","/v1/projects",async()=>T({projects:await e.store.conversations.projects()}),{capability:"read"}),k.add("PUT","/v1/projects/:projectId",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(Tn,n.value);if(!l.ok)return v(l.error,400);let c=await ie(o.principal);if(c!==void 0)return c;let u=(l.value.agents??[]).find((m)=>!se(o.principal,m));if(u!==void 0)return v({code:"agent_not_found",message:`No agent "${u}".`,hint:"GET /v1/agents lists the ones hosted here."},404);try{return T(await e.conversations.upsertProject({id:o.params.projectId??"",...l.value.name===void 0?{}:{name:l.value.name},...l.value.agents===void 0?{}:{agents:l.value.agents}}))}catch(m){return B(m)}},{capability:"admin"}),k.add("DELETE","/v1/projects/:projectId",async(o)=>{let n=await ie(o.principal);if(n!==void 0)return n;let l=o.params.projectId??"";return T({id:l,deleted:await e.store.conversations.deleteProject(l)})},{capability:"admin"}),k.add("PUT","/v1/memory/space/writer",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l=G(En,n.value);if(!l.ok)return v(l.error,400);let c=await ie(o.principal);if(c!==void 0)return c;let u=F(o.principal);try{return await e.conversations.setSpaceWriter(l.value.writer,u),T({writer:l.value.writer})}catch(m){return B(m)}},{capability:"admin"}),k.add("GET","/v1/usage",async(o)=>{let n=Bt(o.url);if(n.kind==="error")return v(n.error,400);let l=Ne(o.principal);return T(await e.store.usage.report({...n.value,...l}))},{capability:"read"}),k.add("GET","/v1/agents/:id/usage",(o)=>L(e,o,async(n)=>{let l=Bt(o.url);if(l.kind==="error")return v(l.error,400);let c=Ne(o.principal).sessionPrefix;return T({id:n.id,...await e.store.usage.report({...l.value,agentIds:[n.id],...c===void 0?{}:{sessionPrefix:c}})})}),{capability:"read"}),k.add("GET","/v1/agents/:id/turns",(o)=>L(e,o,async(n)=>{let l=Ut(o.url,"limit"),c=Ut(o.url,"before");if(l===null||c===null)return v({code:"turns_page_invalid",message:"`limit` and `before` must be positive whole numbers.",hint:"Pass `before` exactly as the previous page's `nextBefore` returned it, and a `limit` up to 200."},400);let u=Ne(o.principal).sessionPrefix,m=await e.store.turns.listForAgent(n.id,{limit:Math.min(l??50,200),...c===void 0?{}:{before:c},...u===void 0?{}:{sessionPrefix:u}});return T({id:n.id,...m})}),{capability:"read"}),k.add("GET","/v1/agents/:id/turns/:turnId",(o)=>L(e,o,async(n)=>{let l=await n.store.turns.get(o.params.turnId??"");if(l===void 0||!ve(o.principal,l.sessionKey))return Q("turn",o.params.turnId??"");return T(l)}),{capability:"read"}),k.add("GET","/v1/agents/:id/sessions",(o)=>L(e,o,async(n)=>{let l=await n.store.sessions.list(n.id),c=await n.store.sessions.heads(n.id);return T(Ge(o.principal,l.map((u)=>({...u,head:ys(u.sessionKey,c)}))))}),{capability:"read"}),k.add("POST","/v1/agents/:id/sessions/resolve",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(xn,l.value);if(!c.ok)return v(c.error,400);let u=c.value.sessionKey,m=fe(o,u);if(m!==void 0)return m;let j=Je(c.value.from);if(j.kind==="error")return v(j.error,400);let S=Oe(o.principal,j.from);if(!S.ok)return v(S.error,403);return T({requested:u,sessionKey:await rt(n,o.principal,u,S.from)})}),{capability:"chat"}),k.add("POST","/v1/agents/:id/sessions/rotate",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(kn,l.value);if(!c.ok)return v(c.error,400);let u=Je(c.value.from);if(u.kind==="error")return v(u.error,400);let m=Oe(o.principal,u.from);if(!m.ok)return v(m.error,403);let j={source:"api",...m.from===void 0?{}:{from:m.from}},S="api:-",E=await n.resolveSessionKey(S,j),O=E===S||!ve(o.principal,E)?void 0:await n.rotateSession(j);if(O===void 0)return v({code:"session_not_rotatable",message:`Agent "${n.id}" has no conversation of yours to start afresh.`,hint:`Rotation is for sessions.scope owner or peer, for the owner or a registered participant, by a key that reaches that conversation; this agent's scope is "${n.manifest.sessions?.scope??"channel-peer"}". Otherwise a new conversation is a new sessionKey of your own on the next message.`},409);return T(O)}),{capability:"chat"}),k.add("GET","/v1/agents/:id/sessions/:key",(o)=>L(e,o,async(n)=>{let l=o.params.key??"",c=fe(o,l);if(c!==void 0)return c;let u=await n.store.sessions.get(n.id,l);if(u===void 0)return Q("session",l);return T(u)}),{capability:"read"}),k.add("GET","/v1/agents/:id/sessions/:key/messages",(o)=>L(e,o,async(n)=>{let l=o.url.searchParams.get("before"),c=o.url.searchParams.get("limit"),u=fe(o,o.params.key??"");if(u!==void 0)return u;let m=await n.store.messages.page(n.id,o.params.key??"",{...l===null?{}:{before:Number.parseInt(l,10)},...c===null?{}:{limit:Number.parseInt(c,10)}});return T(m)}),{capability:"read"}),k.add("DELETE","/v1/agents/:id/sessions/:key",(o)=>L(e,o,async(n)=>{let l=fe(o,o.params.key??"");if(l!==void 0)return l;return await n.store.sessions.clear(n.id,o.params.key??""),T({cleared:o.params.key??"",memoryFilesKept:!0})}),{capability:"write"}),k.add("POST","/v1/agents/:id/sessions/:key/phase",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(ln,l.value);if(!c.ok)return v(c.error,400);let u=c.value.phase;if(typeof u!=="string"&&u!==null)return v({code:"phase_invalid",message:"phase must be a string, or null to clear it.",hint:'Send { "phase": "triage" }. Phase-scoped tool visibility arrives in Phase 7; the column is written now so a session carries the value across a restart.',field:"phase"},400);let m=fe(o,o.params.key??"");if(m!==void 0)return m;let j=o.params.key??"";if(u===null)await n.store.sessions.setPhase(n.id,j,void 0);else await n.setPhase(j,u);return T({sessionKey:j,phase:u})}),{capability:"write"}),k.add("POST","/v1/agents/:id/sessions/:key/recall",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(dn,l.value);if(!c.ok)return v(c.error,400);let u=o.params.key??"",m=fe(o,u);if(m!==void 0)return m;if(await n.store.sessions.get(n.id,u)===void 0)return Q("session",u);return await n.store.sessions.setRecall(n.id,u,c.value.recall),T({sessionKey:u,recall:c.value.recall})}),{capability:"write"}),k.add("POST","/v1/agents/:id/sessions/:key/compact",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(cn,l.value);if(!c.ok)return v(c.error,400);let u=o.params.key??"",m=fe(o,u);if(m!==void 0)return m;if(await n.store.sessions.get(n.id,u)===void 0)return Q("session",u);try{return T(await n.compactSession(u,{...c.value.keepTurns===void 0?{}:{keepTurns:c.value.keepTurns},signal:o.request.signal}))}catch(j){if(_(j)&&(j.code==="session_too_short"||j.code==="nothing_to_gain"))return v(j.toDetail(),409);throw j}}),{capability:"write"}),k.add("GET","/v1/agents/:id/schedules",(o)=>L(e,o,async(n)=>{let l=o.url.searchParams.get("enabled"),c=await n.store.schedules.list(n.id,l===null?{}:{enabled:l==="true"});return T({schedules:c})}),{capability:"read"}),k.add("POST","/v1/agents/:id/schedules",(o)=>L(e,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);return $t(e,n,l.value,void 0)}),{capability:"write"}),k.add("GET","/v1/agents/:id/schedules/preview",(o)=>L(e,o,async()=>{let n=o.url.searchParams,l=n.get("kind")??"",c=n.get("expr")??"",u=n.get("timezone")??void 0,m=Math.min(10,Math.max(1,Number(n.get("count")??"3")||3));if(l!=="cron"&&l!=="every"&&l!=="at")return v({code:"schedule_invalid",message:`kind must be cron, every or at; got ${JSON.stringify(l)}.`,hint:"Send ?kind=cron&expr=0 8 * * *&timezone=Asia/Dhaka, or kind=every&expr=15m, or kind=at&expr=<ISO instant>.",field:"kind"},400);let j=Date.now(),S;try{S=yr({id:"preview",kind:l,expr:c,timezone:u,now:j,field:"expr"})}catch(I){if(_(I))return v(I.toDetail(),400);throw I}let E=[];if(S.kind==="at")E.push(S.at);else if(S.kind==="every")for(let I=1;I<=m;I+=1)E.push(j+I*S.every.ms);else{let I=j;for(let q=0;q<m;q+=1){let z=PA(S.spec,I,S.zone);if(z===void 0)break;E.push(z),I=z}}let O=S.kind==="every"?S.every.ms:S.kind==="cron"&&E.length>1?(E[1]??0)-(E[0]??0):void 0;return T({kind:S.kind,zone:S.zone,next:E.map((I)=>new Date(I).toISOString()),jitterMs:O===void 0?0:Xr("preview",O)})}),{capability:"read"}),k.add("GET","/v1/agents/:id/schedules/:sid",(o)=>L(e,o,async(n)=>{let l=o.params.sid??"",c=await n.store.schedules.get(n.id,l);return c===void 0?Q("schedule",l):T(c)}),{capability:"read"}),k.add("PATCH","/v1/agents/:id/schedules/:sid",(o)=>L(e,o,async(n)=>{let l=o.params.sid??"",c=await n.store.schedules.get(n.id,l);if(c===void 0)return Q("schedule",l);let u=Ot(c);if(u!==void 0)return u;let m=await K(o.request);if(m.kind==="error")return v(m.error,400);let j=m.value===null||typeof m.value!=="object"||Array.isArray(m.value)?{}:m.value,{id:S,...E}=j,O={kind:c.kind,expr:c.expr,task:c.task,deliver:c.deliverChannel===void 0||c.deliverTo===void 0?"none":{channel:c.deliverChannel,to:c.deliverTo},session:c.sessionMode,enabled:c.enabled,...c.timezone===void 0?{}:{timezone:c.timezone},...c.role===void 0?{}:{role:c.role},...c.toolsAllow===void 0?{}:{tools:{allow:c.toolsAllow}},...c.timeoutMs===void 0?{}:{timeoutMs:c.timeoutMs},...c.maxSteps===void 0?{}:{maxSteps:c.maxSteps},...E,id:c.id};return $t(e,n,O,c)}),{capability:"write"}),k.add("DELETE","/v1/agents/:id/schedules/:sid",(o)=>L(e,o,async(n)=>{let l=o.params.sid??"",c=await n.store.schedules.get(n.id,l);if(c===void 0)return Q("schedule",l);let u=Ot(c);if(u!==void 0)return u;if(!await n.store.schedules.remove(n.id,l))return Q("schedule",l);return e.scheduler.changed(),T({removed:l})}),{capability:"write"}),k.add("POST","/v1/agents/:id/schedules/:sid/run",(o)=>L(e,o,async(n)=>{let l=o.params.sid??"",c=await n.store.schedules.get(n.id,l);if(c===void 0)return Q("schedule",l);let u=await n.admit();if(!u.ok)return v(u.error.toDetail(),429);let m=ms(),j=Gs(c.sessionMode,c.id,m),S=so();return e.streams.open(S),n.send(c.task,{admission:u,sessionKey:j,turnId:S,source:`schedule:${c.id}:manual`,...Us(c)}).then((E)=>xs(e.channels,c,j,E)).catch(()=>{}),T({scheduleId:c.id,turnId:S,sessionKey:j,outOfBand:!0},202)}),{capability:"write"}),k.add("GET","/v1/agents/:id/config",(o)=>ye(e,s,o,async(n)=>{let l=n.file,c=l===void 0?void 0:await et(l,"utf8");return T({running:n.agent!==void 0,...l===void 0?{editable:!1}:{editable:!0,file:l},settings:[...sA.filter((u)=>GA.includes(u.path)||u.path==="model.<role>").map((u)=>({path:u.path,means:u.means,...u.confirm===void 0?{}:{confirm:u.confirm},...c===void 0?{}:{value:ti(c,u.path.split("."))}})),...hs(c)]})}),{capability:"admin"}),k.add("PATCH","/v1/agents/:id/config",(o)=>ye(e,s,o,async(n)=>{let l=await K(o.request);if(l.kind==="error")return v(l.error,400);let c=G(hn,l.value);if(!c.ok)return v(c.error,400);let u=c.value.changes===void 0;if(u===(c.value.path===void 0))return v({code:u?"config_path_unknown":"config_changes_invalid",message:u?"A request named no path.":"A request named both a path and changes.",hint:'Send { "path", "value" } for one change, or { "changes": [{ "path", "value" }, ...] } for several in one reload.',field:u?"path":"changes"},400);let m=c.value.changes??[{...c.value,path:c.value.path??""}],j=n.file;if(typeof j!=="string")return v({code:"config_not_editable",message:`"${n.id}" was loaded from an object, not from a file, so it has no manifest to change.`,hint:"An embedder holding new settings passes the new object to dispose() and adopt(). This route edits a manifest on disk."},409);let S=m.map((R,ee)=>({change:R,index:ee})).filter(({change:R})=>(co(R.path)??un(R.path))?.via===void 0&&co(R.path)===void 0);if(!u&&S.length>0){let R=S[0];return v({code:"config_path_unknown",message:`${S.map(({change:ee,index:Z})=>`"${ee.path}" (changes.${Z}.path)`).join(", ")} ${S.length===1?"is not a field":"are not fields"} this surface sets. Nothing was written.`,hint:`GET /v1/agents/:id/config lists every one. Nearest to "${R?.change.path}": ${Yt(R?.change.path??"",GA)??GA.join(", ")}.`,field:`changes.${R?.index??0}.path`},400)}let E=[];for(let R of m){let ee=co(R.path)??un(R.path);if(ee===void 0||co(R.path)===void 0)return v({code:"config_path_unknown",message:ee?.via===void 0?`"${R.path}" is not a field this surface sets.`:`"${R.path}" is set by \`${ee.via}\`, not by a dotted path.`,hint:ee?.via===void 0?`GET /v1/agents/:id/config lists every one. Nearest: ${Yt(R.path,GA)??GA.join(", ")}.`:"It is a key inside a list entry, and the source editor matches a key at an indent — it cannot index a sequence. That action also validates the handle against the service that issues it.",field:"path"},400);let Z=R.remove===!0;if(Z===(R.value!==void 0))return v({code:Z?"config_remove_invalid":"config_value_unreadable",message:Z?"A request named both a value and remove: true.":"A request named neither a value nor remove: true.",hint:'Send { "path", "value" } to set a field, or { "path", "remove": true } to take it out.',field:Z?"remove":"value"},400);if(ee.confirm!==void 0&&R.confirm!==!0)return v({code:"config_confirm_required",message:ee.confirm,hint:'Send { "confirm": true } beside the value to make this change anyway. Nothing has been written.',field:"confirm"},409);E.push(ee)}let O;try{O=await ei(j,m.map((R)=>({path:R.path.split("."),value:R.value===void 0?void 0:go(R.value),...R.remove===!0?{remove:!0}:{},providers:e.toolProviderFactories,mediaProviders:e.mediaProviderFactories})))}catch(R){if(_(R))return v(R.toDetail(),400);throw R}let I;if(O.written&&n.agent===void 0)I=Kt(n.id);else if(O.written)try{I=$e(await e.reload(n.id))}catch(R){if(!_(R))throw R;I=R.toDetail()}let z=m.some((R,ee)=>R.path==="delegation.offer"&&O.edits[ee]?.changed===!0)?await Ts(e,n.id,I===void 0):void 0,X=O.edits.map((R,ee)=>({path:E[ee]?.path??"",before:R.before,after:R.after,reflowed:R.reflowed,changed:R.changed}));return T({...u?X[0]:{changes:X},reloaded:O.written&&I===void 0,...I===void 0?{applied:!0}:{applied:!1,pending:I},...z===void 0?{}:{peers:z}})}),{capability:"admin"}),k.add("PATCH","/v1/agents/:id/channels/:channelId",(o)=>L(e,o,async(n)=>{let l=s.channels;if(l===void 0)return v({code:"channels_not_supported",message:"This server cannot change a channel.",hint:"The host did not supply the channel actions — a library caller embedding this handler has to pass them. `dispach serve` does."},501);let c=e.sourceOf(n.id);if(typeof c!=="string")return v({code:"config_not_editable",message:`Agent "${n.id}" was loaded from an object, so it has no manifest to edit.`,hint:"Only an agent loaded from a file can be changed here."},409);let u=await K(o.request);if(u.kind==="error")return v(u.error,400);let m=G(fn,u.value);if(!m.ok)return v(m.error,400);let{enabled:j,credential:S}=m.value;if(j===void 0&&S===void 0)return v({code:"channel_patch_empty",message:"Nothing to change.",hint:'Send { "enabled": true | false } to connect or disconnect it, { "credential": "…" } to set its token, or both.'},400);let E=o.params.channelId??"",O=[];try{if(S!==void 0)O.push(l.setCredential(c,E,S).note);if(j!==void 0)O.push((await l.setEnabled(c,E,j)).note)}catch(q){if(!_(q))throw q;return v(q.toDetail(),400)}let I;try{I=$e(await e.reload(n.id))}catch(q){if(!_(q))throw q;I=q.toDetail()}return T({channelId:E,notes:O,...I===void 0?{applied:!0}:{applied:!1,pending:I}})}),{capability:"admin"}),k.add("POST","/v1/agents/:id/channels/:channelId/unpair",(o)=>L(e,o,async(n)=>{let l=o.params.channelId??"",c=await e.channels.reset(n.id,l);if(c==="reset")return T({channelId:l,note:"Pairing forgotten. The channel offers a new code to scan; the old device may still be listed on the phone, which is the only place it can be removed.",restarted:!1});let u=s.channels,m=e.sourceOf(n.id);if(u===void 0||typeof m!=="string")return v({code:c==="unsupported"?"channel_has_no_pairing":"channel_unknown",message:c==="unsupported"?`Channel "${l}" stores no pairing.`:`Agent "${n.id}" has no channel "${l}" registered.`,hint:"Only a channel linked by scanning a code has one to forget. A credential somebody typed is changed with PATCH on this channel, and a channel is switched off with { enabled: false }.",field:"channelId"},c==="unsupported"?409:404);try{return T({channelId:l,...u.unpair(m,l),restarted:!1})}catch(j){if(!_(j))throw j;return v(j.toDetail(),j.code==="channel_unknown"?404:409)}}),{capability:"admin"}),k.add("GET","/v1/agents/:id/tools",(o)=>L(e,o,(n)=>{let l=n.manifest.phases,c=Wr(l);return T(n.tools.specs().map((u)=>({slug:u.slug,summary:u.summary,mutating:u.mutating,trust:u.trust,...u.trustReason===void 0?{}:{trustReason:u.trustReason},provider:u.provider??"local",tags:u.tags,...c?{phases:Ds(l,u)}:{}})))}),{capability:"read"}),k.add("GET","/v1/agents/:id/skills",(o)=>L(e,o,(n)=>{let l=n.skills;if(l===void 0)return T({skills:[],configured:!1});return T({configured:!0,maxActive:l.maxActive,threshold:l.threshold,cached:l.cached,skills:l.skills.map((c)=>({name:c.name,description:c.frontmatter.description,tokens:c.tokens,...c.frontmatter.whenNotToUse===void 0?{}:{whenNotToUse:c.frontmatter.whenNotToUse},scripts:c.scripts.map((u)=>u.slug),trusted:n.manifest.skills?.trusted===void 0||n.manifest.skills.trusted.includes(c.name)}))})}),{capability:"read"}),k.add("GET","/v1/agents/:id/context",(o)=>L(e,o,async(n)=>{let l=o.url.searchParams.get("sessionKey"),c=o.url.searchParams.get("input");return T(await n.previewContext({...l===null?{}:{sessionKey:l},...c===null?{}:{input:c}}))}),{capability:"read"}),k.add("POST","/v1/channels/:channelId/webhook/:agentId",async(o)=>{let n=await K(o.request);if(n.kind==="error")return v(n.error,400);let l={};o.request.headers.forEach((u,m)=>{l[m.toLowerCase()]=u});let c=await e.channels.handleWebhook(o.params.agentId??"",o.params.channelId??"",{body:n.value,headers:l});return new Response(c.detail??"",{status:c.status,headers:{"content-type":"text/plain; charset=utf-8"}})},{capability:"open"}),k.add("GET","/v1/events",(o)=>{let n=o.url.searchParams.get("agentId");if(n!==null&&!se(o.principal,n))return Q("agent",n);let l=o.url.searchParams.get("types")?.split(",").filter(Boolean),c=o.url.searchParams.get("chunks")==="true",u=l?.includes("model.chunk")===!0,m=c||u,j=l?.filter((S)=>!Jt.includes(S));if(j!==void 0&&j.length>0){let S=Yt(j[0]??"",Jt);return v({code:"unknown_event_type",message:`No such event type: ${j.join(", ")}.`,hint:S===void 0?"The full catalogue is the event table in docs/04-SPEC-WIRE.md. Omit ?types= to receive every event.":`Did you mean "${S}"? The full catalogue is the event table in docs/04-SPEC-WIRE.md.`,field:"types"},400)}return dt({...o.request.signal===void 0?{}:{signal:o.request.signal},start:({send:S})=>(S({event:"stream.subscribed",data:{agentId:n??null,types:l??null,chunks:m,...m&&!c?{implied:"types names model.chunk"}:{}}}),e.bus.on("*",(E)=>{if(n!==null&&E.agentId!==n)return;if(E.agentId!==void 0&&!se(o.principal,E.agentId))return;if(!qn(o.principal,E))return;if(l!==void 0&&l.length>0&&!l.includes(E.type))return;S({event:E.type,data:E})},{chunks:m}))})},{capability:"read",streaming:!0});let ge=async(o)=>{let n;try{n=new URL(o.url)}catch{return v({code:"bad_request_url",message:"The request URL could not be parsed.",hint:"This usually means the server was handed a relative URL. A handler mounted inside another framework needs an absolute request.url."},400)}let l=o.method.toUpperCase();if(l==="OPTIONS"){let S=k.match("OPTIONS",n.pathname);if(S.kind==="method"){let O=k.match("HEAD",n.pathname).kind==="method"&&ds(k,n.pathname),I=[...S.allowed,...S.allowed.includes("GET")&&!O?["HEAD"]:[],"OPTIONS"];return C(o,new Response(null,{status:204,headers:{allow:I.join(", "),...s.origin===void 0?{}:Or(o,I)}}))}}if(l==="HEAD"){let S=k.match("GET",n.pathname);if(S.kind==="found"){if(S.streaming)return v({code:"method_not_allowed",message:`HEAD is not allowed on ${n.pathname}.`,hint:"This path answers with an open event stream. A HEAD would have to start one and then throw the body away, leaving a subscription nothing ever closes — so it is refused rather than leaked. Use GET, or GET /v1/health to check the server is up."},405,{allow:"GET, OPTIONS"});let E=H(o);if(E!==void 0)return E;let O=await D(o,n.pathname,S.capability);if(O instanceof Response)return O;let I=await zt(S.handler,{request:o,url:n,params:S.params,principal:O});return C(o,new Response(null,{status:I.status,headers:I.headers}))}}let c=Y(l,n.pathname);if(c!==void 0){let S=H(o);if(S!==void 0)return S;return C(o,await oe(o,n,c))}let u=k.match(l,n.pathname);if(u.kind==="method")return v({code:"method_not_allowed",message:`${l} is not allowed on ${n.pathname}.`,hint:`This path accepts ${u.allowed.join(", ")}.`},405,{allow:u.allowed.join(", ")});if(u.kind==="none")return Rt(o.method,n.pathname);let m=H(o);if(m!==void 0)return m;let j=await D(o,n.pathname,u.capability);if(j instanceof Response)return j;return C(o,await zt(u.handler,{request:o,url:n,params:u.params,principal:j}))},Y=(o,n)=>{let l=/^\/v1\/agents\/([^/]+)\/plugins\/([^/]+)(\/.*)?$/.exec(n);if(l!==null){let u=e.list().find((E)=>E.id===decodeURIComponent(l[1]??"")),m=l[2]??"",j=l[3]??"/",S=u?.pluginRoutes.find((E)=>E.plugin===m&&E.method===o&&E.path===j);return u===void 0||S===void 0?void 0:{agent:u,route:S,path:j}}let c=e.list().flatMap((u)=>u.pluginRoutes.filter((m)=>m.root===n&&m.method===o).map((m)=>({agent:u,route:m,path:m.path})));return c.length===1?c[0]:void 0},oe=async(o,n,l)=>{let{agent:c,route:u,path:m}=l,j=u.capability==="open"?{kind:"open"}:await D(o,n.pathname,u.capability);if(j instanceof Response)return j;if(j.kind==="claim"||!se(j,c.id))return Rt(o.method,n.pathname);let S=j.kind==="key"?{kind:"key",keyId:j.keyId,label:j.label??""}:u.capability==="open"?{kind:"anonymous"}:{kind:"operator"};try{return await u.handler({request:o,url:n,path:m,caller:S})}catch(E){return v({code:"plugin_route_failed",message:`Plugin "${u.plugin}" failed answering ${o.method} ${n.pathname}: ${E instanceof Error?E.message:String(E)}`,hint:"This is the plugin's error, not the runtime's. The agent's own routes are unaffected."},500)}};return Object.assign(ge,{authenticate:(o)=>D(o,"/v1/ws","read"),routes:()=>k.routes().map(({method:o,pattern:n,capability:l})=>({method:o,pattern:n,capability:l}))})}function Ot(s){if(s.origin!=="manifest")return;return v({code:"schedule_manifest_owned",message:`Schedule "${s.id}" is declared in this agent's manifest, so the manifest decides it.`,hint:"Writing it here would last until the next start — reconciliation restores every field from the file, enabled included. Change the `schedules:` entry instead, with PATCH /v1/agents/:id/config, or create a separate schedule through this route."},409)}async function $t(s,e,d,p){if(d===null||typeof d!=="object"||Array.isArray(d))return v({code:"schedule_invalid",message:"A schedule must be a JSON object.",hint:"Send { id, kind, expr, task, deliver } — see docs/02-SPEC-MANIFEST.md."},400);try{let b=Fs({agentId:e.id,body:d,channelIds:e.manifest.channels.map((N)=>N.id),roleNames:Object.keys(e.manifest.model),toolSpecs:e.tools.specs(),now:Date.now(),origin:"api",...p===void 0?{}:{existing:p}}),w=await e.store.schedules.upsert(b);return s.scheduler.changed(),T(w,p===void 0?201:200)}catch(b){let w=_(b)?b.toDetail():Re("schedule_invalid","See docs/02-SPEC-MANIFEST.md for the schedule fields; the server's log has the cause.",b);return v(w,400)}}function qe(s,e){let d=es(s,e.request);if(d===void 0)throw new ne({code:"web_asset_missing",message:`No web asset for ${s}.`,hint:"The routes in handler.ts and the table in web.ts have diverged, which spec.test.ts asserts cannot happen — so this build is inconsistent. Rebuild with `bun run build`."});return d}function Re(s,e,d){return process.stderr.write(`${s}: ${d instanceof Error?d.stack??d.message:String(d)}
99
+ `),{code:s,message:"An unexpected failure; the server's log has the cause.",hint:e}}function T(s,e=200){return new Response(JSON.stringify(s),{status:e,headers:{"content-type":"application/json; charset=utf-8"}})}function cs(s){return s==="/v1/health"||s==="/v1/ready"||s.startsWith("/v1/channels/")||Jr.includes(s)||s==="/docs"||s==="/v1/openapi.json"}function ds(s,e){let d=s.match("GET",e);return d.kind==="found"&&d.streaming}async function zt(s,e){try{return await s(e)}catch(d){if(_(d))return v(d.toDetail(),400);return v(Re("internal_error","Not caused by the request. The server's log has the cause, and the runtime's event stream carries what happened around it.",d),500)}}function Rt(s,e){return v({code:"not_found",message:`No route for ${s} ${e}.`,hint:"Every path is under /v1. See docs/04-SPEC-WIRE.md for the surface."},404)}function Q(s,e,d){return v({code:`${s}_not_found`,message:`No ${s} "${e}".`,hint:d??"Check the id — it is case-sensitive, and a session key includes its channel segment."},404)}function us(s){let e=s.headers.get("authorization")??"";if(!e.startsWith("Bearer "))return;let d=e.slice(7);return d===""?void 0:d}function Mt(s,e,d){let p=d.params.id??"";if(!se(d.principal,p))return{kind:"response",response:Q("agent",p)};let b=e.secrets;if(b===void 0)return{kind:"response",response:v({code:"secrets_not_supported",message:"This server cannot write an agent's credentials.",hint:"Credentials go into the .env beside an agent's manifest, and this process was built without a writer for it. Set them where the agent lives, with `config env`, and reload it."},501)};let w=s.sourceOf(p),N=typeof w==="string"?w:e.resolveAgent?.(p);if(N===void 0)return{kind:"response",response:Q("agent",p)};return{kind:"found",id:p,manifestPath:N,admin:b}}function Lt(s){return{...s,failing:s.consecutiveFailures>0}}function Dt(s,e){let d=Ne(s);if(d.agentIds!==void 0){let p=e.scope?.agents;if(p===void 0||!p.every((b)=>d.agentIds?.includes(b)))return!1}if(d.sessionPrefix!==void 0){let p=e.scope?.sessionPrefix;if(p===void 0||!p.startsWith(d.sessionPrefix))return!1}return!0}function Ut(s,e){let d=s.searchParams.get(e);if(d===null)return;let p=Number(d);return Number.isSafeInteger(p)&&p>0?p:null}function Bt(s){let e=s.searchParams.get("by"),d=e===null?["agent","model"]:e.split(",").filter((w)=>w!==""),p=d.filter((w)=>!ni.includes(w));if(p.length>0)return{kind:"error",error:{code:"usage_group_invalid",message:`Cannot group usage by ${p.join(", ")}.`,hint:`Group by any of ${ni.join(", ")}, comma-separated, or pass by= for one total.`,field:"by"}};let b={};for(let w of["from","to"]){let N=s.searchParams.get(w);if(N===null)continue;let A=Date.parse(N);if(Number.isNaN(A))return{kind:"error",error:{code:"usage_range_invalid",message:`${w} is ${JSON.stringify(N)}, which is not a date.`,hint:"Send ISO-8601, like 2026-09-01 or 2026-09-01T00:00:00Z. `from` is inclusive and `to` exclusive, so a month is from=2026-09-01&to=2026-10-01.",field:w}};b[w]=new Date(A).toISOString()}return{kind:"ok",value:{by:d,...b}}}function Ft(s){return{id:s.agentId,name:s.agentId,status:"disabled",...s.reason===void 0?{}:{reason:s.reason},...s.disabledAt===void 0?{}:{disabledAt:s.disabledAt}}}function ye(s,e,d,p){let b=d.params.id??"";if(!se(d.principal,b))return Q("agent",b);let w=s.list().find((A)=>A.id===b);if(w!==void 0){let A=s.sourceOf(b);return p({id:b,agent:w,file:typeof A==="string"?A:void 0})}let N=e.resolveAgent?.(b);if(N===void 0)return Q("agent",b);return p({id:b,agent:void 0,file:N})}function Kt(s){return{code:"agent_not_running",message:`${s} is not running, so the change is on disk and not yet in force.`,hint:`POST /v1/agents/${s}/start loads it from the files as they are now. GET /v1/agents/${s} says whether they load.`}}function L(s,e,d){let p=e.params.id??"",b=s.list().find((w)=>w.id===p);if(b===void 0)return Q("agent",p);if(!se(e.principal,p))return Q("agent",p);return d(b)}function ps(s,e){if(!ct(s))return e;return e.filter((d)=>se(s,d.id))}function Ge(s,e){if(!ct(s))return e;return e.filter((d)=>ve(s,d.sessionKey))}function fe(s,e){return ve(s.principal,e)?void 0:Q("session",e)}function Ht(s,e){if(e===void 0)return ct(s.principal);return!ve(s.principal,e.sessionKey)}function hs(s){if(s===void 0)return[];let e=ti(s,["model"]);if(e===null||typeof e!=="object"||Array.isArray(e))return[];let d=un("model.<role>")?.means??"a named model role";return Object.entries(e).filter(([p])=>p!=="main").map(([p,b])=>({path:`model.${p}`,means:d,value:b}))}async function We(s,e){let d=Zr.safeParse(Rs(await et(e,"utf8")));if(!d.success)return v({code:"workspace_manifest_invalid",message:`${s}'s manifest does not parse, so its workspace files cannot be named.`,hint:"Fix the manifest first: PATCH /v1/agents/:id/config, and GET /v1/agents/:id for what is wrong."},409);let p=Ae(e),b=d.data.context,w=we(p,b.workspace),N=b.soul,A=[...bs(b,p).refs.map((U)=>({path:U.path,tier:U.tier,field:U.field})),...N?.file===void 0?[]:[{path:we(w,N.file),tier:"soul",field:"context.soul.file"}],...N?.distilled===void 0?[]:[{path:we(w,N.distilled),tier:"soul",field:"context.soul.distilled"}]];return{workspaceDir:w,declared:A}}function Gt(s,e,d){return s.find((p)=>p.path===we(e,d)||Te(p.path)===d)?.path}function Ve(s,e,d){return v({code:"workspace_file_unknown",message:`${e} is not one of ${s}'s workspace files.`,hint:`Declared: ${d.map((p)=>Te(p.path)).join(", ")||"none"}. A new file is added to context.static or context.volatile with PATCH /config first.`,field:"file"},404)}function Wt(s,e){let d=e.manifest.phases,p=Wr(d);return{id:e.id,name:e.manifest.name??e.id,...e.manifest.description===void 0?{}:{description:e.manifest.description},ask:e.manifest.delegation?.ask===!0,status:"loaded",model:e.manifest.model.main.id,channels:e.manifest.channels.map((b)=>{let w=s.channels.statusOf(e.id).find((A)=>A.id===b.id),N=typeof b.tokenEnv==="string"?b.tokenEnv:void 0;return{...w??{},id:b.id,type:b.type,enabled:b.enabled,...N===void 0?{}:{credentialEnv:N,credentialSet:e.hasEnv(N)}}}),entryPhase:p?ws(d)??null:null,...p?{phases:Object.keys(d)}:{},sessionScope:e.manifest.sessions?.scope??"channel-peer"}}function Qe(s){return{...s.disabledAt===void 0?{}:{disabledAt:s.disabledAt},...s.reason===void 0?{}:{reason:s.reason}}}async function K(s,e=as){let d=Number.parseInt(s.headers.get("content-length")??"0",10);if(Number.isFinite(d)&&d>e)return{kind:"error",error:{code:"body_too_large",message:`The request body declares ${d} bytes; the limit is ${e}.`,hint:"This cap is enforced before a channel plugin sees anything, so a plugin never has to defend against a large POST."}};let p=await s.text();if(p.length>e)return{kind:"error",error:{code:"body_too_large",message:`The request body is ${p.length} bytes; the limit is ${e}.`,hint:"Send less. A message longer than this is not a message."}};if(p==="")return{kind:"ok",value:{}};try{return{kind:"ok",value:JSON.parse(p)}}catch{return{kind:"error",error:{code:"body_not_json",message:"The request body is not valid JSON.",hint:"Send application/json. A shell quoting mistake is the usual cause — check for unescaped quotes inside the payload."}}}}function Je(s){if(s===void 0||s===null)return{kind:"ok",from:void 0};let e=(p,b,w="from")=>({kind:"error",error:{code:"sender_invalid",message:p,hint:b,field:w}});if(typeof s!=="object")return e("from must be an object.",'Send { "from": { "id": "agent:ops-bot", "kind": "agent" } }, or omit it entirely for a turn the token-holder is sending itself.');let d=s;if(typeof d.id!=="string"||d.id.trim()==="")return e("from.id is required and must be a non-empty string.","Use a stable identity in your own namespace — `agent:ops-bot`, `user:018f…`, an email address. It is opaque to this runtime and is recorded on the turn so an audit can answer who asked.","from.id");if(d.id.length>It)return e(`from.id is ${d.id.length} characters, over the ${It} limit.`,"A sender id is an identifier, not a payload. It is rendered into the prompt's fence label, so an unbounded one spends the context window the message needs.","from.id");if(typeof d.kind!=="string"||!qt.includes(d.kind)){let p=typeof d.kind==="string"?Yt(d.kind,qt):void 0;return e(`from.kind must be one of: ${qt.join(", ")}.`,`${p===void 0?"":`Did you mean "${p}"? `}This field decides the trust boundary — "agent" fences the message and blocks mutating tools for the turn, "user" does not — so there is no default and an unknown value is refused rather than guessed at. A turn the token-holder is sending itself omits "from".`,"from.kind")}if(d.name!==void 0&&typeof d.name!=="string")return e("from.name must be a string when present.","It is a display name only and is rendered inside the fence, never above it. Omit it if you have none.","from.name");return{kind:"ok",from:{id:d.id,kind:d.kind,...d.name===void 0?{}:{name:d.name.slice(0,ss)}}}}function fs(s){let e=s.headers.get("idempotency-key");if(e===null)return{kind:"ok",key:void 0};let d=e.trim(),p=(b)=>({kind:"error",error:{code:"idempotency_key_invalid",message:b,hint:`Send 1-${He} printable ASCII characters that are unique per logical request — a UUID is the usual choice. Omit the header entirely to accept that a retry runs the turn again. Printable ASCII because the key is a database key, and node:sqlite truncates a bound string at a NUL byte where bun:sqlite stores it whole.`,field:"Idempotency-Key"}});if(d==="")return p("Idempotency-Key is present but empty.");if(d.length>He)return p(`Idempotency-Key is ${d.length} characters, over the ${He} limit.`);if(!/^[\x20-\x7e]+$/.test(d))return p("Idempotency-Key contains characters that are not printable ASCII.");return{kind:"ok",key:d}}async function gs(s,e){let d=new TextEncoder().encode(`${s}\x00${e}`),p=await crypto.subtle.digest("SHA-256",d);return Array.from(new Uint8Array(p)).map((b)=>b.toString(16).padStart(2,"0")).join("")}function js(s){if(s===void 0||s===null||s==="none")return{kind:"ok",target:void 0};if(typeof s==="object"){let e=s;if(typeof e.channel==="string"&&typeof e.to==="string")return{kind:"ok",target:{channel:e.channel,to:e.to}}}return{kind:"error",error:{code:"deliver_invalid",message:'deliver must be "none" or { channel, to }.',hint:'A bare channel id is not enough on an API turn: the request has no originating conversation, so there is no recipient to infer. Send { "channel": "tg", "to": "12345" }, or "none" to read the reply from the event stream.',field:"deliver"}}}function Ns(s){let e=s.status==="running";return dt({start:({send:d,close:p})=>{d({event:e?"stream.unavailable":"stream.ended",data:{turnId:s.turnId,status:s.status,sessionKey:s.sessionKey,...e?{reason:"no buffer for this turn in this process",hint:"The turn is recorded as running but is not observable here — its events are buffered in whichever process is executing it, and buffers are in-memory and per-process. Poll GET /v1/agents/:id/turns/:turnId for the outcome."}:{steps:s.steps,...s.errorCode===void 0?{}:{errorCode:s.errorCode},hint:"This turn finished before you attached and its buffer has been evicted. Its full text is in GET /v1/agents/:id/turns/:turnId."}}}),p();return}})}function Vt(s,e,d){return dt({...d?.status===void 0?{}:{status:d.status},start:({send:p,close:b})=>{if(d?.accepted!==void 0)p({event:"turn.accepted",data:d.accepted});let w=s.streams.attach(e,(N)=>{if(p({event:N.type,data:N}),N.type==="turn.end"&&N.turnId===e)b()},{chunks:d?.chunks===!0,children:d?.children===!0});if(w===void 0){p({event:"stream.unavailable",data:{turnId:e,reason:"no buffer for this turn in this process",hint:"Read the final state from GET /v1/agents/:id/turns/:turnId. Buffers are in-memory and are evicted after a turn ends."}}),b();return}p({event:"stream.replay",data:{turnId:e,state:w.state,events:w.replay.length,truncated:w.truncated,dropped:w.dropped,chunks:w.chunks,...w.truncated?{hint:`The oldest ${w.dropped} event(s) of this turn were discarded to stay under the buffer cap, so this replay starts mid-turn. The turn's final text is complete in GET /v1/agents/:id/turns/:turnId.`}:{}}});for(let N of w.replay)p({event:N.type,data:N});if(w.state==="ended")b();return()=>w.unsubscribe()}})}async function Ts(s,e,d){let p=s.list().filter((w)=>{let N=w.manifest.delegation?.to;return w.id!==e&&(N==="*"||(N?.includes(e)??!1))}),b=[];for(let w of p){if(!d){b.push({id:w.id,applied:!1,pending:{code:"reload_pending",message:`${e}'s own reload is waiting for running turns, so ${w.id} still lists its old offer.`,hint:`POST /v1/agents/${w.id}/reload once ${e}'s agent.reloaded event arrives.`}});continue}try{let N=$e(await s.reload(w.id));b.push(N===void 0?{id:w.id,applied:!0}:{id:w.id,applied:!1,pending:N})}catch(N){if(!_(N))throw N;b.push({id:w.id,applied:!1,pending:N.toDetail()})}}return b}function $e(s){if(s.status!=="pending")return;return{code:"reload_pending",message:`It applies when the ${s.running} running turn(s) finish; they complete on the settings they started with.`,hint:`New turns keep the old settings for ${s.holdAfterMs} ms, then wait and start on the new ones. The agent.reloaded event says when it is in force.`}}var Es=new Set([".env",".api-token",".venv","node_modules",".git"]),Ze={env:[".env",".api-token"],git:[".git"]};async function Qt(s,e,d=new Set){let p=[],b=async(w)=>{for(let N of await ta(w,{withFileTypes:!0})){if(e.has(N.name))continue;let A=tt(w,N.name);if(d.has(we(A)))continue;if(N.isDirectory())await b(A);else if(N.isFile())p.push({name:ra(s,A).split(sa).join("/"),path:A})}};return await b(s),p}function ts(){let s=Cr(),e=!1;return{token:s,live:()=>!e,spend:()=>{if(e)return!1;return e=!0,!0}}}function an(s){let e=s.startsWith("[")&&s.endsWith("]")?s.slice(1,-1):s,d=e==="0.0.0.0"||e==="::"||e===""?"127.0.0.1":e;return d.includes(":")?`[${d}]`:d}function As(s,e,d){return`http://${an(s)}:${e}/?claim=${d}`}function ns(s,e,d){return`curl -sX POST http://${an(s)}:${e}/v1/keys -H 'Authorization: Bearer ${d}' -H 'content-type: application/json' -d '{"label":"my browser"}'`}function Yn(s,e,d=new Map){let p=new Set,b,w=0,N,A=(C)=>{let ae=C.type==="model.chunk";for(let M of p){if(M.data.agentId!==void 0&&C.agentId!==M.data.agentId)continue;if(C.agentId!==void 0&&!se(M.data.principal,C.agentId))continue;if(!qn(M.data.principal,C))continue;if(ae&&!M.data.chunks)continue;try{M.send(JSON.stringify(C))}catch{}}},U=()=>{if(w+=1,N===void 0)N=s.bus.on("model.chunk",A)},H=()=>{if(w===0)return;if(w-=1,w===0)N?.(),N=void 0};return{async accept(C){let ae=new URL(C.url),M=ca(C),D=ae.searchParams.get("token"),F=await e(da(C,M??D??""));if(F instanceof Response)return{kind:"reject",response:F};let J=ae.searchParams.get("agentId");if(J!==null&&!se(F,J))return{kind:"reject",response:new Response(JSON.stringify({error:{code:"agent_not_found",message:`No agent "${J}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}),{status:404,headers:{"content-type":"application/json"}})};return{kind:"accept",session:{agentId:J??void 0,chunks:ae.searchParams.get("chunks")==="true",principal:F},...M===void 0?{}:{protocol:Ee}}},handlers:{open(C){if(p.add(C),b===void 0)b=s.bus.on("*",A);if(C.data.chunks)U();C.send(JSON.stringify({type:"ws.open",agentId:C.data.agentId??null,chunks:C.data.chunks}))},message(C,ae){let M;try{M=JSON.parse(typeof ae==="string"?ae:new TextDecoder().decode(ae))}catch{C.send(JSON.stringify({type:"ws.error",code:"frame_not_json"}));return}if(M.type==="ping"){C.send(JSON.stringify({type:"pong"}));return}if(M.type==="subscribe"){if(M.agentId===void 0&&M.sessionKey!==void 0){C.send(JSON.stringify({type:"ws.error",code:"subscribe_needs_agent_id",hint:"Send { type: 'subscribe', agentId: '<agent>' }. A socket filters on the agent an event carries; sessionKey names a conversation and can never match one, so a socket pointed with it receives nothing."}));return}let Y=typeof M.chunks==="boolean"?M.chunks:C.data.chunks;if(Y&&!C.data.chunks)U();else if(!Y&&C.data.chunks)H();let oe=M.agentId??C.data.agentId;if(oe!==void 0&&!se(C.data.principal,oe)){C.send(JSON.stringify({type:"ws.error",error:{code:"agent_not_found",message:`No agent "${oe}".`,hint:"Check the id — it is case-sensitive. A key scoped away from an agent sees exactly what a caller asking for one that does not exist sees."}}));return}C.data={agentId:oe,chunks:Y,principal:C.data.principal},C.send(JSON.stringify({type:"ws.subscribed",agentId:C.data.agentId??null,chunks:C.data.chunks}));return}if(M.type==="stop"){let Y=M.turnId===void 0?void 0:d.get(M.turnId);Y?.abort(),C.send(JSON.stringify({type:"ws.stopping",turnId:M.turnId??null,found:Y!==void 0}));return}if(M.type!=="message"){C.send(JSON.stringify({type:"ws.error",code:"unknown_frame_type"}));return}let D=C.data.agentId,k=s.list().find((Y)=>Y.id===D);if(k===void 0){C.send(JSON.stringify({type:"ws.error",code:"agent_not_found"}));return}let F=M.text??"";if(F.trim()===""){C.send(JSON.stringify({type:"ws.error",code:"message_text_required"}));return}let J=Oe(C.data.principal,void 0),ce=J.ok?J.from:void 0,re=M.sessionKey??"api:default",B=(Y,oe)=>{let o=so(),n=new AbortController;d.set(o,n),C.send(JSON.stringify({type:"ws.accepted",turnId:o,sessionKey:oe})),k.send(F,{admission:Y,sessionKey:oe,sessionResolved:!0,turnId:o,source:"ws",...ce===void 0?{}:{from:ce},signal:n.signal}).catch(()=>{}).finally(()=>d.delete(o))},ue=(k.manifest.sessions?.scope??"channel-peer")!=="channel-peer",ie=(Y)=>{if(!Y.ok){C.send(JSON.stringify({type:"ws.error",...Y.error.toDetail()}));return}if(!ue){B(Y,re);return}rt(k,C.data.principal,re,ce).then((oe)=>B(Y,oe),(oe)=>{Y.release(),process.stderr.write(`internal: ${oe instanceof Error?oe.stack??oe.message:String(oe)}
100
+ `),C.send(JSON.stringify({type:"ws.error",code:"internal_error",message:"The conversation for this message could not be read."}))})},ge=k.admitNow();if(ge!==void 0){ie(ge);return}k.admit().then(ie,(Y)=>{process.stderr.write(`internal: ${Y instanceof Error?Y.stack??Y.message:String(Y)}
101
+ `),C.send(JSON.stringify({type:"ws.error",code:"internal_error",message:"The turn budget could not be read."}))})},close(C){if(p.delete(C)&&C.data.chunks)H();if(p.size===0)b?.(),b=void 0}},closeAll(){for(let C of p)try{C.close(1001,"server stopping")}catch{}p.clear(),b?.(),b=void 0,N?.(),N=void 0,w=0}}}async function os(s){let{host:e,port:d,runtime:p}=s;if(!Me(e)&&s.token===void 0)throw new ne({code:"server_public_without_token",message:`Refusing to bind ${e}:${d} with no API token.`,hint:`Set ${V.envPrefix}API_TOKEN (or the variable a manifest names in server.tokenEnv instead), or bind 127.0.0.1. A public bind with no token exposes every endpoint — including the ones that start a turn — to anyone who can reach the port, and behaves identically to a safe one until someone finds it.`,field:"server.host"});let b=new Map,w=ls({runtime:p,...s.token===void 0?{}:{token:s.token},...s.token===void 0?{allowUnauthenticated:!0}:{},...s.now===void 0?{}:{now:s.now},running:b,...s.approvals===void 0?{}:{approvals:s.approvals},...s.claim===void 0?{}:{claim:s.claim},...s.resolveAgent===void 0?{}:{resolveAgent:s.resolveAgent},...s.provision===void 0?{}:{provision:s.provision},...s.channels===void 0?{}:{channels:s.channels},...s.remover===void 0?{}:{remover:s.remover},...s.secrets===void 0?{}:{secrets:s.secrets},...s.home===void 0?{}:{home:s.home},origin:{host:s.host,...s.allowedOrigins===void 0?{}:{allowedOrigins:s.allowedOrigins},...s.allowedHosts===void 0?{}:{allowedHosts:s.allowedHosts}}});if(s.engine==="bun"||s.engine===void 0&&typeof Bun<"u"&&typeof Bun.serve==="function")return Cs(w,s,b);return Is(w,s,b)}function Cs(s,e,d){let p=Yn(e.runtime,s.authenticate,d),b=Bun.serve({port:e.port,hostname:e.host,idleTimeout:Math.min(255,Math.ceil(Wn/1000*3)),fetch:async(w,N)=>{if(new URL(w.url).pathname!=="/v1/ws")return s(w);let U=Le(w,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(U!==void 0)return new Response(JSON.stringify({error:U}),{status:403,headers:{"content-type":"application/json; charset=utf-8"}});let H=await p.accept(w);if(H.kind==="reject")return H.response;if(N.upgrade(w,{data:H.session,...H.protocol===void 0?{}:{headers:{"sec-websocket-protocol":H.protocol}}}))return;return new Response("upgrade failed",{status:400})},websocket:{open:(w)=>p.handlers.open(w),message:(w,N)=>p.handlers.message(w,N),close:(w)=>p.handlers.close(w)}});return{url:`http://${e.host}:${b.port}`,port:b.port??e.port,host:e.host,websocket:!0,stop:async()=>{p.closeAll(),await b.stop(!0)}}}async function Is(s,e,d){let{createServer:p}=await import("node:http"),{WebSocketServer:b}=await import("./wrapper-5zhcdmnk.js"),w=Yn(e.runtime,s.authenticate,d),N=(D,k)=>{let F=`http://${D.headers.host??`${e.host}:${e.port}`}${D.url??"/"}`,J=new Headers;for(let[re,B]of Object.entries(D.headers))if(typeof B==="string")J.set(re,B);else if(Array.isArray(B))J.set(re,B.join(", "));let ce=D.method??"GET";return new Request(F,{method:ce,headers:J,...ce==="GET"||ce==="HEAD"||k===void 0?{}:{body:k}})},A=p((D,k)=>{(async()=>{let F=[];for await(let B of D)F.push(B);let J=await s(N(D,Buffer.concat(F))),ce={};if(J.headers.forEach((B,ue)=>{ce[ue]=B}),k.writeHead(J.status,ce),J.body===null){k.end();return}let re=J.body.getReader();k.on("close",()=>void re.cancel().catch(()=>{}));for(;;){let{done:B,value:ue}=await re.read();if(B)break;k.write(Buffer.from(ue))}k.end()})().catch(()=>{if(!k.headersSent)k.writeHead(500);k.end()})}),U=new WeakMap,H=new b({noServer:!0,handleProtocols:(D,k)=>U.get(k)??!1}),C=(D,k,F)=>{D.end(`HTTP/1.1 ${k} Refused\r
102
102
  content-type: application/json; charset=utf-8\r
103
- content-length: ${Buffer.byteLength(L)}\r
103
+ content-length: ${Buffer.byteLength(F)}\r
104
104
  connection: close\r
105
105
  \r
106
- ${L}`)};N.on("upgrade",(K,g,L)=>{(async()=>{let Y=b(K);if(new URL(Y.url).pathname!=="/v1/ws"){g.destroy();return}let re=Ne(Y,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(re!==void 0){j(g,403,JSON.stringify({error:re}));return}let J=await m.accept(Y);if(J.kind==="reject"){j(g,J.response.status,await J.response.text());return}if(J.protocol!==void 0)V.set(K,J.protocol);F.handleUpgrade(K,g,L,(O)=>{let se={data:J.session,send:(ee)=>O.send(ee),close:(ee,ce)=>O.close(ee,ce)};O.on("message",(ee,ce)=>{let G=Array.isArray(ee)?Buffer.concat(ee):ee instanceof ArrayBuffer?Buffer.from(ee):ee;m.handlers.message(se,ce?new Uint8Array(G):G.toString("utf8"))}),O.on("close",()=>m.handlers.close(se)),m.handlers.open(se)})})().catch(()=>g.destroy())}),await new Promise((K,g)=>{N.once("error",g),N.listen(e.port,e.host,()=>{N.removeListener("error",g),K()})});let Z=N.address(),M=typeof Z==="object"&&Z!==null?Z.port:e.port;return{url:`http://${e.host}:${M}`,port:M,host:e.host,websocket:!0,stop:()=>new Promise((K)=>{m.closeAll(),F.close(),N.closeAllConnections?.(),N.close(()=>K())})}}function AA(a,e){let d=new URL(a);if(d.pathname="/",d.hostname=an(d.hostname),e!==void 0&&e!=="")d.searchParams.set("agent",e);return d.toString()}
107
- export{Yr,As,an,ns,os,rs,AA};
106
+ ${F}`)};A.on("upgrade",(D,k,F)=>{(async()=>{let J=N(D);if(new URL(J.url).pathname!=="/v1/ws"){k.destroy();return}let ce=Le(J,{host:e.host,...e.allowedOrigins===void 0?{}:{allowedOrigins:e.allowedOrigins},...e.allowedHosts===void 0?{}:{allowedHosts:e.allowedHosts}});if(ce!==void 0){C(k,403,JSON.stringify({error:ce}));return}let re=await w.accept(J);if(re.kind==="reject"){C(k,re.response.status,await re.response.text());return}if(re.protocol!==void 0)U.set(D,re.protocol);H.handleUpgrade(D,k,F,(B)=>{let ue={data:re.session,send:(ie)=>B.send(ie),close:(ie,ge)=>B.close(ie,ge)};B.on("message",(ie,ge)=>{let Y=Array.isArray(ie)?Buffer.concat(ie):ie instanceof ArrayBuffer?Buffer.from(ie):ie;w.handlers.message(ue,ge?new Uint8Array(Y):Y.toString("utf8"))}),B.on("close",()=>w.handlers.close(ue)),w.handlers.open(ue)})})().catch(()=>k.destroy())}),await new Promise((D,k)=>{A.once("error",k),A.listen(e.port,e.host,()=>{A.removeListener("error",k),D()})});let ae=A.address(),M=typeof ae==="object"&&ae!==null?ae.port:e.port;return{url:`http://${e.host}:${M}`,port:M,host:e.host,websocket:!0,stop:()=>new Promise((D)=>{w.closeAll(),H.close(),A.closeAllConnections?.(),A.close(()=>D())})}}function nA(s,e){let d=new URL(s);if(d.pathname="/",d.hostname=an(d.hostname),e!==void 0&&e!=="")d.searchParams.set("agent",e);return d.toString()}
107
+ export{Yr,ts,an,As,ns,os,nA};
108
108
 
109
- //# debugId=14E4FD5F285FAA2264756E2164756E21
110
- //# sourceMappingURL=index-k8e9f466.js.map
109
+ //# debugId=CFBD17832ADD99F364756E2164756E21
110
+ //# sourceMappingURL=index-s0mfq8t7.js.map