dispach 0.2.4 → 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 (187) hide show
  1. package/README.md +32 -33
  2. package/dist/APEv2Parser-rt8hyadd.js +5 -0
  3. package/dist/{FlacParser-8xprykrh.js.map → APEv2Parser-rt8hyadd.js.map} +1 -1
  4. package/dist/{AiffParser-ns1y9f0g.js → AiffParser-gvpmtb2e.js} +3 -3
  5. package/dist/{AiffParser-ns1y9f0g.js.map → AiffParser-gvpmtb2e.js.map} +1 -1
  6. package/dist/{App-wkpkwgjt.js → App-18dvbyev.js} +8 -8
  7. package/dist/{App-wkpkwgjt.js.map → App-18dvbyev.js.map} +1 -1
  8. package/dist/{AsfParser-bae2a1yf.js → AsfParser-h9zyh6cx.js} +3 -3
  9. package/dist/{AsfParser-bae2a1yf.js.map → AsfParser-h9zyh6cx.js.map} +1 -1
  10. package/dist/{ConfigEditor-hy9jtas3.js → ConfigEditor-444m13ta.js} +3 -3
  11. package/dist/{ConfigEditor-hy9jtas3.js.map → ConfigEditor-444m13ta.js.map} +1 -1
  12. package/dist/{DsdiffParser-s0zvxnfa.js → DsdiffParser-gxqv4gn1.js} +3 -3
  13. package/dist/{DsdiffParser-s0zvxnfa.js.map → DsdiffParser-gxqv4gn1.js.map} +1 -1
  14. package/dist/{DsfParser-90mvzt4v.js → DsfParser-sndt4jbk.js} +3 -3
  15. package/dist/{DsfParser-90mvzt4v.js.map → DsfParser-sndt4jbk.js.map} +1 -1
  16. package/dist/FlacParser-rmkpvf9e.js +5 -0
  17. package/dist/{APEv2Parser-x13n424p.js.map → FlacParser-rmkpvf9e.js.map} +1 -1
  18. package/dist/{KeyProbe-fk5krzks.js → KeyProbe-6t531sy6.js} +3 -3
  19. package/dist/{KeyProbe-fk5krzks.js.map → KeyProbe-6t531sy6.js.map} +1 -1
  20. package/dist/{MP4Parser-nmvbkq21.js → MP4Parser-87xfsck4.js} +3 -3
  21. package/dist/{MP4Parser-nmvbkq21.js.map → MP4Parser-87xfsck4.js.map} +1 -1
  22. package/dist/{MatroskaParser-tsmz2qfq.js → MatroskaParser-7krspfgx.js} +3 -3
  23. package/dist/{MatroskaParser-tsmz2qfq.js.map → MatroskaParser-7krspfgx.js.map} +1 -1
  24. package/dist/{MpegParser-y5fjpaz9.js → MpegParser-jcs35q0h.js} +3 -3
  25. package/dist/{MpegParser-y5fjpaz9.js.map → MpegParser-jcs35q0h.js.map} +1 -1
  26. package/dist/{MusepackParser-544q0byg.js → MusepackParser-d4zfnzk3.js} +3 -3
  27. package/dist/{MusepackParser-544q0byg.js.map → MusepackParser-d4zfnzk3.js.map} +1 -1
  28. package/dist/{OggParser-v77rbjnt.js → OggParser-fbspjs7v.js} +3 -3
  29. package/dist/{OggParser-v77rbjnt.js.map → OggParser-fbspjs7v.js.map} +1 -1
  30. package/dist/{Picker-32m79nmp.js → Picker-x6aj42tc.js} +3 -3
  31. package/dist/{Picker-32m79nmp.js.map → Picker-x6aj42tc.js.map} +1 -1
  32. package/dist/{SessionPicker-9p06npt5.js → SessionPicker-pngdv97x.js} +3 -3
  33. package/dist/{SessionPicker-9p06npt5.js.map → SessionPicker-pngdv97x.js.map} +1 -1
  34. package/dist/{SkillBrowser-ezdx3xsh.js → SkillBrowser-3mnzkakr.js} +3 -3
  35. package/dist/{SkillBrowser-ezdx3xsh.js.map → SkillBrowser-3mnzkakr.js.map} +1 -1
  36. package/dist/{WavPackParser-k623m0hk.js → WavPackParser-0x9z4466.js} +3 -3
  37. package/dist/{WavPackParser-k623m0hk.js.map → WavPackParser-0x9z4466.js.map} +1 -1
  38. package/dist/{WaveParser-nj4p1vx8.js → WaveParser-31b6qtef.js} +3 -3
  39. package/dist/{WaveParser-nj4p1vx8.js.map → WaveParser-31b6qtef.js.map} +1 -1
  40. package/dist/{WizardApp-p350qspw.js → WizardApp-c42wc116.js} +3 -3
  41. package/dist/{WizardApp-p350qspw.js.map → WizardApp-c42wc116.js.map} +1 -1
  42. package/dist/{channels-a9zx9yba.js → channels-nf6d8fvx.js} +14 -14
  43. package/dist/{channels-a9zx9yba.js.map → channels-nf6d8fvx.js.map} +1 -1
  44. package/dist/client.d.ts +1 -1
  45. package/dist/client.js +11 -11
  46. package/dist/client.js.map +4 -4
  47. package/dist/{config-3mz4zwsf.js → config-sx40rg8m.js} +21 -21
  48. package/dist/{config-3mz4zwsf.js.map → config-sx40rg8m.js.map} +1 -1
  49. package/dist/{credential-ja7zmd4c.js → credential-vdbkfk65.js} +5 -5
  50. package/dist/{credential-ja7zmd4c.js.map → credential-vdbkfk65.js.map} +1 -1
  51. package/dist/daemon.d.ts.map +1 -1
  52. package/dist/{index-dcy14zdn.js → index-0dcpsfet.js} +5 -5
  53. package/dist/{index-dcy14zdn.js.map → index-0dcpsfet.js.map} +1 -1
  54. package/dist/{index-a1axc952.js → index-1h8s50d9.js} +4 -4
  55. package/dist/{index-a1axc952.js.map → index-1h8s50d9.js.map} +1 -1
  56. package/dist/{index-ayhdn87b.js → index-1hbvhrsj.js} +4 -4
  57. package/dist/{index-ayhdn87b.js.map → index-1hbvhrsj.js.map} +1 -1
  58. package/dist/{index-5gn74n56.js → index-1hfece7s.js} +7 -7
  59. package/dist/{index-5gn74n56.js.map → index-1hfece7s.js.map} +1 -1
  60. package/dist/{index-0dvs3a06.js → index-2h566rtg.js} +4 -4
  61. package/dist/{index-0dvs3a06.js.map → index-2h566rtg.js.map} +1 -1
  62. package/dist/{index-zzpgsbn3.js → index-4fj1k64j.js} +4 -4
  63. package/dist/{index-zzpgsbn3.js.map → index-4fj1k64j.js.map} +1 -1
  64. package/dist/{index-gezqawvw.js → index-4g4smpkk.js} +5 -5
  65. package/dist/{index-gezqawvw.js.map → index-4g4smpkk.js.map} +1 -1
  66. package/dist/index-4gfsf9n8.js +6 -0
  67. package/dist/{index-tc054tcb.js.map → index-4gfsf9n8.js.map} +1 -1
  68. package/dist/{index-mgef1n4e.js → index-5ptbytze.js} +9 -9
  69. package/dist/{index-mgef1n4e.js.map → index-5ptbytze.js.map} +1 -1
  70. package/dist/{index-f6r3h2yh.js → index-5s1cq8np.js} +5 -5
  71. package/dist/{index-f6r3h2yh.js.map → index-5s1cq8np.js.map} +1 -1
  72. package/dist/{index-rqfwd7j5.js → index-659ggfbf.js} +4 -4
  73. package/dist/{index-rqfwd7j5.js.map → index-659ggfbf.js.map} +1 -1
  74. package/dist/index-6ebppx3t.js +6 -0
  75. package/dist/{index-x9nn57kk.js.map → index-6ebppx3t.js.map} +1 -1
  76. package/dist/{index-4j65jp20.js → index-6pym9p8h.js} +6 -6
  77. package/dist/{index-4j65jp20.js.map → index-6pym9p8h.js.map} +1 -1
  78. package/dist/index-9ejax6hp.js +6 -0
  79. package/dist/{index-s0t15ndj.js.map → index-9ejax6hp.js.map} +1 -1
  80. package/dist/{index-86rb86nr.js → index-9hw9j1qg.js} +4 -4
  81. package/dist/{index-86rb86nr.js.map → index-9hw9j1qg.js.map} +1 -1
  82. package/dist/{index-yz0fcxky.js → index-9xhresrg.js} +4 -4
  83. package/dist/{index-yz0fcxky.js.map → index-9xhresrg.js.map} +1 -1
  84. package/dist/{index-2td5h856.js → index-abm0zyc0.js} +6 -6
  85. package/dist/{index-2td5h856.js.map → index-abm0zyc0.js.map} +1 -1
  86. package/dist/{index-8k8y7edx.js → index-ar5c9d2f.js} +5 -5
  87. package/dist/{index-8k8y7edx.js.map → index-ar5c9d2f.js.map} +1 -1
  88. package/dist/index-bhj4pmrx.js +74 -0
  89. package/dist/index-bhj4pmrx.js.map +13 -0
  90. package/dist/{index-brh25jhq.js → index-brt17yfr.js} +3 -3
  91. package/dist/{index-brh25jhq.js.map → index-brt17yfr.js.map} +1 -1
  92. package/dist/index-bysnsdkd.js +6 -0
  93. package/dist/{index-c6qrcweh.js.map → index-bysnsdkd.js.map} +1 -1
  94. package/dist/{index-kz01jz58.js → index-c74wx9pv.js} +4 -4
  95. package/dist/{index-kz01jz58.js.map → index-c74wx9pv.js.map} +1 -1
  96. package/dist/{index-qj4adnfe.js → index-cm3g4t3r.js} +9 -9
  97. package/dist/{index-qj4adnfe.js.map → index-cm3g4t3r.js.map} +1 -1
  98. package/dist/{index-8mkatm20.js → index-dzp6mc5h.js} +4 -4
  99. package/dist/{index-8mkatm20.js.map → index-dzp6mc5h.js.map} +1 -1
  100. package/dist/{index-b8bfzbfe.js → index-fad09b8c.js} +4 -4
  101. package/dist/{index-b8bfzbfe.js.map → index-fad09b8c.js.map} +1 -1
  102. package/dist/{index-2fw9e5gg.js → index-fvb2dxzn.js} +4 -4
  103. package/dist/{index-2fw9e5gg.js.map → index-fvb2dxzn.js.map} +1 -1
  104. package/dist/index-gpq4agva.js +5 -0
  105. package/dist/{index-635wcsh1.js.map → index-gpq4agva.js.map} +1 -1
  106. package/dist/index-hcpvk5de.js +5 -0
  107. package/dist/{index-7zgjkbb0.js.map → index-hcpvk5de.js.map} +1 -1
  108. package/dist/{index-s0f0s6n5.js → index-jv5t63tp.js} +4 -4
  109. package/dist/{index-s0f0s6n5.js.map → index-jv5t63tp.js.map} +1 -1
  110. package/dist/{index-60h4knj6.js → index-kyz4t0j0.js} +59 -59
  111. package/dist/{index-60h4knj6.js.map → index-kyz4t0j0.js.map} +1 -1
  112. package/dist/{index-7p8d1gf0.js → index-m6r2sxcw.js} +23 -23
  113. package/dist/{index-7p8d1gf0.js.map → index-m6r2sxcw.js.map} +1 -1
  114. package/dist/{index-4fajxhdv.js → index-mhw3d7af.js} +4 -4
  115. package/dist/{index-4fajxhdv.js.map → index-mhw3d7af.js.map} +1 -1
  116. package/dist/{index-h787rq0h.js → index-mk7hrzq7.js} +10 -10
  117. package/dist/{index-h787rq0h.js.map → index-mk7hrzq7.js.map} +1 -1
  118. package/dist/{index-r83jpct7.js → index-n0hqgwad.js} +4 -4
  119. package/dist/{index-r83jpct7.js.map → index-n0hqgwad.js.map} +1 -1
  120. package/dist/{index-k6wq0j4q.js → index-ncb840sk.js} +4 -4
  121. package/dist/{index-k6wq0j4q.js.map → index-ncb840sk.js.map} +1 -1
  122. package/dist/{index-8jejze0z.js → index-ntczmwnf.js} +3 -3
  123. package/dist/{index-8jejze0z.js.map → index-ntczmwnf.js.map} +1 -1
  124. package/dist/{index-ts8a1sdn.js → index-p5gy5s7p.js} +6 -6
  125. package/dist/{index-ts8a1sdn.js.map → index-p5gy5s7p.js.map} +1 -1
  126. package/dist/index-p86w0qjw.js +5 -0
  127. package/dist/{index-pz92ksp8.js.map → index-p86w0qjw.js.map} +1 -1
  128. package/dist/{index-cb45233h.js → index-qhh30m9p.js} +4 -4
  129. package/dist/{index-cb45233h.js.map → index-qhh30m9p.js.map} +1 -1
  130. package/dist/{index-z4adxmzm.js → index-rerdsr3d.js} +5 -5
  131. package/dist/{index-z4adxmzm.js.map → index-rerdsr3d.js.map} +1 -1
  132. package/dist/{index-67sfck4d.js → index-s0mfq8t7.js} +18 -18
  133. package/dist/index-s0mfq8t7.js.map +11 -0
  134. package/dist/{index-9k6qa50r.js → index-s9ybp2r1.js} +6 -6
  135. package/dist/{index-9k6qa50r.js.map → index-s9ybp2r1.js.map} +1 -1
  136. package/dist/index-ss77hvwy.js +1246 -0
  137. package/dist/{index-tv52jhac.js.map → index-ss77hvwy.js.map} +32 -31
  138. package/dist/{index-yy4v9kca.js → index-t9bnt6a1.js} +4 -4
  139. package/dist/{index-yy4v9kca.js.map → index-t9bnt6a1.js.map} +1 -1
  140. package/dist/{index-5zpfz4kb.js → index-w2ss9hn5.js} +7 -7
  141. package/dist/{index-5zpfz4kb.js.map → index-w2ss9hn5.js.map} +1 -1
  142. package/dist/{index-1cagdzqe.js → index-w80shmpv.js} +2 -2
  143. package/dist/index-w8e8qxd4.js +337 -0
  144. package/dist/index-w8e8qxd4.js.map +21 -0
  145. package/dist/{index-xyh98x7p.js → index-z9r4e0yq.js} +4 -4
  146. package/dist/{index-xyh98x7p.js.map → index-z9r4e0yq.js.map} +1 -1
  147. package/dist/{index-039ew35r.js → index-zj87j4j2.js} +4 -4
  148. package/dist/{index-039ew35r.js.map → index-zj87j4j2.js.map} +1 -1
  149. package/dist/{index-446exxcb.js → index-zmerx9rc.js} +7 -7
  150. package/dist/{index-446exxcb.js.map → index-zmerx9rc.js.map} +1 -1
  151. package/dist/{index-nndwx2wp.js → index-zqjtjs7c.js} +39 -39
  152. package/dist/{index-nndwx2wp.js.map → index-zqjtjs7c.js.map} +1 -1
  153. package/dist/index.js +318 -305
  154. package/dist/index.js.map +6 -5
  155. package/dist/lib/launchd.d.ts.map +1 -1
  156. package/dist/lib/service-env.d.ts.map +1 -1
  157. package/dist/lib/templates.d.ts.map +1 -1
  158. package/dist/lib/theme.d.ts.map +1 -1
  159. package/dist/lib/watchdog.d.ts +20 -0
  160. package/dist/lib/watchdog.d.ts.map +1 -0
  161. package/dist/serve.d.ts.map +1 -1
  162. package/dist/skills.d.ts.map +1 -1
  163. package/dist/sources.d.ts.map +1 -1
  164. package/dist/{web-7mdrcb8a.js → web-zvf80ns1.js} +5 -5
  165. package/dist/{web-7mdrcb8a.js.map → web-zvf80ns1.js.map} +1 -1
  166. package/dist/wire.js +11 -11
  167. package/dist/wire.js.map +4 -4
  168. package/dist/wrapper-5zhcdmnk.js +5 -0
  169. package/dist/{wrapper-4hdmdwft.js.map → wrapper-5zhcdmnk.js.map} +1 -1
  170. package/package.json +4 -4
  171. package/dist/APEv2Parser-x13n424p.js +0 -5
  172. package/dist/FlacParser-8xprykrh.js +0 -5
  173. package/dist/index-635wcsh1.js +0 -5
  174. package/dist/index-67sfck4d.js.map +0 -13
  175. package/dist/index-7zgjkbb0.js +0 -5
  176. package/dist/index-c6qrcweh.js +0 -6
  177. package/dist/index-hd5nkwd7.js +0 -74
  178. package/dist/index-hd5nkwd7.js.map +0 -13
  179. package/dist/index-n197qdw1.js +0 -308
  180. package/dist/index-n197qdw1.js.map +0 -21
  181. package/dist/index-pz92ksp8.js +0 -5
  182. package/dist/index-s0t15ndj.js +0 -6
  183. package/dist/index-tc054tcb.js +0 -6
  184. package/dist/index-tv52jhac.js +0 -1252
  185. package/dist/index-x9nn57kk.js +0 -6
  186. package/dist/wrapper-4hdmdwft.js +0 -5
  187. /package/dist/{index-1cagdzqe.js.map → index-w80shmpv.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,104 +1,104 @@
1
1
  #!/usr/bin/env node
2
- import{A,J,h,n,Co,si,bt,KA,eA,YA,cA,Se,ho,ci,li,lA,Bo,Mt,yo,Tt,jA,Bt,Qo,mo,Fe,Re,U,z,ui,Nr,JA,q,Do,bo,uA,qA,Oo,EA,ee,re,fi,Ce,Qn,No,Mo,hi,Bi,yi,v,qs}from"./index-tv52jhac.js";import{dr,Ye,ur,Er,qt,pr,Cr,fr}from"./index-hd5nkwd7.js";import{ae,be,Ee,pe,Ie,Qe,qr}from"./index-n197qdw1.js";import{ra}from"./index-ayhdn87b.js";import{Sn}from"./index-rqfwd7j5.js";import{kA,vA,Ao,He,Is,ds,ar,Jr,gr,ft,cr,LA,Kt,lr,Yt,PA,us,Es}from"./index-60h4knj6.js";import{Ar,sn,Ut,Hr,nr,OA,or,Jn,NA,MA,an,qn,Vn,ts,Wn,zn,Zn}from"./index-nndwx2wp.js";import{zt,UA,uo,pn,Eo,xA,wr,Cn,lt,gA,Zt,HA,Dr}from"./index-mgef1n4e.js";import{jr,ns,gn,os,rs,is,oA}from"./index-67sfck4d.js";import{cn,at,ln,gs}from"./index-039ew35r.js";import{Kn,Yn,on,er,bA,Ji,jn,Wi,zi}from"./index-h787rq0h.js";import"./index-z4adxmzm.js";import{Xo}from"./index-yz0fcxky.js";import{Ft,rn,Xi,es}from"./index-k6wq0j4q.js";import{TA,As}from"./index-ts8a1sdn.js";import{Ve}from"./index-gezqawvw.js";import{ss}from"./index-yy4v9kca.js";import{cs,ir,sr,We,ze,xt,ls,Ht,De,_A,Ct,to}from"./index-b8bfzbfe.js";import{Ke,gt}from"./index-xyh98x7p.js";import{ro,wt,Cs,H,hs,Ze,ht,Ir,Bs}from"./index-4j65jp20.js";import{C,L,w,S,rA,un,iA,sA}from"./index-9k6qa50r.js";import{$t,Oe,W,br,G,ge,Or,fn,hn,ii,Hs,Xt,Ks,oe,Ge}from"./index-f6r3h2yh.js";import{Ue}from"./index-0dvs3a06.js";import{ea,Aa}from"./index-zzpgsbn3.js";import{vo,da,_t,Me,Go,Ko,o,E,wn}from"./index-tc054tcb.js";async function xn(e){let t=await Ht(e),r=[];for(let i of oe()){let s=i.id??i.ref,a=await sr(s,e)??{enabled:!0},d=t.find((u)=>u.agentId===s),l=d===void 0?Number.NaN:Date.now()-Date.parse(d.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...d===void 0?{}:{pid:d.pid,serving:`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(l)?` · up ${un(l)}`:""}`}})}return r}function Tn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((t)=>({label:t.ref,value:t.problem!==void 0?"broken":t.enabled?"on":"off",note:t.problem??t.serving??(t.enabled?`not hosted${t.modelId===void 0?"":` · ${t.modelId}`}`:`switched off${t.reason===void 0?"":` — ${t.reason}`}`)}))}async function kt(e){if(e.manifestPaths.length===0){let a=await xn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
- `);else process.stdout.write(`${C(Tn(a))}
4
- `);return o}let t=await Ce.create({agents:[...e.manifestPaths],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v(e.manifestPaths),store:e.store??G(),lease:!1});H(()=>t.stop("cli-exit"));let r=t.list().map((a)=>a.describe()),i=new Map;for(let a of await t.store.leases.all()){if(a.runtimeId===t.runtimeId||!ee(a.pid))continue;let d=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(d)?` · up ${un(d)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:r.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
5
- `),o;let s=r.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${C(s)}
6
- `),o}import{basename as en,dirname as Ci,join as le,resolve as Ni}from"node:path";import{rmSync as ai}from"node:fs";import{isAbsolute as Pt,join as di,resolve as Et}from"node:path";var mi=3;async function Rt(e){if(e.answers.skills!=="find")return;let t=e.answers.skillsSearch?.trim()??"";if(t===""){process.stdout.write("\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\n");return}let r=He(e.env);if(r.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
- searching ${r.length} skill source(s) for ${JSON.stringify(t)}
8
- `);let i=[],s=[];for(let c of r){if(!ft(c.name,e.env))try{await LA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(f){s.push(`${c.name} — ${h(f)?f.message:String(f)}`);continue}i.push(...Kt(c,e.env))}for(let c of s)process.stdout.write(S(`could not fetch ${c}
9
- `));if(i.length===0){process.stdout.write(`${S("no source could be read, so no skill was installed — the directory is there and empty")}
10
- ${S("`sources update` reports why; `sources search <words>` when it works",4)}
11
- `);return}let a=pi(t,i);if(a.length===0){process.stdout.write(`${S(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
- ${S("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
13
- `);return}let d=a[0],l=`${d.source}/${d.skill}`;if(process.stdout.write(`${S(`best of ${i.length}: ${l}`)}
14
- `),a.length>1)process.stdout.write(`${S(`also matched: ${a.slice(1,1+mi).map((c)=>`${c.source}/${c.skill}`).join(", ")}`,4)}
2
+ import{A,J,h,n,fo,si,bt,HA,Xt,KA,gA,Se,Co,ai,gi,cA,ho,Nt,Bo,Mt,YA,Bt,yo,Qo,Fe,Re,U,z,Ii,Or,jA,q,wo,Do,dA,JA,bo,uA,ee,re,fi,pe,yn,Oo,No,pi,Ci,hi,v,Js}from"./index-ss77hvwy.js";import{Ir,Ye,dr,ur,Jt,Er,fr,pr}from"./index-bhj4pmrx.js";import{ae,be,Ee,fe,Ie,Qe,Jr}from"./index-w8e8qxd4.js";import{oa}from"./index-1hbvhrsj.js";import{mn}from"./index-659ggfbf.js";import{_A,kA,to,He,cs,ls,sr,jr,ar,pt,gr,vA,Ht,cr,Kt,LA,Is,ds}from"./index-kyz4t0j0.js";import{tr,rn,Ft,xr,Ar,bA,nr,jn,OA,NA,sn,Jn,qn,Xi,Vn,Wn,zn}from"./index-zqjtjs7c.js";import{Wt,FA,Io,En,uo,UA,Sr,fn,ct,aA,zt,xA,wr}from"./index-5ptbytze.js";import{Yr,ts,an,As,ns,os,nA}from"./index-s0mfq8t7.js";import{gn,st,cn,ss}from"./index-zj87j4j2.js";import{Hn,Kn,nn,Xo,DA,Yi,Yn,qi,Vi}from"./index-mk7hrzq7.js";import"./index-rerdsr3d.js";import{$o}from"./index-9xhresrg.js";import{Gt,on,Zi,$i}from"./index-ncb840sk.js";import{MA,es}from"./index-p5gy5s7p.js";import{Ve}from"./index-4g4smpkk.js";import{rs}from"./index-t9bnt6a1.js";import{as,rr,ir,We,ze,Ut,gs,xt,De,RA,ft,eo}from"./index-fad09b8c.js";import{Ke,at}from"./index-z9r4e0yq.js";import{oo,wt,Es,H,ps,Ze,Ct,lr,Cs}from"./index-6pym9p8h.js";import{p,L,D,w,oA,dn,rA,iA}from"./index-s9ybp2r1.js";import{Zt,Oe,W,Dr,G,ge,br,pn,Cn,ii,Hs,$t,Ks,oe,Ge}from"./index-5s1cq8np.js";import{Ue}from"./index-2h566rtg.js";import{Xs,ta}from"./index-4fj1k64j.js";import{ko,Ia,Rt,Me,Po,Ho,o,E,Sn}from"./index-4gfsf9n8.js";async function In(e){let t=await xt(e),s=[];for(let i of oe()){let r=i.id??i.ref,a=await ir(r,e)??{enabled:!0},d=t.find((u)=>u.agentId===r),l=d===void 0?Number.NaN:Date.now()-Date.parse(d.startedAt);s.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...d===void 0?{}:{pid:d.pid,serving:`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(l)?` · up ${dn(l)}`:""}`}})}return s}function On(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((t)=>({label:t.ref,value:t.problem!==void 0?"broken":t.enabled?"on":"off",note:t.problem??t.serving??(t.enabled?`not hosted${t.modelId===void 0?"":` · ${t.modelId}`}`:`switched off${t.reason===void 0?"":` — ${t.reason}`}`)}))}async function Pt(e){if(e.manifestPaths.length===0){let a=await In(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
+ `);else process.stdout.write(`${p(On(a))}
4
+ `);return o}let t=await pe.create({agents:[...e.manifestPaths],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v(e.manifestPaths),store:e.store??G(),lease:!1});H(()=>t.stop("cli-exit"));let s=t.list().map((a)=>a.describe()),i=new Map;for(let a of await t.store.leases.all()){if(a.runtimeId===t.runtimeId||!ee(a.pid))continue;let d=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(d)?` · up ${dn(d)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:s.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
5
+ `),o;let r=s.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${p(r)}
6
+ `),o}import{basename as tn,dirname as Mi,join as de,resolve as Di}from"node:path";import{rmSync as yi}from"node:fs";import{isAbsolute as Et,join as wi,resolve as Tt}from"node:path";var bi=3;async function It(e){if(e.answers.skills!=="find")return;let t=e.answers.skillsSearch?.trim()??"";if(t===""){process.stdout.write("\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\n");return}let s=He(e.env);if(s.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
+ searching ${s.length} skill source(s) for ${JSON.stringify(t)}
8
+ `);let i=[],r=[];for(let c of s){if(!pt(c.name,e.env))try{await vA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(f){r.push(`${c.name} — ${h(f)?f.message:String(f)}`);continue}i.push(...Ht(c,e.env))}for(let c of r)process.stdout.write(w(`could not fetch ${c}
9
+ `));if(i.length===0){process.stdout.write(`${w("no source could be read, so no skill was installed — the directory is there and empty")}
10
+ ${w("`sources update` reports why; `sources search <words>` when it works",4)}
11
+ `);return}let a=vi(t,i);if(a.length===0){process.stdout.write(`${w(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
+ ${w("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
13
+ `);return}let d=a[0],l=`${d.source}/${d.skill}`;if(process.stdout.write(`${w(`best of ${i.length}: ${l}`)}
14
+ `),a.length>1)process.stdout.write(`${w(`also matched: ${a.slice(1,1+bi).map((c)=>`${c.source}/${c.skill}`).join(", ")}`,4)}
15
15
  `);if(process.stdout.write(`
16
- `),Yt({action:"install",manifestPath:e.manifestPath,name:l,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let p=gi(e.manifestPath,e.envOverlay);if(p!==void 0)wi(e.manifestPath,d.skill,e.envOverlay),process.stdout.write(`
17
- ${w(`${l} was removed again: it does not load on this machine`)}
18
- ${S(p,4)}
19
- ${S("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
- `)}function pi(e,t){let r=new Map,i=t.filter((s)=>s.problem===void 0).map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return qA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}function gi(e,t){try{let r=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=r.manifest.skills;if(i===void 0)return;let s=Se(r.manifest.model.main.id,r.manifest.model.main.capabilities);uA({dir:Pt(i.dir)?i.dir:Et(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:s.promptStyle,agentDir:r.dir,runner:pe()});return}catch(r){return h(r)?r.message:String(r)}}function wi(e,t,r){try{let i=z(e,{...r===void 0?{}:{env:{...process.env,...r}}}),s=i.manifest.skills;if(s===void 0)return;let a=Pt(s.dir)?s.dir:Et(i.dir,s.dir);ai(di(a,t),{recursive:!0,force:!0}),lr(a,t)}catch{}}var In=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function It(e,t,r={}){let i=r.fetch??fetch,s=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},d=async(g)=>{try{let R=await i(g,{headers:a,signal:AbortSignal.timeout(3000)});if(!R.ok)return;let P=await R.json();return P!==null&&typeof P==="object"?P:void 0}catch{return}},p=((await d(`${s}/models/${t}/endpoints`))?.data?.endpoints??[]).map((g)=>In(g.context_length)).filter((g)=>g!==void 0);if(p.length>0)return{tokens:Math.min(...p),source:`the smallest of ${p.length} published endpoint${p.length===1?"":"s"} at ${s}`};let f=((await d(`${s}/models`))?.data??[]).find((g)=>g.id===t),m=In(f?.context_length)??In(f?.max_model_len);return m===void 0?void 0:{tokens:m,source:`${s}/models`}}import{randomBytes as bi}from"node:crypto";import{mkdirSync as $i,readFileSync as Ot,writeFileSync as vi}from"node:fs";import{join as Si}from"node:path";function qe(e){return Si(e,".owner")}function ki(e,t=bi){try{let i=Ot(qe(e),"utf8").trim();if(i!=="")return i}catch{}let r=`me:${Co(t(6))}`;return $i(e,{recursive:!0}),vi(qe(e),`${r}
21
- `,{encoding:"utf8",mode:384}),r}function Pi(e){return e.flatMap((t)=>(t.allowFrom??[]).filter((r)=>r!=="*").map((r)=>`${t.type}:${r}`))}async function Ei(e,t){let r=e.conversations,i=(t.now??new Date).toISOString(),s=await r.assignment(t.agentId);if(s!==void 0&&s.participantId!==t.owner)throw new n({code:"owner_assigned_elsewhere",message:`Agent "${t.agentId}" is assigned to ${s.participantId}, not to ${t.owner}.`,hint:`Somebody else is this agent's owner, and taking it over would make it answer the wrong person as its owner. If it really is yours, unassign it first (DELETE /v1/agents/${t.agentId}/assignee) and run \`${A.slug} owner adopt ${t.agentId}\` again.`});if(await r.participant(t.owner)===void 0)await r.upsertParticipant({id:t.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...s?.channelIds??[],...t.channelIds])];return await r.assign({agentId:t.agentId,participantId:t.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function we(e,t,r){let i=Ot(t,"utf8"),s=String(Re(i,["id"])??""),a=Re(i,["channels"]),d=ki(r),{channelIds:l}=await Ei(e,{agentId:s,owner:d,channelIds:Pi(Array.isArray(a)?a.filter((u)=>typeof u?.type==="string"):[])});return{agentId:s,owner:d,channelIds:l}}import{existsSync as Ri,mkdirSync as xi,writeFileSync as Ti}from"node:fs";import{dirname as Ii,join as On,resolve as An,sep as Oi}from"node:path";var Je={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",region:"--region",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function _n(e,t,r,i){let s=[];for(;;){let a=gA(e,r);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){s.push(a.step),e[a.step]="(missing)";continue}let d=Zt(a.step,a.fallback);if(d.ok)e[a.step]=d.value}if(s.length>0){if(i?.naming==="answers"){let d=s.map((l)=>`answers.${l}`).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Provide ${d} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=s.map((d)=>Je[d]).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Pass ${a} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Nn(e,t){let r=e,i=zt(r.preset),s=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",d=r.dir??UA(r.dirChoice,r.name,t);if(d===void 0)throw new n({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(r.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:r.user,name:r.name,purpose:r.purpose,preset:r.preset,model:r.model,baseUrl:r.baseUrl??"",...r.region===void 0?{}:{region:r.region},system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:Ai(d,t.agentDirBase)?Hs(t.agentDirBase,At):At()}:{},...s===void 0?{}:{apiKeyEnv:s},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:d}}function Ai(e,t){let r=An(e),i=An(t);return r===i||r.startsWith(i+Oi)}function At(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((t)=>t.toString(16).padStart(2,"0")).join("")}function ke(e,t){let r=t.map((i)=>On(e,i.relPath)).filter((i)=>Ri(i));if(r.length>0)throw new n({code:"cli_init_target_exists",message:`${r.length} of the files init would write already exist: ${r.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of t){let s=On(e,i.relPath);xi(Ii(s),{recursive:!0}),Ti(s,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function Xe(e,t){let r=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=Se(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:s,warnings:a}=EA(r,i.promptStyle),d=eA(s,r.manifest.context.rules);if(d!==void 0&&r.manifest.context.rules.onExceed==="fail")throw d;return{distilled:a.some((l)=>l.code==="soul_distilled")}}var jt=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Fn=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Lt(e){let t=Zt(e.step,e.fallback);return t.ok?t.value:e.fallback}function _i(e,t){let r=Fn.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Lt(e),optional:e.optional===!0,secret:Cn.has(e.step),...t===void 0?{}:{requires:t},...e.options===void 0?{}:{choices:e.options.filter((i)=>r?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var Nt=64;function Dt(e){let t=new Map,r=new Set,i=(a,d)=>{let l={...a},u=[];for(let p=0;p<Nt;p+=1){let c=gA(l,e);if(c===void 0)break;let f=Lt(c);if(!jt.has(c.step)&&!t.has(c.step))t.set(c.step,_i(c,d));for(let m of c.options??[]){if(m.value===f)continue;if(Fn.get(c.step)?.has(m.value)===!0)continue;u.push({seed:{...l,[c.step]:m.value},opened:{step:c.step,value:m.value}})}l[c.step]=f}return u},s=[...i({})];for(let a=0;a<Nt&&s.length>0;a+=1){let d=s.splice(0,s.length);for(let l of d){let u=`${l.opened.step}=${l.opened.value}`;if(r.has(u))continue;r.add(u),s.push(...i(l.seed,l.opened))}}return[...t.values()].sort((a,d)=>wr.indexOf(a.step)-wr.indexOf(d.step))}function Gt(e){let t={};for(let[l,u]of Object.entries(e.answers)){let p=l;if(!(p in Je))throw new n({code:"provision_unknown_answer",message:`"${l}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:l});let c=jt.get(p);if(c!==void 0)throw new n({code:c.code,message:`"${l}" cannot be set over the API.`,hint:c.hint,field:l});let f=Fn.get(p)?.get(u.trim().toLowerCase());if(f!==void 0)throw new n({code:f.code,message:`${l} is ${JSON.stringify(u)}, which this runtime cannot do over the API.`,hint:f.hint,field:l});let m=Zt(p,u);if(!m.ok)throw new n({code:"provision_answer_invalid",message:`${l} is ${JSON.stringify(u)}, which ${m.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:l});t[p]=m.value}_n(t,"this is the provisioning API",e.defaults,{naming:"answers"});let r=Nn(t,e.defaults),i=lt(r.name),s=UA("sandbox",r.name,e.defaults);if(s===void 0)throw new n({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(r.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=An(s),d=Dr({...r,dir:a});return ke(a,d),{agentId:i,dir:a,manifestPath:On(a,"agent.yaml"),files:d.map((l)=>l.relPath)}}function ji(e){if(e.web!=="search")return;return uo(e.webBackend??"tavily")?.apiKeyEnv}async function Wt(e){let t=await Vt(e);if(t.kind==="aborted")return process.stdout.write(`nothing written
22
- `),o;return t.kind==="failed"?t.code:o}async function Un(e){return Vt(e)}async function Vt(e){let t=Ui(e),r=gt({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,s={agentDirBase:W()};if(i){let b=await Li(t,s);if(b===void 0)return{kind:"aborted"};Object.assign(t,b)}else _n(t,e.yes===!0?"--yes was passed":r.because,s);let a=Nn(t,s),d=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),l=(i||e.measureWindow===!0)&&a.baseUrl!==""?await It(a.baseUrl,a.model,{...d===void 0||d===""?{}:{apiKey:d}}):void 0,u=a,p=Ni(process.cwd(),u.dir),c=Ks(p);if(c!==void 0)process.stderr.write(`${c}
23
- `);let f=le(p,"agent.yaml"),m=Dr(u,l);ke(p,m);let g=u.apiKeyEnv,P=g!==void 0&&u.apiKey===void 0&&(process.env[g]===void 0||process.env[g]==="")&&g!==void 0?{[g]:"(pending)"}:void 0,y=!1;try{y=Xe(le(p,"agent.yaml"),P).distilled}catch(b){if(h(b))return process.stderr.write(`init wrote ${m.length} files to ${p}, but the result does not load:
24
- ${b.format()}
25
- `),{kind:"failed",code:E};throw b}if(process.stdout.write(`wrote ${m.length} files to ${p} — validated ok
26
- `),u.skills==="find"){let b=(u.skillsPick??"").split(",").map((x)=>x.trim()).filter((x)=>x!=="");if(b.length>0)us(b,f,{...P===void 0?{}:{envOverlay:P}});else if(!i)await Rt({answers:u,manifestPath:f,...P===void 0?{}:{envOverlay:P}})}await Fi(f,p,s.agentDirBase);let j;if(u.daemon==="service"){process.stdout.write(`
27
- `);let{outcome:b,host:x}=await Jn({...e.installServer===void 0?{}:{install:e.installServer}}),I=OA(b);if(I!==void 0)process.stderr.write(I);if(x?.baseUrl!==void 0){let _=await NA(x,f);if(_.ok)j=x.baseUrl;else process.stderr.write(`pid ${x.pid} did not adopt ${lt(u.name)}${_.detail===void 0?"":`: ${_.detail}`}
28
- `)}}let D;if(u.whatsapp==="connected"&&(u.whatsappNumber??"")!==""&&i)D=j!==void 0?await qn({manifestPath:f,channelId:"wa"}):await Vn({manifestPath:f,dir:p,number:u.whatsappNumber??"",channelId:"wa"});if(u.whatsapp==="connected"&&D!=="paired")process.stdout.write(`
29
- ${ts(lt(u.name))}`);return process.stdout.write(Mi(u,p,y,j)),{kind:"ok",manifestPath:le(p,"agent.yaml")}}async function Fi(e,t,r){let i=en(t);if(!Xt(t)){process.stdout.write(`
16
+ `),Kt({action:"install",manifestPath:e.manifestPath,name:l,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let g=Si(e.manifestPath,e.envOverlay);if(g!==void 0)ki(e.manifestPath,d.skill,e.envOverlay),process.stdout.write(`
17
+ ${D(`${l} was removed again: it does not load on this machine`)}
18
+ ${w(g,4)}
19
+ ${w("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
+ `)}function vi(e,t){let s=new Map,i=t.filter((r)=>r.problem===void 0).map((r)=>{let a=`${r.source}/${r.skill}`;return s.set(a,r),{name:a,dir:r.dir,tokens:r.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:r.description,metadata:{}}}});return JA(e,i).filter((r)=>r.score>0).map((r)=>s.get(r.skill.name)).filter((r)=>r!==void 0)}function Si(e,t){try{let s=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=s.manifest.skills;if(i===void 0)return;let r=Se(s.manifest.model.main.id,s.manifest.model.main.capabilities);dA({dir:Et(i.dir)?i.dir:Tt(s.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:r.promptStyle,agentDir:s.dir,runner:fe()});return}catch(s){return h(s)?s.message:String(s)}}function ki(e,t,s){try{let i=z(e,{...s===void 0?{}:{env:{...process.env,...s}}}),r=i.manifest.skills;if(r===void 0)return;let a=Et(r.dir)?r.dir:Tt(i.dir,r.dir);yi(wi(a,t),{recursive:!0,force:!0}),cr(a,t)}catch{}}var An=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function Ot(e,t,s={}){let i=s.fetch??fetch,r=e.replace(/\/+$/,""),a=s.apiKey===void 0?{}:{authorization:`Bearer ${s.apiKey}`},d=async(y)=>{try{let R=await i(y,{headers:a,signal:AbortSignal.timeout(3000)});if(!R.ok)return;let T=await R.json();return T!==null&&typeof T==="object"?T:void 0}catch{return}},g=((await d(`${r}/models/${t}/endpoints`))?.data?.endpoints??[]).map((y)=>An(y.context_length)).filter((y)=>y!==void 0);if(g.length>0)return{tokens:Math.min(...g),source:`the smallest of ${g.length} published endpoint${g.length===1?"":"s"} at ${r}`};let f=((await d(`${r}/models`))?.data??[]).find((y)=>y.id===t),m=An(f?.context_length)??An(f?.max_model_len);return m===void 0?void 0:{tokens:m,source:`${r}/models`}}import{randomBytes as Pi}from"node:crypto";import{mkdirSync as Ei,readFileSync as At,writeFileSync as Ri}from"node:fs";import{join as Ti}from"node:path";function Je(e){return Ti(e,".owner")}function xi(e,t=Pi){try{let i=At(Je(e),"utf8").trim();if(i!=="")return i}catch{}let s=`me:${fo(t(6))}`;return Ei(e,{recursive:!0}),Ri(Je(e),`${s}
21
+ `,{encoding:"utf8",mode:384}),s}function Oi(e){return e.flatMap((t)=>(t.allowFrom??[]).filter((s)=>s!=="*").map((s)=>`${t.type}:${s}`))}async function Ai(e,t){let s=e.conversations,i=(t.now??new Date).toISOString(),r=await s.assignment(t.agentId);if(r!==void 0&&r.participantId!==t.owner)throw new n({code:"owner_assigned_elsewhere",message:`Agent "${t.agentId}" is assigned to ${r.participantId}, not to ${t.owner}.`,hint:`Somebody else is this agent's owner, and taking it over would make it answer the wrong person as its owner. If it really is yours, unassign it first (DELETE /v1/agents/${t.agentId}/assignee) and run \`${A.slug} owner adopt ${t.agentId}\` again.`});if(await s.participant(t.owner)===void 0)await s.upsertParticipant({id:t.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...r?.channelIds??[],...t.channelIds])];return await s.assign({agentId:t.agentId,participantId:t.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function ve(e,t,s){let i=At(t,"utf8"),r=String(Re(i,["id"])??""),a=Re(i,["channels"]),d=xi(s),{channelIds:l}=await Ai(e,{agentId:r,owner:d,channelIds:Oi(Array.isArray(a)?a.filter((u)=>typeof u?.type==="string"):[])});return{agentId:r,owner:d,channelIds:l}}import{existsSync as _i,mkdirSync as Ni,writeFileSync as ji}from"node:fs";import{dirname as Fi,join as _n,resolve as Nn,sep as Li}from"node:path";var Xe={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",region:"--region",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function Fn(e,t,s,i){let r=[];for(;;){let a=aA(e,s);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){r.push(a.step),e[a.step]="(missing)";continue}let d=zt(a.step,a.fallback);if(d.ok)e[a.step]=d.value}if(r.length>0){if(i?.naming==="answers"){let d=r.map((l)=>`answers.${l}`).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${r.join(", ")} ${r.length===1?"has":"have"} no default.`,hint:`Provide ${d} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=r.map((d)=>Xe[d]).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${r.join(", ")} ${r.length===1?"has":"have"} no default.`,hint:`Pass ${a} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Ln(e,t){let s=e,i=Wt(s.preset),r=s.apiKeyEnv??i?.apiKeyEnv,a=s.server??"local",d=s.dir??FA(s.dirChoice,s.name,t);if(d===void 0)throw new n({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(s.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:s.user,name:s.name,purpose:s.purpose,preset:s.preset,model:s.model,baseUrl:s.baseUrl??"",...s.region===void 0?{}:{region:s.region},system:s.system,web:s.web,...s.webBackend===void 0?{}:{webBackend:s.webBackend},...s.webKey===void 0||s.webKey===""?{}:{webKey:s.webKey},composio:s.composio,...s.composioKey===void 0||s.composioKey===""?{}:{composioKey:s.composioKey},telegram:s.telegram,...s.telegramToken===void 0||s.telegramToken===""?{}:{telegramToken:s.telegramToken},...s.telegramAllow===void 0||s.telegramAllow===""?{}:{telegramAllow:s.telegramAllow},whatsapp:s.whatsapp??"none",...s.whatsappNumber===void 0||s.whatsappNumber===""?{}:{whatsappNumber:s.whatsappNumber},schedules:s.schedules??"none",server:a,skills:s.skills,...s.skillsSearch===void 0||s.skillsSearch===""?{}:{skillsSearch:s.skillsSearch},...s.skillsPick===void 0||s.skillsPick===""?{}:{skillsPick:s.skillsPick},daemon:s.daemon,...a==="local"?{serverToken:Ki(d,t.agentDirBase)?Hs(t.agentDirBase,_t):_t()}:{},...r===void 0?{}:{apiKeyEnv:r},...s.apiKey===void 0||s.apiKey===""?{}:{apiKey:s.apiKey},...s.dirChoice===void 0?{}:{dirChoice:s.dirChoice},dir:d}}function Ki(e,t){let s=Nn(e),i=Nn(t);return s===i||s.startsWith(i+Li)}function _t(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((t)=>t.toString(16).padStart(2,"0")).join("")}function Te(e,t){let s=t.map((i)=>_n(e,i.relPath)).filter((i)=>_i(i));if(s.length>0)throw new n({code:"cli_init_target_exists",message:`${s.length} of the files init would write already exist: ${s.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of t){let r=_n(e,i.relPath);Ni(Fi(r),{recursive:!0}),ji(r,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function en(e,t){let s=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=Se(s.manifest.model.main.id,s.manifest.model.main.capabilities),{workspace:r,warnings:a}=uA(s,i.promptStyle),d=Xt(r,s.manifest.context.rules);if(d!==void 0&&s.manifest.context.rules.onExceed==="fail")throw d;return{distilled:a.some((l)=>l.code==="soul_distilled")}}var Lt=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Un=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Dt(e){let t=zt(e.step,e.fallback);return t.ok?t.value:e.fallback}function Ui(e,t){let s=Un.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Dt(e),optional:e.optional===!0,secret:fn.has(e.step),...t===void 0?{}:{requires:t},...e.options===void 0?{}:{choices:e.options.filter((i)=>s?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var jt=64;function qt(e){let t=new Map,s=new Set,i=(a,d)=>{let l={...a},u=[];for(let g=0;g<jt;g+=1){let c=aA(l,e);if(c===void 0)break;let f=Dt(c);if(!Lt.has(c.step)&&!t.has(c.step))t.set(c.step,Ui(c,d));for(let m of c.options??[]){if(m.value===f)continue;if(Un.get(c.step)?.has(m.value)===!0)continue;u.push({seed:{...l,[c.step]:m.value},opened:{step:c.step,value:m.value}})}l[c.step]=f}return u},r=[...i({})];for(let a=0;a<jt&&r.length>0;a+=1){let d=r.splice(0,r.length);for(let l of d){let u=`${l.opened.step}=${l.opened.value}`;if(s.has(u))continue;s.add(u),r.push(...i(l.seed,l.opened))}}return[...t.values()].sort((a,d)=>Sr.indexOf(a.step)-Sr.indexOf(d.step))}function Vt(e){let t={};for(let[l,u]of Object.entries(e.answers)){let g=l;if(!(g in Xe))throw new n({code:"provision_unknown_answer",message:`"${l}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:l});let c=Lt.get(g);if(c!==void 0)throw new n({code:c.code,message:`"${l}" cannot be set over the API.`,hint:c.hint,field:l});let f=Un.get(g)?.get(u.trim().toLowerCase());if(f!==void 0)throw new n({code:f.code,message:`${l} is ${JSON.stringify(u)}, which this runtime cannot do over the API.`,hint:f.hint,field:l});let m=zt(g,u);if(!m.ok)throw new n({code:"provision_answer_invalid",message:`${l} is ${JSON.stringify(u)}, which ${m.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:l});t[g]=m.value}Fn(t,"this is the provisioning API",e.defaults,{naming:"answers"});let s=Ln(t,e.defaults),i=ct(s.name),r=FA("sandbox",s.name,e.defaults);if(r===void 0)throw new n({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(s.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=Nn(r),d=wr({...s,dir:a});return Te(a,d),{agentId:i,dir:a,manifestPath:_n(a,"agent.yaml"),files:d.map((l)=>l.relPath)}}function Hi(e){if(e.web!=="search")return;return Io(e.webBackend??"tavily")?.apiKeyEnv}async function Yt(e){let t=await Qt(e);if(t.kind==="aborted")return process.stdout.write(`nothing written
22
+ `),o;return t.kind==="failed"?t.code:o}async function Mn(e){return Qt(e)}async function Qt(e){let t=Bi(e),s=at({json:!1,plain:e.plain===!0,oneShot:!1}),i=s.mode==="rich"&&e.yes!==!0,r={agentDirBase:W()};if(i){let S=await Ji(t,r);if(S===void 0)return{kind:"aborted"};Object.assign(t,S)}else Fn(t,e.yes===!0?"--yes was passed":s.because,r);let a=Ln(t,r),d=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),l=(i||e.measureWindow===!0)&&a.baseUrl!==""?await Ot(a.baseUrl,a.model,{...d===void 0||d===""?{}:{apiKey:d}}):void 0,u=a,g=Di(process.cwd(),u.dir),c=Ks(g);if(c!==void 0)process.stderr.write(`${c}
23
+ `);let f=de(g,"agent.yaml"),m=wr(u,l);Te(g,m);let y=u.apiKeyEnv,T=y!==void 0&&u.apiKey===void 0&&(process.env[y]===void 0||process.env[y]==="")&&y!==void 0?{[y]:"(pending)"}:void 0,b=!1;try{b=en(de(g,"agent.yaml"),T).distilled}catch(S){if(h(S))return process.stderr.write(`init wrote ${m.length} files to ${g}, but the result does not load:
24
+ ${S.format()}
25
+ `),{kind:"failed",code:E};throw S}if(process.stdout.write(`wrote ${m.length} files to ${g} — validated ok
26
+ `),u.skills==="find"){let S=(u.skillsPick??"").split(",").map((P)=>P.trim()).filter((P)=>P!=="");if(S.length>0)Is(S,f,{...T===void 0?{}:{envOverlay:T}});else if(!i)await It({answers:u,manifestPath:f,...T===void 0?{}:{envOverlay:T}})}await Wi(f,g,r.agentDirBase);let N;if(u.daemon==="service"){process.stdout.write(`
27
+ `);let{outcome:S,host:P}=await jn({...e.installServer===void 0?{}:{install:e.installServer}}),I=bA(S);if(I!==void 0)process.stderr.write(I);if(P?.baseUrl!==void 0){let O=await OA(P,f);if(O.ok)N=P.baseUrl;else process.stderr.write(`pid ${P.pid} did not adopt ${ct(u.name)}${O.detail===void 0?"":`: ${O.detail}`}
28
+ `)}}let M;if(u.whatsapp==="connected"&&(u.whatsappNumber??"")!==""&&i)M=N!==void 0?await Jn({manifestPath:f,channelId:"wa"}):await qn({manifestPath:f,dir:g,number:u.whatsappNumber??"",channelId:"wa"});if(u.whatsapp==="connected"&&M!=="paired")process.stdout.write(`
29
+ ${Xi(ct(u.name))}`);return process.stdout.write(zi(u,g,b,N)),{kind:"ok",manifestPath:de(g,"agent.yaml")}}async function Wi(e,t,s){let i=tn(t);if(!$t(t)){process.stdout.write(`
30
30
  To make it yours across every surface: ${A.slug} owner adopt ${e}
31
- `);return}let s;try{s=await re.open({path:G()}),await we(s,e,r)}catch(a){let d=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${d}
31
+ `);return}let r;try{r=await re.open({path:G()}),await ve(r,e,s)}catch(a){let d=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${d}
32
32
  hint: run \`${A.slug} owner adopt ${i}\` once the store is reachable.
33
- `)}finally{await s?.close()}}function Ki(e){if(e===void 0)return[];if(xA.some((t)=>t.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Ui(e){let t={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["region",e.region],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...Ki(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,s]of r){if(s===void 0)continue;let a=Zt(i,s);if(!a.ok)throw new n({code:"cli_init_flag_invalid",message:`${Je[i]} is ${JSON.stringify(s)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});t[i]=a.value}return t}async function Li(e,t){let[{render:r},{createElement:i},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-p350qspw.js")]),a;ro();let d=r(i(s,{title:`${A.name} ${q}`,given:e,defaults:t,onDone:(l)=>{a=l}}),{exitOnCtrlC:!1,...Ke()});return H(()=>d.unmount()),await d.waitUntilExit(),d.unmount(),a}function Mi(e,t,r,i){let s=i!==void 0,d=Ci(t)===W()?en(t):le(t,"agent.yaml"),l=le(t,"agent.yaml"),u=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)u.push(`Add your key: edit ${le(t,".env")} and set ${e.apiKeyEnv}=`);let p=ji(e);if(p!==void 0&&e.webKey===void 0)u.push(`Add your search key: edit ${le(t,".env")} and set ${p}= — web_fetch works without it, web_search does not`);if(HA(e)&&e.composioKey===void 0)u.push(`Add your Composio key: edit ${le(t,".env")} and set ${pn}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)u.push(`Add your bot token: message @BotFather with /newbot, then edit ${le(t,".env")} and set ${Eo}=`);let c=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],f=c.length>0||e.server==="local",m=[...c,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)u.push(`open ${oA(i,en(t))} — the web UI. The service is serving `+`${en(t)} now; ${m} ${c.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),u.push(`${A.slug} run ${d} — talks to it here, attached to that same service.`);else u.push(`${A.slug} run ${d}`);if(f&&!s){if(u.push(`${A.slug} serve ${d} — starts ${m}; \`run\` starts neither`),e.daemon==="service")u.push(`${A.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(e.telegram==="connected"&&e.telegramAllow===void 0)u.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(HA(e))u.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");u.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${d} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches the configured catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${d} <name>\` writes one.`),u.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${l}\` shows exactly what still reads as a template.`);let g=s?`
33
+ `)}finally{await r?.close()}}function Gi(e){if(e===void 0)return[];if(UA.some((t)=>t.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Bi(e){let t={},s=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["region",e.region],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...Gi(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,r]of s){if(r===void 0)continue;let a=zt(i,r);if(!a.ok)throw new n({code:"cli_init_flag_invalid",message:`${Xe[i]} is ${JSON.stringify(r)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});t[i]=a.value}return t}async function Ji(e,t){let[{render:s},{createElement:i},{WizardApp:r}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-c42wc116.js")]),a;oo();let d=s(i(r,{title:`${A.name} ${q}`,given:e,defaults:t,onDone:(l)=>{a=l}}),{exitOnCtrlC:!1,...Ke()});return H(()=>d.unmount()),await d.waitUntilExit(),d.unmount(),a}function zi(e,t,s,i){let r=i!==void 0,d=Mi(t)===W()?tn(t):de(t,"agent.yaml"),l=de(t,"agent.yaml"),u=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)u.push(`Add your key: edit ${de(t,".env")} and set ${e.apiKeyEnv}=`);let g=Hi(e);if(g!==void 0&&e.webKey===void 0)u.push(`Add your search key: edit ${de(t,".env")} and set ${g}= — web_fetch works without it, web_search does not`);if(xA(e)&&e.composioKey===void 0)u.push(`Add your Composio key: edit ${de(t,".env")} and set ${En}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)u.push(`Add your bot token: message @BotFather with /newbot, then edit ${de(t,".env")} and set ${uo}=`);let c=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],f=c.length>0||e.server==="local",m=[...c,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(r)u.push(`open ${nA(i,tn(t))} — the web UI. The service is serving `+`${tn(t)} now; ${m} ${c.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),u.push(`${A.slug} run ${d} — talks to it here, attached to that same service.`);else u.push(`${A.slug} run ${d}`);if(f&&!r){if(u.push(`${A.slug} serve ${d} — starts ${m}; \`run\` starts neither`),e.daemon==="service")u.push(`${A.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(e.telegram==="connected"&&e.telegramAllow===void 0)u.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(xA(e))u.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");u.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${d} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches the configured catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${d} <name>\` writes one.`),u.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${l}\` shows exactly what still reads as a template.`);let y=r?`
34
34
  it is running in the background now — \`${A.slug} status\` at any time,
35
35
  \`${A.slug} restart ${d}\` after editing it, and \`${A.slug} stop\` turns everything off.
36
- `:"";return`${r?`
36
+ `:"";return`${s?`
37
37
  this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
38
38
  frontier-class model, and activates automatically if you upgrade.
39
- `:""}${g}
40
- `+u.map((P,y)=>` ${y+1}. ${P}
41
- `).join("")}var nn=16;function tn(e=process.stdin){let t=[],r=[],i=(s)=>{let a=typeof s==="string"?s:s.toString("utf8");if(r.push(a),r.length>nn)r.splice(0,r.length-nn);if(t.push(...ea(a)),t.length>nn)t.splice(0,t.length-nn)};return e.on("data",i),{correct:(s,a)=>Aa(s,a,t),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Jt=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${A.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function dn(e){let t=e.TERM_PROGRAM??"";if(t==="vscode")return"vscode";if(t==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(t==="WarpTerminal")return"warp";if(t==="iTerm.app")return"iterm2";if(t==="Apple_Terminal")return"apple";return"unknown"}function mn(e){return Jt.find((t)=>t.id===e)}function Qt(){return Jt}function as(e,t){return t.marker!==void 0&&e.includes(t.marker)}function fs(e,t){let r=t.line;if(r===void 0)return;if(t.id!=="vscode"){let l=e.trimEnd();return l===""?`${r}
39
+ `:""}${y}
40
+ `+u.map((T,b)=>` ${b+1}. ${T}
41
+ `).join("")}var ln=16;function un(e=process.stdin){let t=[],s=[],i=(r)=>{let a=typeof r==="string"?r:r.toString("utf8");if(s.push(a),s.length>ln)s.splice(0,s.length-ln);if(t.push(...Xs(a)),t.length>ln)t.splice(0,t.length-ln)};return e.on("data",i),{correct:(r,a)=>ta(r,a,t),takeRaw:()=>s.shift(),close:()=>{e.off("data",i)}}}var er=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${A.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function hn(e){let t=e.TERM_PROGRAM??"";if(t==="vscode")return"vscode";if(t==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(t==="WarpTerminal")return"warp";if(t==="iTerm.app")return"iterm2";if(t==="Apple_Terminal")return"apple";return"unknown"}function wn(e){return er.find((t)=>t.id===e)}function or(){return er}function mr(e,t){return t.marker!==void 0&&e.includes(t.marker)}function hr(e,t){let s=t.line;if(s===void 0)return;if(t.id!=="vscode"){let l=e.trimEnd();return l===""?`${s}
42
42
  `:`${l}
43
- ${r}
43
+ ${s}
44
44
  `}let i=e.trim();if(i===""||i==="[]")return`[
45
- ${r}
45
+ ${s}
46
46
  ]
47
- `;let s=i.indexOf("[");if(s===-1)return;let d=i.slice(s+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,s+1)}
48
- ${r}${d}
49
- ${i.slice(s+1)}`}async function ms(e={}){let t=gt({plain:!1,json:!1,oneShot:!1});if(t.mode!=="rich")throw new n({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${t.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let r=Ke(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,s=dn(process.env),a=mn(s)?.name??s,[{render:d},{createElement:l},{KeyProbe:u}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-fk5krzks.js")]),p=()=>{},c=new Promise((g)=>{p=g}),f=tn();H(()=>{f.close()}),wt(),process.stdout.write(_t);let m=d(l(u,{columns:Ue(process.stdout.columns,Me),asked:i,terminal:a,takeRaw:f.takeRaw,correctKeys:f.correct,onDone:p}),{exitOnCtrlC:!1,...r});return H(()=>m.unmount()),await c,m.unmount(),f.close(),Ze(),await ht(),o}var Di=24,Ln=22;function Mn(e){let t=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${t===""?"":` ${t}`}`}function ps(e){let t=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?t:`-${e.short}, ${t}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(Di-1)} ${e.help}${i}`}var ys=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
50
- delivery reads the channel back out of the key.`;function Hi(e){let t=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((s)=>s.value.length))+2;t.push("",`${r.name}:`);for(let s of r.choices)t.push(` ${s.value.padEnd(i)}${s.help}`)}return t}function Dn(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Mn(e)} [flags]`,...Hi(e),"","flags:",...ln(e).map(ps)];if(e.flags.some((i)=>i.name==="session"))r.push("",ys);return`${r.join(`
47
+ `;let r=i.indexOf("[");if(r===-1)return;let d=i.slice(r+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,r+1)}
48
+ ${s}${d}
49
+ ${i.slice(r+1)}`}async function yr(e={}){let t=at({plain:!1,json:!1,oneShot:!1});if(t.mode!=="rich")throw new n({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${t.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let s=Ke(e.noEnhancedKeys),i=s.kittyKeyboard!==void 0,r=hn(process.env),a=wn(r)?.name??r,[{render:d},{createElement:l},{KeyProbe:u}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-6t531sy6.js")]),g=()=>{},c=new Promise((y)=>{g=y}),f=un();H(()=>{f.close()}),wt(),process.stdout.write(Rt);let m=d(l(u,{columns:Ue(process.stdout.columns,Me),asked:i,terminal:a,takeRaw:f.takeRaw,correctKeys:f.correct,onDone:g}),{exitOnCtrlC:!1,...s});return H(()=>m.unmount()),await c,m.unmount(),f.close(),Ze(),await Ct(),o}var Qi=24,Dn=22;function Gn(e){let t=e.args.map((s)=>{let i=s.variadic===!0?`${s.name}...`:s.name;return s.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${t===""?"":` ${t}`}`}function $r(e){let t=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,s=e.short===void 0?t:`-${e.short}, ${t}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${s.padEnd(Qi-1)} ${e.help}${i}`}var vr=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
50
+ delivery reads the channel back out of the key.`;function ea(e){let t=[];for(let s of e.args){if(s.choices===void 0||s.choices.length===0)continue;let i=Math.max(...s.choices.map((r)=>r.value.length))+2;t.push("",`${s.name}:`);for(let r of s.choices)t.push(` ${r.value.padEnd(i)}${r.help}`)}return t}function Bn(e){if(e!==void 0){let s=[e.summary,"","usage:",` ${Gn(e)} [flags]`,...ea(e),"","flags:",...cn(e).map($r)];if(e.flags.some((i)=>i.name==="session"))s.push("",vr);return`${s.join(`
51
51
  `)}
52
- `}let t=Math.max(...at.map((r)=>Mn(r).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...at.map((r)=>` ${Mn(r).padEnd(t)}${r.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...cn.map(ps),"",ys,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(Ln)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Ln)}set to anything to force plain output`,` ${"DEBUG".padEnd(Ln)}print stack traces on failure`].join(`
52
+ `}let t=Math.max(...st.map((s)=>Gn(s).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...st.map((s)=>` ${Gn(s).padEnd(t)}${s.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...gn.map($r),"",vr,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(Dn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Dn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Dn)}print stack traces on failure`].join(`
53
53
  `)}
54
- `}function ws(e){if(!(e instanceof Error))return;let t=e.code;if(t!=="ERR_MODULE_NOT_FOUND"&&t!=="MODULE_NOT_FOUND")return;let r=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return r?.[1]==="ink"||r?.[1]==="react"?r[1]:void 0}import{readFileSync as Gi,statSync as qi}from"node:fs";var Vi=65536;function bs(e=process.env,t=(r)=>process.stderr.write(`${r}
55
- `)){let r=[];for(let[i,s]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||s===void 0||s==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(qi(s).size>Vi)continue;e[a]=Gi(s,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(d){t(`${i} names ${s}, which could not be read (${d instanceof Error?d.message:String(d)}); ${a} is not set from it.`)}}return r}var Yi=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function Qi(e,t){return Yi.some((r)=>r.name===e&&t.includes(r.contains))}function Zi(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var $s;function vs(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if($s)return;if(Zi(e))return;let t=process.emitWarning;$s=t,process.emitWarning=(r,...i)=>{let s=typeof r==="string"?na(i):r.name,a=typeof r==="string"?r:r.message;if(Qi(s,a))return;Reflect.apply(t,process,[r,...i])}}function na(e){let t=e[0];return typeof t==="string"?t:"Warning"}var Ss=96;async function Ps(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});try{let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let u=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(u,null,2)}
56
- `),o;return process.stdout.write(C([{label:"passages",value:String(u.passages)},{label:"files read",value:String(u.indexed.length)},{label:"conversations",value:u.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(u.sessions.length)},{label:"shared scopes",value:u.scopes.length===0?"none":u.scopes.join(", ")},{label:"dropped",value:u.dropped.length===0?"":u.dropped.join(", ")}])),process.stdout.write(u.indexed.length===0&&u.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
54
+ `}function kr(e){if(!(e instanceof Error))return;let t=e.code;if(t!=="ERR_MODULE_NOT_FOUND"&&t!=="MODULE_NOT_FOUND")return;let s=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return s?.[1]==="ink"||s?.[1]==="react"?s[1]:void 0}import{readFileSync as na,statSync as ra}from"node:fs";var sa=65536;function Pr(e=process.env,t=(s)=>process.stderr.write(`${s}
55
+ `)){let s=[];for(let[i,r]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||r===void 0||r==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(ra(r).size>sa)continue;e[a]=na(r,"utf8").replace(/\r?\n$/,""),s.push(a)}catch(d){t(`${i} names ${r}, which could not be read (${d instanceof Error?d.message:String(d)}); ${a} is not set from it.`)}}return s}var ia=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function aa(e,t){return ia.some((s)=>s.name===e&&t.includes(s.contains))}function da(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var Rr;function Tr(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(Rr)return;if(da(e))return;let t=process.emitWarning;Rr=t,process.emitWarning=(s,...i)=>{let r=typeof s==="string"?la(i):s.name,a=typeof s==="string"?s:s.message;if(aa(r,a))return;Reflect.apply(t,process,[s,...i])}}function la(e){let t=e[0];return typeof t==="string"?t:"Warning"}var _r=96;async function Nr(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});try{let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let u=await s.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(u,null,2)}
56
+ `),o;return process.stdout.write(p([{label:"passages",value:String(u.passages)},{label:"files read",value:String(u.indexed.length)},{label:"conversations",value:u.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(u.sessions.length)},{label:"shared scopes",value:u.scopes.length===0?"none":u.scopes.join(", ")},{label:"dropped",value:u.dropped.length===0?"":u.dropped.join(", ")}])),process.stdout.write(u.indexed.length===0&&u.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
57
57
  Read: ${[...u.indexed,...u.sessions].join(", ")}
58
58
  `),o}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
59
- `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),E;let s=await r.searchMemory({query:i,limit:e.limit??10}),a=s.hits.filter((u)=>u.score>=s.threshold),d=e.all===!0?s.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:s.corpus,threshold:s.threshold,carried:s.carried??null,hits:d.map((u)=>({source:u.passage.source,at:u.passage.at,score:u.score,lexical:u.lexical,coverage:u.coverage,tokens:u.tokens,wouldInject:u.score>=s.threshold,carried:u.passage.source===s.carried,text:u.passage.text}))},null,2)}
60
- `),o;if(process.stdout.write(C([{label:"corpus",value:`${s.corpus} passage${s.corpus===1?"":"s"}`},{label:"threshold",value:s.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),s.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),o;if(d.length===0)return process.stdout.write(`
61
- Nothing ${e.all===!0?"matched":`scored above ${s.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
62
- `),o;let l=Math.max(6,...d.map((u)=>ks(u,s.carried).length));process.stdout.write(`
63
- ${ie("SCORE",6)} ${ie("LEXICAL",7)} ${ie("COVER",5)} ${ie("SOURCE",l)} ${ie("LEARNED",10)} PASSAGE
64
- `);for(let u of d){let p=u.score>=s.threshold?" ":"·";process.stdout.write(`${ie(u.score.toFixed(3),6)} ${ie(u.lexical.toFixed(3),7)} ${ie(u.coverage.toFixed(2),5)} ${ie(ks(u,s.carried),l)} ${ie(u.passage.at.slice(0,10),10)} ${p}${ta(u.passage.text)}
59
+ `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),E;let r=await s.searchMemory({query:i,limit:e.limit??10}),a=r.hits.filter((u)=>u.score>=r.threshold),d=e.all===!0?r.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:r.corpus,threshold:r.threshold,carried:r.carried??null,hits:d.map((u)=>({source:u.passage.source,at:u.passage.at,score:u.score,lexical:u.lexical,coverage:u.coverage,tokens:u.tokens,wouldInject:u.score>=r.threshold,carried:u.passage.source===r.carried,text:u.passage.text}))},null,2)}
60
+ `),o;if(process.stdout.write(p([{label:"corpus",value:`${r.corpus} passage${r.corpus===1?"":"s"}`},{label:"threshold",value:r.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),r.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),o;if(d.length===0)return process.stdout.write(`
61
+ Nothing ${e.all===!0?"matched":`scored above ${r.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
62
+ `),o;let l=Math.max(6,...d.map((u)=>Cr(u,r.carried).length));process.stdout.write(`
63
+ ${se("SCORE",6)} ${se("LEXICAL",7)} ${se("COVER",5)} ${se("SOURCE",l)} ${se("LEARNED",10)} PASSAGE
64
+ `);for(let u of d){let g=u.score>=r.threshold?" ":"·";process.stdout.write(`${se(u.score.toFixed(3),6)} ${se(u.lexical.toFixed(3),7)} ${se(u.coverage.toFixed(2),5)} ${se(Cr(u,r.carried),l)} ${se(u.passage.at.slice(0,10),10)} ${g}${ca(u.passage.text)}
65
65
  `)}if(e.all===!0&&a.length<d.length)process.stdout.write(`
66
66
  ${d.length-a.length} shown below the threshold; a turn would not inject those.
67
- `);if(s.carried!==void 0&&d.some((u)=>u.passage.source===s.carried))process.stdout.write(`
68
- ${s.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
69
- `);return o}finally{await t.stop("cli-exit")}}function ta(e){let t=e.replace(/\s+/g," ").trim();return t.length<=Ss?t:`${t.slice(0,Ss-1)}…`}function ie(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ks(e,t){return e.passage.source===t?`${e.passage.source} *`:e.passage.source}var sa=["context_length","context_window","max_context_length","max_model_len"],oa=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let t=e.prompt_tokens_details;return yn(t)?t.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function yn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Hn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Rs(e,t){let r=yn(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let s=t.toLowerCase();for(let a of i){if(!yn(a))continue;let d=typeof a.id==="string"?a.id.toLowerCase():void 0;if(d===void 0)continue;if(!(d===s||d.endsWith(`/${s}`)||s.endsWith(`/${d}`)))continue;for(let u of sa){let p=Hn(a[u]);if(p!==void 0)return{technique:"metadata",tokens:p,bound:"ceiling",detail:`GET /models published ${u}: ${p}`}}return}return}function Gn(e){let t=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],r=[];for(let i of t){let s=i.exec(e);if(s?.[1]===void 0)continue;let a=Hn(Number(s[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function xs(e){if(!yn(e))return;let t=Hn(e.prompt_tokens)??0;for(let[r,i]of oa){let s=i(e);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:t,field:r}}return{cached:void 0,promptTokens:t,field:void 0}}function Ts(e,t,r){if(e===void 0||t===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(t.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=t.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${t.promptTokens} prompt tokens, via ${t.field}`};return{supported:!1,detail:`${t.field} came back 0 on an identical repeat of a ${r}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function Pe(e){let t=e.filter((i)=>i.bound==="ceiling");return(t.length>0?t:e).reduce((i,s)=>i===void 0||s.tokens>i.tokens?s:i,void 0)}function Os(e,t,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${t.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
70
- `)}function _s(e,t,r){return`measured ${t} against ${e} — ${r}`}function Ns(e,t){let r=Math.max(1,e),i=0,s=0;while(r<t)i+=r,s+=1,r*=2;return i+=t,s+=1,{requests:s,tokens:i}}var ia=2000000000,js=1024,Us=8192,Ls=2097152;function Ms(e){return"context ".repeat(Math.max(1,e))}async function xe(e){let t=await e.text();try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Ds(e,t){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let s=i.message;if(typeof s==="string")return s}if(typeof r.message==="string")return r.message}return t}async function aa(e,t,r){try{let i=await t(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:s}=await xe(i),a=Rs(s,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function la(e,t,r){try{let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:ia})}),{text:s,json:a}=await xe(i);if(i.ok)return r.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let d=Ds(a,s.slice(0,400)),l=Gn(d);if(l===void 0)return r.push(`the refusal named no number: ${d.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let u=/max_?tokens/i.test(d);return{window:u?void 0:{technique:"refusal",tokens:l,bound:"ceiling",detail:`refused an over-range request naming ${l}`},outputCeiling:u?l:void 0}}catch(i){return r.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function Fs(e,t,r){let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:s}=await xe(i),a=typeof s==="object"&&s!==null?s.usage:void 0;return xs(a)}async function ca(e,t,r){let i=`${Ms(js)}
71
- Reply with the single character x.`;try{let s=await Fs(e,t,i),a=await Fs(e,t,i);return Ts(s,a,js)}catch(s){return r.push(`the caching probe failed: ${s instanceof Error?s.message:String(s)}`),{supported:void 0,detail:"the probe did not complete"}}}async function ua(e,t,r){let i=Us,s=0;while(i<=Ls){let a;try{a=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ms(i)}],max_tokens:1})})}catch(p){r.push(`the search stopped at ${i}: ${p instanceof Error?p.message:String(p)}`);break}if(a.ok){let{json:p}=await xe(a),c=typeof p==="object"&&p!==null?p.usage:void 0,f=typeof c==="object"&&c!==null?c.prompt_tokens:void 0;s=typeof f==="number"&&Number.isFinite(f)?f:s,i*=2;continue}let{text:d,json:l}=await xe(a),u=Gn(Ds(l,d.slice(0,400)));if(u!==void 0)return{technique:"search",tokens:u,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${u}`};break}if(s===0)return;return{technique:"search",tokens:s,bound:"floor",detail:`accepted a prompt the endpoint counted at ${s} tokens; nothing above it named a number`}}function fa(e,t){let r=Pe(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,s=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[L(` ${e.role} · ${e.modelId}`),C([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:s},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...t===void 0?[]:[{label:"price",value:`$${t}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((d)=>` · ${d}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Os(e.modelId,r.tokens,e.outputCeiling).split(`
67
+ `);if(r.carried!==void 0&&d.some((u)=>u.passage.source===r.carried))process.stdout.write(`
68
+ ${r.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
69
+ `);return o}finally{await t.stop("cli-exit")}}function ca(e){let t=e.replace(/\s+/g," ").trim();return t.length<=_r?t:`${t.slice(0,_r-1)}…`}function se(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Cr(e,t){return e.passage.source===t?`${e.passage.source} *`:e.passage.source}var ua=["context_length","context_window","max_context_length","max_model_len"],fa=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let t=e.prompt_tokens_details;return bn(t)?t.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function bn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Xn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Fr(e,t){let s=bn(e)?e.data:void 0,i=Array.isArray(s)?s:Array.isArray(e)?e:void 0;if(i===void 0)return;let r=t.toLowerCase();for(let a of i){if(!bn(a))continue;let d=typeof a.id==="string"?a.id.toLowerCase():void 0;if(d===void 0)continue;if(!(d===r||d.endsWith(`/${r}`)||r.endsWith(`/${d}`)))continue;for(let u of ua){let g=Xn(a[u]);if(g!==void 0)return{technique:"metadata",tokens:g,bound:"ceiling",detail:`GET /models published ${u}: ${g}`}}return}return}function Qn(e){let t=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],s=[];for(let i of t){let r=i.exec(e);if(r?.[1]===void 0)continue;let a=Xn(Number(r[1].replaceAll(/[,_]/g,"")));if(a!==void 0)s.push(a)}if(s.length===0)return;return Math.max(...s)}function Lr(e){if(!bn(e))return;let t=Xn(e.prompt_tokens)??0;for(let[s,i]of fa){let r=i(e);if(typeof r==="number"&&Number.isFinite(r))return{cached:r,promptTokens:t,field:s}}return{cached:void 0,promptTokens:t,field:void 0}}function Kr(e,t,s){if(e===void 0||t===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(t.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=t.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${t.promptTokens} prompt tokens, via ${t.field}`};return{supported:!1,detail:`${t.field} came back 0 on an identical repeat of a ${s}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function xe(e){let t=e.filter((i)=>i.bound==="ceiling");return(t.length>0?t:e).reduce((i,r)=>i===void 0||r.tokens>i.tokens?r:i,void 0)}function Ur(e,t,s){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${t.toLocaleString("en-US").replaceAll(",","_")},`,...s===void 0?[]:[` maxOutput: ${s.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
70
+ `)}function Mr(e,t,s){return`measured ${t} against ${e} — ${s}`}function Hr(e,t){let s=Math.max(1,e),i=0,r=0;while(s<t)i+=s,r+=1,s*=2;return i+=t,r+=1,{requests:r,tokens:i}}var ma=2000000000,Wr=1024,Br=8192,qr=2097152;function Vr(e){return"context ".repeat(Math.max(1,e))}async function Ae(e){let t=await e.text();try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Xr(e,t){if(typeof e==="object"&&e!==null){let s=e,i=s.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let r=i.message;if(typeof r==="string")return r}if(typeof s.message==="string")return s.message}return t}async function pa(e,t,s){try{let i=await t(e.models,{headers:e.headers});if(!i.ok){s.push(`GET /models answered ${i.status}`);return}let{json:r}=await Ae(i),a=Fr(r,e.modelId);if(a===void 0)s.push("GET /models published no context length");return a}catch(i){s.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function ha(e,t,s){try{let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:ma})}),{text:r,json:a}=await Ae(i);if(i.ok)return s.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let d=Xr(a,r.slice(0,400)),l=Qn(d);if(l===void 0)return s.push(`the refusal named no number: ${d.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let u=/max_?tokens/i.test(d);return{window:u?void 0:{technique:"refusal",tokens:l,bound:"ceiling",detail:`refused an over-range request naming ${l}`},outputCeiling:u?l:void 0}}catch(i){return s.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function Gr(e,t,s){let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:s}],max_tokens:1})});if(!i.ok)return;let{json:r}=await Ae(i),a=typeof r==="object"&&r!==null?r.usage:void 0;return Lr(a)}async function ga(e,t,s){let i=`${Vr(Wr)}
71
+ Reply with the single character x.`;try{let r=await Gr(e,t,i),a=await Gr(e,t,i);return Kr(r,a,Wr)}catch(r){return s.push(`the caching probe failed: ${r instanceof Error?r.message:String(r)}`),{supported:void 0,detail:"the probe did not complete"}}}async function ya(e,t,s){let i=Br,r=0;while(i<=qr){let a;try{a=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Vr(i)}],max_tokens:1})})}catch(g){s.push(`the search stopped at ${i}: ${g instanceof Error?g.message:String(g)}`);break}if(a.ok){let{json:g}=await Ae(a),c=typeof g==="object"&&g!==null?g.usage:void 0,f=typeof c==="object"&&c!==null?c.prompt_tokens:void 0;r=typeof f==="number"&&Number.isFinite(f)?f:r,i*=2;continue}let{text:d,json:l}=await Ae(a),u=Qn(Xr(l,d.slice(0,400)));if(u!==void 0)return{technique:"search",tokens:u,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${u}`};break}if(r===0)return;return{technique:"search",tokens:r,bound:"floor",detail:`accepted a prompt the endpoint counted at ${r} tokens; nothing above it named a number`}}function wa(e,t){let s=xe(e.findings),i=s===void 0?"nothing measured — every technique came back empty":`${s.tokens} (${s.bound}) · ${s.detail}`,r=s===void 0?"":s.tokens===e.declared?"matches what is configured":s.bound==="ceiling"&&s.tokens>e.declared?`configured value is ${e.declared}, which is ${(s.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[L(` ${e.role} · ${e.modelId}`),p([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:r},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...t===void 0?[]:[{label:"price",value:`$${t}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((d)=>` · ${d}`)],...s===void 0||s.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Ur(e.modelId,s.tokens,e.outputCeiling).split(`
72
72
  `).map((d)=>` ${d}`).join(`
73
73
  `)]].join(`
74
- `)}async function Gs(e){let t=e.fetch??globalThis.fetch;try{let r=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:i}=r,s=Mt(i).filter((u)=>u.role===u.configuredAs),a=!1;if(e.window){let u=Ns(Us,Ls),p=u.tokens*s.length,c=e.price===void 0?"":` ≈ $${(p/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${u.requests} requests per role, about ${p.toLocaleString("en-US")} input tokens in total${c}.
74
+ `)}async function zr(e){let t=e.fetch??globalThis.fetch;try{let s=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:i}=s,r=Nt(i).filter((u)=>u.role===u.configuredAs),a=!1;if(e.window){let u=Hr(Br,qr),g=u.tokens*r.length,c=e.price===void 0?"":` ≈ $${(g/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${u.requests} requests per role, about ${g.toLocaleString("en-US")} input tokens in total${c}.
75
75
  That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
76
76
  Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
77
- `),a=e.yes||await TA("spend it?"),process.stdout.write(a?`
77
+ `),a=e.yes||await MA("spend it?"),process.stdout.write(a?`
78
78
  `:`
79
79
  Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
80
80
 
81
- `)}let d=[];for(let u of s){let p=i.model[u.role]??i.model.main;if(p.baseUrl===void 0){process.stdout.write(`model.${u.role} uses the ${p.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${u.window.contextWindow.toLocaleString("en-US")} tokens (${u.window.source}).
82
- `);continue}let c={chat:ho(p.baseUrl),models:ci(p.baseUrl),headers:li(p.apiKeyEnv,r.env,`model.${u.role}`),modelId:p.id},f=[],m=[],g=await aa(c,t,f);if(g!==void 0)m.push(g);let R=await la(c,t,f);if(R.window!==void 0)m.push(R.window);let P=await ca(c,t,f);if(a){let y=await ua(c,t,f);if(y!==void 0)m.push(y)}d.push({role:u.role,modelId:p.id,baseUrl:p.baseUrl,declared:u.window.contextWindow,declaredSource:u.window.source,findings:m,cache:P,outputCeiling:R.outputCeiling,failures:f})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:d},null,2)}
83
- `),o;let l=e.write?await ma(r.path,d):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${d.length} role${d.length===1?"":"s"}`,...d.map((u)=>fa(u,e.price)),"",...e.write?[...l.written.length===0?[]:[" written to the manifest:",...l.written.map((u)=>` ${u}`)],...l.refused.length===0?[]:[" not written:",...l.refused.map((u)=>` ${u}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[pa(d)],""].join(`
84
- `)),o}catch(r){if(h(r))return process.stderr.write(`${r.format()}
85
- `),E;throw r}}async function ma(e,t){let r=[],i=[];for(let s of t){let a=Pe(s.findings);if(a===void 0){i.push(`${s.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${s.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===s.declared){i.push(`${s.role}: already ${a.tokens}, nothing to change`);continue}await Fe({file:e,path:["model",s.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${s.role}: ${s.declared} → ${a.tokens}`)}return{written:r,refused:i}}function pa(e){let t=e.filter((a)=>Pe(a.findings)?.bound==="ceiling");if(t.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=t[0],i=r===void 0?void 0:Pe(r.findings);if(r===void 0||i===void 0)return"";let s=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${_s(s,new Date().toISOString().slice(0,10),i.detail)}`].join(`
86
- `)}import{readFileSync as ha}from"node:fs";async function Ws(e){let t=W();if(e.action==="show"){let p;try{p=ha(qe(t),"utf8").trim()||void 0}catch{p=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:p??null})}
87
- `);else process.stdout.write(p===void 0?`No owner yet. \`${A.slug} init\` or \`${A.slug} owner adopt <agent>\` makes you one.
88
- `:`${p}
89
- `);return o}let r=e.manifestPath;if(r===void 0||r==="")throw new n({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${A.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=U(r).id??"",s=await re.open({path:e.store??G()}),a;try{a=await we(s,r,t)}finally{await s.close()}let d=await Fe({file:r,path:["sessions","scope"],value:"owner",fallback:(p)=>/^sessions:/m.test(p)?void 0:`${p.replace(/\n*$/,`
81
+ `)}let d=[];for(let u of r){let g=i.model[u.role]??i.model.main;if(g.baseUrl===void 0){process.stdout.write(`model.${u.role} uses the ${g.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${u.window.contextWindow.toLocaleString("en-US")} tokens (${u.window.source}).
82
+ `);continue}let c={chat:Co(g.baseUrl),models:ai(g.baseUrl),headers:gi(g.apiKeyEnv,s.env,`model.${u.role}`),modelId:g.id},f=[],m=[],y=await pa(c,t,f);if(y!==void 0)m.push(y);let R=await ha(c,t,f);if(R.window!==void 0)m.push(R.window);let T=await ga(c,t,f);if(a){let b=await ya(c,t,f);if(b!==void 0)m.push(b)}d.push({role:u.role,modelId:g.id,baseUrl:g.baseUrl,declared:u.window.contextWindow,declaredSource:u.window.source,findings:m,cache:T,outputCeiling:R.outputCeiling,failures:f})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:d},null,2)}
83
+ `),o;let l=e.write?await ba(s.path,d):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${d.length} role${d.length===1?"":"s"}`,...d.map((u)=>wa(u,e.price)),"",...e.write?[...l.written.length===0?[]:[" written to the manifest:",...l.written.map((u)=>` ${u}`)],...l.refused.length===0?[]:[" not written:",...l.refused.map((u)=>` ${u}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[$a(d)],""].join(`
84
+ `)),o}catch(s){if(h(s))return process.stderr.write(`${s.format()}
85
+ `),E;throw s}}async function ba(e,t){let s=[],i=[];for(let r of t){let a=xe(r.findings);if(a===void 0){i.push(`${r.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${r.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===r.declared){i.push(`${r.role}: already ${a.tokens}, nothing to change`);continue}await Fe({file:e,path:["model",r.role,"capabilities","contextWindow"],value:a.tokens}),s.push(`${r.role}: ${r.declared} → ${a.tokens}`)}return{written:s,refused:i}}function $a(e){let t=e.filter((a)=>xe(a.findings)?.bound==="ceiling");if(t.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let s=t[0],i=s===void 0?void 0:xe(s.findings);if(s===void 0||i===void 0)return"";let r=new URL(s.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${Mr(r,new Date().toISOString().slice(0,10),i.detail)}`].join(`
86
+ `)}import{readFileSync as va}from"node:fs";async function Qr(e){let t=W();if(e.action==="show"){let g;try{g=va(Je(t),"utf8").trim()||void 0}catch{g=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:g??null})}
87
+ `);else process.stdout.write(g===void 0?`No owner yet. \`${A.slug} init\` or \`${A.slug} owner adopt <agent>\` makes you one.
88
+ `:`${g}
89
+ `);return o}let s=e.manifestPath;if(s===void 0||s==="")throw new n({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${A.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=U(s).id??"",r=await re.open({path:e.store??G()}),a;try{a=await ve(r,s,t)}finally{await r.close()}let d=await Fe({file:s,path:["sessions","scope"],value:"owner",fallback:(g)=>/^sessions:/m.test(g)?void 0:`${g.replace(/\n*$/,`
90
90
  `)}
91
91
  # One conversation with you across the web, the terminal and every channel.
92
92
  sessions:
93
93
  scope: owner
94
- `}),l=await MA(r,e.store),u=l.kind==="reloaded"||l.kind==="pending"?`reloaded by pid ${l.pid}`:l.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${l.pid} did not reload it (${l.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:d.changed,reload:l.kind})}
94
+ `}),l=await NA(s,e.store),u=l.kind==="reloaded"||l.kind==="pending"?`reloaded by pid ${l.pid}`:l.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${l.pid} did not reload it (${l.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:d.changed,reload:l.kind})}
95
95
  `),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${d.changed?"":" (already)"}`,`you on ${a.channelIds.length===0?"the web and the terminal only — no allowFrom entries to recognise you by on a channel":a.channelIds.join(", ")}`,`host ${u}`,""].join(`
96
- `)),o}import{existsSync as rr,rmSync as Sa}from"node:fs";import{resolve as ka}from"node:path";var ga={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Vs(e){if(e===null||typeof e!=="object")return!1;let t=e.kind;return t==="network"||t==="env"||t==="fs"||t==="exec"||t==="store"}async function Js(e,t={}){let r=[],i=[],s=t.hostVersion??Ye,a=(m,g,R)=>{r.push({level:"error",check:m,message:g,hint:R})},d=(m,g,R)=>{r.push({level:"warning",check:m,message:g,hint:R})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(ur(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let l=ur(s,e.dispachApi);if(l===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!l)d("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${s}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")d("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[m,g]of(e.permissions??[]).entries())if(!Vs(g))a("permissions",`\`permissions[${m}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let u=t.config??{};if(e.configSchema!==void 0){let m=e.configSchema.safeParse(u);if(m.success)u=m.data;else d("configSchema","The schema refused the config this suite passed.","Pass a valid `config` through `conformance(plugin, { config })`. The default is `{}`, which a schema with required fields correctly rejects.")}let p={defineChannel:(m)=>i.push(`channel:${m}`),defineToolProvider:(m)=>i.push(`toolProvider:${m}`),defineModelTransport:(m)=>i.push(`modelTransport:${m}`),defineMediaProvider:(m)=>i.push(`mediaProvider:${m}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(m)=>i.push(`middleware:${m.name}`),defineRoute:(m)=>i.push(`route:${m.method} ${m.path}`),config:u,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:ga,events:new dr({runtimeId:"conformance"})},c=performance.now();try{await e.setup(p)}catch(m){a("setup",`\`setup\` threw: ${m instanceof Error?m.message:String(m)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let f=Math.round((performance.now()-c)*100)/100;if(f>Er)a("setup budget",`\`setup\` took ${f} ms against a ${Er} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)d("setup","`setup` registered nothing.","A plugin that registers no channel, tool provider, script runner or middleware extends nothing. Every `define*` and `use` call is recorded, so registering something and still seeing this means the registration did not run — check for a branch in `setup` that skipped it.");return{ok:r.every((m)=>m.level!=="error"),findings:r,registered:i,setupMs:f,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Vs)}}}import{existsSync as ue,mkdirSync as ya,readdirSync as wa,readFileSync as Bn,renameSync as Xs,rmSync as ce,writeFileSync as ba}from"node:fs";import{join as Q}from"node:path";var zs=".origin.json";function $a(e){let t=Q(e,zs);if(!ue(t))return;try{return JSON.parse(Bn(t,"utf8"))}catch{return}}function Xn(e){let t=ge(e),r;try{r=wa(t)}catch{return[]}let i=[];for(let s of r.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let a=Q(t,s);if(!ue(Q(a,"package.json"))&&!ue(Q(a,"index.js")))continue;let d=$a(a);i.push({name:s,dir:a,...d===void 0?{}:{origin:d}})}return i}function Ys(e){let t=Q(e,"package.json");if(!ue(t))return Q(e,"index.js");try{let r=JSON.parse(Bn(t,"utf8"));if(typeof r.main==="string"&&r.main!=="")return Q(e,r.main)}catch{}return Q(e,"index.js")}function Qs(e){let t=Q(e,"package.json");if(!ue(t))return;let r;try{r=JSON.parse(Bn(t,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(r.dependencies??{});if(i.length===0)return;if(ue(Q(e,"node_modules")))return;let s=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${s}${i.length>4?", …":""}) and ships no node_modules`}function Zs(e,t){let i=((t??e).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!vA(i))throw new n({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function tr(e,t={}){let r=t.git??Jr,i=Or(e.name,t.env),s=`${i}.partial`;ya(ge(t.env),{recursive:!0}),ce(s,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,s]);if(a.code!==0)throw ce(s,{recursive:!0,force:!0}),va(e,a.stderr,a.timedOut===!0);let d=await r(["rev-parse","--short","HEAD"],s),l=d.code===0?d.stdout.trim():"unknown",u=e.path===void 0?s:Q(s,e.path);if(!ue(u))throw ce(s,{recursive:!0,force:!0}),new n({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${l}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ce(Q(u,".git"),{recursive:!0,force:!0});try{await t.inspect?.(u)}catch(c){throw ce(s,{recursive:!0,force:!0}),c}if(ce(i,{recursive:!0,force:!0}),u===s)Xs(s,i);else Xs(u,i),ce(s,{recursive:!0,force:!0});let p={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:l,fetchedAt:new Date().toISOString()};return ba(Q(i,zs),`${JSON.stringify(p,null,4)}
97
- `),{dir:i,commit:l}}function va(e,t,r){let i=t.trim().split(`
98
- `).slice(-3).join(" ");if(r)return new n({code:"plugin_fetch_timeout",message:`${e.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${e.name} is untouched.`});return new n({code:"plugin_fetch_failed",message:`${e.name}: could not clone ${e.url}${i.length===0?"":` — ${i}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function mr(e){switch(e.action){case"list":return await Pa(e);case"add":return await Ra(e);case"remove":return await Oa(e);default:throw new n({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${A.slug} plugins list <agent>\`.`})}}async function Pa(e){let t=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(e.env),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),store:G(e.env),lease:!1});H(()=>t.stop("cli-exit"));let r=[...t.plugins.values()].flat(),i=Xn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:qr},null,2)}
99
- `),o;if(r.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
96
+ `)),o}import{existsSync as bs,rmSync as xa}from"node:fs";import{resolve as Oa}from"node:path";var Sa={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Zr(e){if(e===null||typeof e!=="object")return!1;let t=e.kind;return t==="network"||t==="env"||t==="fs"||t==="exec"||t==="store"}async function is(e,t={}){let s=[],i=[],r=t.hostVersion??Ye,a=(m,y,R)=>{s.push({level:"error",check:m,message:y,hint:R})},d=(m,y,R)=>{s.push({level:"warning",check:m,message:y,hint:R})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(dr(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let l=dr(r,e.dispachApi);if(l===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!l)d("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${r}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")d("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[m,y]of(e.permissions??[]).entries())if(!Zr(y))a("permissions",`\`permissions[${m}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let u=t.config??{};if(e.configSchema!==void 0){let m=e.configSchema.safeParse(u);if(m.success)u=m.data;else d("configSchema","The schema refused the config this suite passed.","Pass a valid `config` through `conformance(plugin, { config })`. The default is `{}`, which a schema with required fields correctly rejects.")}let g={defineChannel:(m)=>i.push(`channel:${m}`),defineToolProvider:(m)=>i.push(`toolProvider:${m}`),defineModelTransport:(m)=>i.push(`modelTransport:${m}`),defineMediaProvider:(m)=>i.push(`mediaProvider:${m}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(m)=>i.push(`middleware:${m.name}`),defineRoute:(m)=>i.push(`route:${m.method} ${m.path}`),config:u,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Sa,events:new Ir({runtimeId:"conformance"})},c=performance.now();try{await e.setup(g)}catch(m){a("setup",`\`setup\` threw: ${m instanceof Error?m.message:String(m)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let f=Math.round((performance.now()-c)*100)/100;if(f>ur)a("setup budget",`\`setup\` took ${f} ms against a ${ur} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)d("setup","`setup` registered nothing.","A plugin that registers no channel, tool provider, script runner or middleware extends nothing. Every `define*` and `use` call is recorded, so registering something and still seeing this means the registration did not run — check for a branch in `setup` that skipped it.");return{ok:s.every((m)=>m.level!=="error"),findings:s,registered:i,setupMs:f,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Zr)}}}import{existsSync as ue,mkdirSync as ka,readdirSync as Pa,readFileSync as Zn,renameSync as us,rmSync as ce,writeFileSync as Ea}from"node:fs";import{join as Q}from"node:path";var fs=".origin.json";function Ra(e){let t=Q(e,fs);if(!ue(t))return;try{return JSON.parse(Zn(t,"utf8"))}catch{return}}function et(e){let t=ge(e),s;try{s=Pa(t)}catch{return[]}let i=[];for(let r of s.sort()){if(r.startsWith(".")||r.endsWith(".partial"))continue;let a=Q(t,r);if(!ue(Q(a,"package.json"))&&!ue(Q(a,"index.js")))continue;let d=Ra(a);i.push({name:r,dir:a,...d===void 0?{}:{origin:d}})}return i}function ms(e){let t=Q(e,"package.json");if(!ue(t))return Q(e,"index.js");try{let s=JSON.parse(Zn(t,"utf8"));if(typeof s.main==="string"&&s.main!=="")return Q(e,s.main)}catch{}return Q(e,"index.js")}function hs(e){let t=Q(e,"package.json");if(!ue(t))return;let s;try{s=JSON.parse(Zn(t,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(s.dependencies??{});if(i.length===0)return;if(ue(Q(e,"node_modules")))return;let r=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${r}${i.length>4?", …":""}) and ships no node_modules`}function ys(e,t){let i=((t??e).split("/").filter((r)=>r.length>0).pop()??"").replace(/\.git$/,"");if(!kA(i))throw new n({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function ws(e,t={}){let s=t.git??jr,i=br(e.name,t.env),r=`${i}.partial`;ka(ge(t.env),{recursive:!0}),ce(r,{recursive:!0,force:!0});let a=await s(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,r]);if(a.code!==0)throw ce(r,{recursive:!0,force:!0}),Ta(e,a.stderr,a.timedOut===!0);let d=await s(["rev-parse","--short","HEAD"],r),l=d.code===0?d.stdout.trim():"unknown",u=e.path===void 0?r:Q(r,e.path);if(!ue(u))throw ce(r,{recursive:!0,force:!0}),new n({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${l}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ce(Q(u,".git"),{recursive:!0,force:!0});try{await t.inspect?.(u)}catch(c){throw ce(r,{recursive:!0,force:!0}),c}if(ce(i,{recursive:!0,force:!0}),u===r)us(r,i);else us(u,i),ce(r,{recursive:!0,force:!0});let g={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:l,fetchedAt:new Date().toISOString()};return Ea(Q(i,fs),`${JSON.stringify(g,null,4)}
97
+ `),{dir:i,commit:l}}function Ta(e,t,s){let i=t.trim().split(`
98
+ `).slice(-3).join(" ");if(s)return new n({code:"plugin_fetch_timeout",message:`${e.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${e.name} is untouched.`});return new n({code:"plugin_fetch_failed",message:`${e.name}: could not clone ${e.url}${i.length===0?"":` — ${i}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function $s(e){switch(e.action){case"list":return await Aa(e);case"add":return await Ca(e);case"remove":return await La(e);default:throw new n({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${A.slug} plugins list <agent>\`.`})}}async function Aa(e){let t=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(e.env),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),store:G(e.env),lease:!1});H(()=>t.stop("cli-exit"));let s=[...t.plugins.values()].flat(),i=et(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:s,installed:i,available:Jr},null,2)}
99
+ `),o;if(s.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
100
100
 
101
- ${qr.map((l)=>` - "${l}"`).join(`
101
+ ${Jr.map((l)=>` - "${l}"`).join(`
102
102
  `)}
103
103
 
104
104
  Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${A.slug} plugins add <agent> <repo>\`.
@@ -106,160 +106,160 @@ Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one wi
106
106
  Installed in ${ge(e.env)} and named by no agent:
107
107
  ${i.map((l)=>` - "${l.name}"`).join(`
108
108
  `)}
109
- `);return o}let s=r.map((l)=>({label:l.name,value:`${l.version} ${`${l.setupMs} ms`.padStart(9)}`,note:`${Ea(l.spec,l.lookup,i)} — ${l.registered.length===0?"registered nothing":l.registered.join(", ")}`}));process.stdout.write(`${C(s)}
110
- `);let a=r.filter((l)=>l.permissions.length>0);if(a.length>0){process.stdout.write(`
109
+ `);return o}let r=s.map((l)=>({label:l.name,value:`${l.version} ${`${l.setupMs} ms`.padStart(9)}`,note:`${_a(l.spec,l.lookup,i)} — ${l.registered.length===0?"registered nothing":l.registered.join(", ")}`}));process.stdout.write(`${p(r)}
110
+ `);let a=s.filter((l)=>l.permissions.length>0);if(a.length>0){process.stdout.write(`
111
111
  Declared access — advisory in v1, recorded and not enforced:
112
- `);for(let l of a)for(let u of l.permissions)process.stdout.write(` ${l.name} ${u.kind} ${hr(u)}
113
- `)}let d=i.filter((l)=>!r.some((u)=>u.spec===l.name));if(d.length>0)process.stdout.write(`
112
+ `);for(let l of a)for(let u of l.permissions)process.stdout.write(` ${l.name} ${u.kind} ${vs(u)}
113
+ `)}let d=i.filter((l)=>!s.some((u)=>u.spec===l.name));if(d.length>0)process.stdout.write(`
114
114
  Also installed, named by no agent: ${d.map((l)=>l.name).join(", ")}
115
- `);return o}function Ea(e,t,r){if(t!=="installed")return t==="registry"?"built in":"imported";let i=r.find((s)=>s.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function hr(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function Ra(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${A.slug} plugins add <agent> <owner/repo> [--ref v1.0.0]\`. A plugin is fetched with git — an owner/repo shorthand, a clone URL, the page URL you were reading (whose .../tree/<branch>/<subdir> is understood), or a local repository while you are writing one.`});let r=cr(t)?{url:ka(t.replace(/^file:\/\//,""))}:ar(t),i=e.ref??r.ref,s=e.name===void 0?Zs(r.url,r.path):xa(e.name),a=Xn(e.env).find((f)=>f.name===s);if(a?.origin!==void 0&&a.origin.url!==r.url)throw new n({code:"plugin_name_taken",message:`A different plugin is already installed as "${s}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${A.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${s}"…
116
- `);let d,l=await tr({name:s,url:r.url,...i===void 0?{}:{ref:i},...r.path===void 0?{}:{path:r.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(f)=>{let m=Qs(f);if(m!==void 0)throw new n({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${m}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let g=Ys(f);if(!rr(g))throw new n({code:"plugin_entry_missing",message:`${s} has no entry file — ${g.slice(f.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let R=await Ta(s,g);if(d=await Js(R),!d.ok)throw new n({code:"plugin_not_conformant",message:`${d.declared.name} does not meet the plugin contract:
117
- ${d.findings.filter((P)=>P.level==="error").map((P)=>` ${P.check}: ${P.message}`).join(`
118
- `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${A.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(Do(q,d.declared.apiRange)!==!0)throw new n({code:"plugin_api_mismatch",message:`${d.declared.name} ${d.declared.version} supports host ${d.declared.apiRange}, and this host is ${q}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),u=d?.declared;if(process.stdout.write(`
119
- ${u?.name??s} ${u?.version??"?"} (${l.commit})
120
- from ${r.url}${i===void 0?"":` at ${i}`}
115
+ `);return o}function _a(e,t,s){if(t!=="installed")return t==="registry"?"built in":"imported";let i=s.find((r)=>r.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function vs(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function Ca(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${A.slug} plugins add <agent> <owner/repo> [--ref v1.0.0]\`. A plugin is fetched with git — an owner/repo shorthand, a clone URL, the page URL you were reading (whose .../tree/<branch>/<subdir> is understood), or a local repository while you are writing one.`});let s=gr(t)?{url:Oa(t.replace(/^file:\/\//,""))}:sr(t),i=e.ref??s.ref,r=e.name===void 0?ys(s.url,s.path):Na(e.name),a=et(e.env).find((f)=>f.name===r);if(a?.origin!==void 0&&a.origin.url!==s.url)throw new n({code:"plugin_name_taken",message:`A different plugin is already installed as "${r}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${A.slug} plugins remove <agent> ${r}\` first.`});process.stdout.write(`Fetching ${s.url}${i===void 0?"":` at ${i}`} as "${r}"…
116
+ `);let d,l=await ws({name:r,url:s.url,...i===void 0?{}:{ref:i},...s.path===void 0?{}:{path:s.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(f)=>{let m=hs(f);if(m!==void 0)throw new n({code:"plugin_not_self_contained",message:`${r} cannot be loaded as fetched: ${m}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let y=ms(f);if(!bs(y))throw new n({code:"plugin_entry_missing",message:`${r} has no entry file — ${y.slice(f.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let R=await ja(r,y);if(d=await is(R),!d.ok)throw new n({code:"plugin_not_conformant",message:`${d.declared.name} does not meet the plugin contract:
117
+ ${d.findings.filter((T)=>T.level==="error").map((T)=>` ${T.check}: ${T.message}`).join(`
118
+ `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${A.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(wo(q,d.declared.apiRange)!==!0)throw new n({code:"plugin_api_mismatch",message:`${d.declared.name} ${d.declared.version} supports host ${d.declared.apiRange}, and this host is ${q}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),u=d?.declared;if(process.stdout.write(`
119
+ ${u?.name??r} ${u?.version??"?"} (${l.commit})
120
+ from ${s.url}${i===void 0?"":` at ${i}`}
121
121
  installed ${l.dir}
122
122
  host range ${u?.apiRange??"?"} — this host is ${q}
123
123
  registers ${d===void 0||d.registered.length===0?"nothing":d.registered.join(", ")}
124
124
  `),u!==void 0&&u.permissions.length>0)process.stdout.write(`
125
125
  It declares access to:
126
- ${u.permissions.map((f)=>` ${f.kind} ${hr(f)}`).join(`
126
+ ${u.permissions.map((f)=>` ${f.kind} ${vs(f)}`).join(`
127
127
  `)}
128
128
  `+"\nAdvisory only. `permissions` is recorded and enforced by nothing in v1 (decision 7.5) —\n"+`a plugin is trusted in-process code, so this list is what the author says it needs, not a
129
129
  boundary. Install plugins you trust.
130
130
  `);else process.stdout.write(`
131
131
  It declares no access. That is not a guarantee: \`permissions\` is advisory in v1, so a
132
132
  plugin that declares nothing can still do anything this process can. Install plugins you trust.
133
- `);let p=d?.findings.filter((f)=>f.level==="warning")??[];for(let f of p)process.stdout.write(`
133
+ `);let g=d?.findings.filter((f)=>f.level==="warning")??[];for(let f of g)process.stdout.write(`
134
134
  note: ${f.check} — ${f.message}
135
- `);if(u!==void 0&&u.name!==s)process.stdout.write(`
136
- note: it calls itself "${u.name}"; the \`plugins:\` entry is the directory, "${s}".
137
- `);let c=await Ia(e.manifestPath,s);return process.stdout.write(c==="already"?`
138
- ${e.manifestPath} already names "${s}".
135
+ `);if(u!==void 0&&u.name!==r)process.stdout.write(`
136
+ note: it calls itself "${u.name}"; the \`plugins:\` entry is the directory, "${r}".
137
+ `);let c=await Fa(e.manifestPath,r);return process.stdout.write(c==="already"?`
138
+ ${e.manifestPath} already names "${r}".
139
139
  `:`
140
- Added "${s}" to the plugins: block in ${e.manifestPath}.
140
+ Added "${r}" to the plugins: block in ${e.manifestPath}.
141
141
  It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
142
- `),o}function xa(e){if(vA(e))return e;throw new n({code:"plugin_name_invalid",message:`--name ${JSON.stringify(e)} is not a usable plugin directory name`,hint:"Lowercase letters, digits and single hyphens. That segment is what the manifest's `plugins:` entry names, so it has to be a directory name and a YAML scalar at once."})}async function Ta(e,t){let r;try{r=await import(t)}catch(s){throw new n({code:"plugin_import_failed",message:`${e}: ${t} could not be imported — ${s instanceof Error?s.message:String(s)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:s})}let i=r.default;if(i===null||typeof i!=="object")throw new n({code:"plugin_malformed",message:`${e}: ${t} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${A.slug}Api\` host range and \`setup\`. A named export is not searched for and a factory function is not called, because a wrong guess produces a plugin that registers nothing and reports success.`});if(typeof i.setup!=="function")throw new n({code:"plugin_malformed",message:`${e}: the default export of ${t} has no \`setup\` function`,hint:"`setup(context)` is the whole extension surface — it registers channels, tool providers, a script runner or middleware, and does no work."});return i}async function Ia(e,t){let i=U(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===t))return"already";return await Fe({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),t]}),"written"}async function Oa(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${A.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(U(e.manifestPath).plugins??[]).map((d)=>typeof d==="string"?d:d.spec);if(i.includes(t))await Fe({file:e.manifestPath,path:["plugins"],value:i.filter((d)=>d!==t)}),process.stdout.write(`Dropped "${t}" from ${e.manifestPath}.
142
+ `),o}function Na(e){if(kA(e))return e;throw new n({code:"plugin_name_invalid",message:`--name ${JSON.stringify(e)} is not a usable plugin directory name`,hint:"Lowercase letters, digits and single hyphens. That segment is what the manifest's `plugins:` entry names, so it has to be a directory name and a YAML scalar at once."})}async function ja(e,t){let s;try{s=await import(t)}catch(r){throw new n({code:"plugin_import_failed",message:`${e}: ${t} could not be imported — ${r instanceof Error?r.message:String(r)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:r})}let i=s.default;if(i===null||typeof i!=="object")throw new n({code:"plugin_malformed",message:`${e}: ${t} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${A.slug}Api\` host range and \`setup\`. A named export is not searched for and a factory function is not called, because a wrong guess produces a plugin that registers nothing and reports success.`});if(typeof i.setup!=="function")throw new n({code:"plugin_malformed",message:`${e}: the default export of ${t} has no \`setup\` function`,hint:"`setup(context)` is the whole extension surface — it registers channels, tool providers, a script runner or middleware, and does no work."});return i}async function Fa(e,t){let i=U(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===t))return"already";return await Fe({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),t]}),"written"}async function La(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${A.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(U(e.manifestPath).plugins??[]).map((d)=>typeof d==="string"?d:d.spec);if(i.includes(t))await Fe({file:e.manifestPath,path:["plugins"],value:i.filter((d)=>d!==t)}),process.stdout.write(`Dropped "${t}" from ${e.manifestPath}.
143
143
  Run \`${A.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
144
144
  `);else process.stdout.write(`${e.manifestPath} does not name "${t}".
145
- `);let s=Or(t,e.env);if(!rr(s))return process.stdout.write(`Nothing installed at ${s}.
146
- `),o;let a=_a(t,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${s} — still named by ${a.join(", ")}.
145
+ `);let r=br(t,e.env);if(!bs(r))return process.stdout.write(`Nothing installed at ${r}.
146
+ `),o;let a=Ka(t,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${r} — still named by ${a.join(", ")}.
147
147
  Remove it from those agents first, or delete the directory by hand.
148
- `),o;return Sa(s,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${s}.
149
- `),o}function _a(e,t,r){let i=[];for(let s of oe(r)){if(s.manifestPath===t)continue;try{if((U(s.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec).includes(e))i.push(s.ref)}catch{}}return i}import{existsSync as Da,readdirSync as Rr,rmSync as et,statSync as xr}from"node:fs";import{homedir as Ha}from"node:os";import{join as Tr}from"node:path";function yr(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let t=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${t} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function $r(e){let t=[];if(e.running!==void 0)t.push({kind:"stop",detail:`stop pid ${e.running.pid} (${e.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!e.filesOnly&&e.service!==void 0)t.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(t.push({kind:"store",detail:`delete ${M(r.sessions,"conversation")}, ${M(r.messages,"message")}, ${M(r.passages,"memory passage")}`}),e.logs.length>0)t.push({kind:"logs",detail:`delete ${M(e.logs.length,"log file")}`})}return t.push({kind:"directory",detail:`delete ${e.dir}`}),t}function vr(e){let t=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${M(e.files.count,"file")}, ${rA(e.files.bytes)}`}];if(e.agentId!==e.ref)r.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)r.push({label:"keeping",value:`${M(t.sessions,"conversation")}, ${M(t.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${M(t.sessions,"conversation")}, ${M(t.messages,"message")}, ${M(t.turns,"turn")}`},{label:"memory",value:`${M(t.passages,"passage")} from ${M(t.memorySources,"source")}`},{label:"outbox",value:t.outbox===0?"nothing queued":`${M(t.outbox,"delivery")}${t.outboxPending===0?"":`, ${t.outboxPending} not yet sent`}`,...t.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:t.schedules===0?"none":M(t.schedules,"schedule"),...t.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${M(e.logs.length,"file")}, ${rA(e.logs.reduce((i,s)=>i+s.bytes,0))}`},{label:"service",value:e.service??"not installed"});return r.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),C(r)}function Sr(e){if(e.length===0)return"";return e.map((t)=>{let r=t.footprint,i=[];if(r.sessions>0)i.push(`${M(r.sessions,"conversation")}, ${M(r.messages,"message")}`);if(r.passages>0)i.push(`${M(r.passages,"memory passage")}`);if(r.outbox>0)i.push(`${M(r.outbox,"queued delivery")}`);if(r.schedules>0)i.push(`${M(r.schedules,"schedule")}`);if(r.lease)i.push("a stale lease");if(t.logs.length>0)i.push(`${M(t.logs.length,"log file")}, ${rA(t.logs.reduce((s,a)=>s+a.bytes,0))}`);return` ${t.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
150
- `)}function M(e,t){return`${e} ${t}${e===1?"":"s"}`}import{homedir as Ca}from"node:os";var kr=12000,Na=250;async function $n(e){if(e.manifestPath!==void 0)return await ja(e,e.manifestPath);return await Fa(e)}async function ja(e,t){let r=Ma(t),i=[];if(e.dryRun===!0){let l=await We(r,e.store);return process.stdout.write(`would stop 1 agent:
151
- ${w(`${r} — ${l===void 0?"not running; would be switched off for the next start":l.baseUrl===void 0?`pid ${l.pid} (${l.mode}), which serves no HTTP — would be signalled`:`pid ${l.pid} (${l.mode}) at ${l.baseUrl}, which would drop it and keep serving`}`)}
152
- `),o}await ir(r,!1,e.reason,e.store),i.push("switched off for the next start");let s=await We(r,e.store),a=!0;if(s===void 0)i.push("nothing was running");else if(s.baseUrl===void 0){let l=await bn(s.pid,"SIGTERM");a=l||await bn(s.pid,"SIGKILL",!0),i.push(l?`pid ${s.pid} stopped cleanly`:a?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let l=await Ct(s,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},t);if(l.ok)i.push(`pid ${s.pid} dropped it and kept serving`);else if(l.status===409)a=!1,i.push(l.detail??"a turn is running");else if(l.status===401)a=!1,i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${l.detail===void 0?"":`: ${l.detail}`}`)}let d={agentId:r,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[d]},null,2)}
153
- `);else process.stdout.write(`${C([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:d.note}])}
148
+ `),o;return xa(r,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${r}.
149
+ `),o}function Ka(e,t,s){let i=[];for(let r of oe(s)){if(r.manifestPath===t)continue;try{if((U(r.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec).includes(e))i.push(r.ref)}catch{}}return i}import{existsSync as Va,readdirSync as Os,rmSync as nt,statSync as _s}from"node:fs";import{homedir as Ja}from"node:os";import{join as Ns}from"node:path";function Ss(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let t=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${t} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function ks(e){let t=[];if(e.running!==void 0)t.push({kind:"stop",detail:`stop pid ${e.running.pid} (${e.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!e.filesOnly&&e.service!==void 0)t.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let s=e.footprint;if(t.push({kind:"store",detail:`delete ${K(s.sessions,"conversation")}, ${K(s.messages,"message")}, ${K(s.passages,"memory passage")}`}),e.logs.length>0)t.push({kind:"logs",detail:`delete ${K(e.logs.length,"log file")}`})}return t.push({kind:"directory",detail:`delete ${e.dir}`}),t}function Ps(e){let t=e.footprint,s=[{label:"directory",value:`${e.dir}`,note:`${K(e.files.count,"file")}, ${oA(e.files.bytes)}`}];if(e.agentId!==e.ref)s.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)s.push({label:"keeping",value:`${K(t.sessions,"conversation")}, ${K(t.passages,"memory passage")}, and the logs`,note:"--files-only"});else s.push({label:"sessions",value:`${K(t.sessions,"conversation")}, ${K(t.messages,"message")}, ${K(t.turns,"turn")}`},{label:"memory",value:`${K(t.passages,"passage")} from ${K(t.memorySources,"source")}`},{label:"outbox",value:t.outbox===0?"nothing queued":`${K(t.outbox,"delivery")}${t.outboxPending===0?"":`, ${t.outboxPending} not yet sent`}`,...t.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:t.schedules===0?"none":K(t.schedules,"schedule"),...t.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${K(e.logs.length,"file")}, ${oA(e.logs.reduce((i,r)=>i+r.bytes,0))}`},{label:"service",value:e.service??"not installed"});return s.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),p(s)}function Rs(e){if(e.length===0)return"";return e.map((t)=>{let s=t.footprint,i=[];if(s.sessions>0)i.push(`${K(s.sessions,"conversation")}, ${K(s.messages,"message")}`);if(s.passages>0)i.push(`${K(s.passages,"memory passage")}`);if(s.outbox>0)i.push(`${K(s.outbox,"queued delivery")}`);if(s.schedules>0)i.push(`${K(s.schedules,"schedule")}`);if(s.lease)i.push("a stale lease");if(t.logs.length>0)i.push(`${K(t.logs.length,"log file")}, ${oA(t.logs.reduce((r,a)=>r+a.bytes,0))}`);return` ${t.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
150
+ `)}function K(e,t){return`${e} ${t}${e===1?"":"s"}`}import{homedir as Ua}from"node:os";var Ts=12000,Ma=250;async function vn(e){if(e.manifestPath!==void 0)return await Da(e,e.manifestPath);return await Ha(e)}async function Da(e,t){let s=qa(t),i=[];if(e.dryRun===!0){let l=await We(s,e.store);return process.stdout.write(`would stop 1 agent:
151
+ ${D(`${s} — ${l===void 0?"not running; would be switched off for the next start":l.baseUrl===void 0?`pid ${l.pid} (${l.mode}), which serves no HTTP — would be signalled`:`pid ${l.pid} (${l.mode}) at ${l.baseUrl}, which would drop it and keep serving`}`)}
152
+ `),o}await rr(s,!1,e.reason,e.store),i.push("switched off for the next start");let r=await We(s,e.store),a=!0;if(r===void 0)i.push("nothing was running");else if(r.baseUrl===void 0){let l=await $n(r.pid,"SIGTERM");a=l||await $n(r.pid,"SIGKILL",!0),i.push(l?`pid ${r.pid} stopped cleanly`:a?`pid ${r.pid} had to be killed`:`pid ${r.pid} would not stop — check it by hand`)}else{let l=await ft(r,`/v1/agents/${encodeURIComponent(s)}/stop`,e.reason===void 0?{}:{reason:e.reason},t);if(l.ok)i.push(`pid ${r.pid} dropped it and kept serving`);else if(l.status===409)a=!1,i.push(l.detail??"a turn is running");else if(l.status===401)a=!1,i.push(`pid ${r.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${r.pid} at ${r.baseUrl} could not be reached${l.detail===void 0?"":`: ${l.detail}`}`)}let d={agentId:s,service:!1,...r===void 0?{}:{pid:r.pid,mode:r.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[d]},null,2)}
153
+ `);else process.stdout.write(`${p([{label:s,value:a?"stopped":"NOT FULLY STOPPED",note:d.note}])}
154
154
  `),process.stdout.write(`
155
- Stays off across restarts. \`${A.slug} start ${r}\` switches it back on.
156
- `);return a?o:E}async function Fa(e){let t=e.platform??process.platform,r=t==="darwin"?sn(t,{home:Ca(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Ka(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
155
+ Stays off across restarts. \`${A.slug} start ${s}\` switches it back on.
156
+ `);return a?o:E}async function Ha(e){let t=e.platform??process.platform,s=t==="darwin"?rn(t,{home:Ua(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Wa(s,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
157
157
  `:`Nothing is running — no service is installed and no process holds an agent.
158
158
  `),o;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
159
- ${i.map((a)=>w(La(a))).join(`
159
+ ${i.map((a)=>D(Ba(a))).join(`
160
160
  `)}
161
- `),o;let s=[];for(let a of i)s.push(await Ua(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
162
- `);else{let a=s.map((d)=>({label:Pr(d.agentId),value:d.stopped?"stopped":"STILL RUNNING",note:d.note}));if(process.stdout.write(`${C(a)}
163
- `),s.some((d)=>d.service&&d.stopped))process.stdout.write(`
161
+ `),o;let r=[];for(let a of i)r.push(await Ga(a,s));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:r},null,2)}
162
+ `);else{let a=r.map((d)=>({label:xs(d.agentId),value:d.stopped?"stopped":"STILL RUNNING",note:d.note}));if(process.stdout.write(`${p(a)}
163
+ `),r.some((d)=>d.service&&d.stopped))process.stdout.write(`
164
164
  Services are disabled as well as unloaded, so they stay stopped across a reboot.
165
165
  Start one again with \`${A.slug} daemon start <agent>\`.
166
- `);if(s.some((d)=>d.forced===!0))process.stdout.write(`
166
+ `);if(r.some((d)=>d.forced===!0))process.stdout.write(`
167
167
  Something had to be killed rather than asked. A forced stop skips the runtime's own
168
168
  cleanup, so a command the agent had left running in the background may still be alive —
169
169
  \`ps\` will show it if so.
170
- `)}return s.every((a)=>a.stopped)?o:E}async function Ka(e,t){let r=`${A.slug}.agent.`,i=new Map;for(let s of e?.labels(r)??[]){let a=s.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let s=await re.open({path:t??G()});for(let a of await s.leases.all()){if(a.pid===process.pid||!ee(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await s.close()}catch{}return[...i.values()].sort((s,a)=>s.agentId.localeCompare(a.agentId))}async function Ua(e,t){let r=[];if(e.service&&t!==void 0)try{t.stop(Ar(A.slug,e.agentId)),r.push("service disabled and unloaded")}catch(a){r.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:r.join(" · ")||"no process was running"};if(!ee(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await bn(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let s=await bn(e.pid,"SIGKILL",!0);return r.push(s?`pid ${e.pid} did not stop in ${Math.round(kr/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:s,forced:!0,note:r.join(" · ")}}async function bn(e,t,r=!1){try{process.kill(r?-e:e,t)}catch(s){if(s.code==="ESRCH")return!0;if(r)try{process.kill(e,t)}catch{return!ee(e)}}let i=Date.now()+(t==="SIGKILL"?3000:kr);while(Date.now()<i){if(!ee(e))return!0;await new Promise((s)=>setTimeout(s,Na))}return!ee(e)}function La(e){let t=[];if(e.service)t.push("background service");if(e.pid!==void 0)t.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${Pr(e.agentId)} — ${t.join(", ")}`}function Pr(e){return e===xt?"(host, no agents)":e}function Ma(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_stop_agent_id_missing",message:`${e} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${A.slug} stop\` with no argument to stop everything.`});return t.id}async function _r(e){let t=await re.open({path:e.store??G()});try{if(e.prune===!0)return await Ba(e,t);if(e.all===!0)return await Wa(e,t);if(e.ref===void 0)throw new n({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${A.slug} remove <name>\` takes a sandbox agent's name — the ones \`${A.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await Ga(e.ref,e,t)}finally{await t.close()}}async function Ga(e,t,r){let i=await Kr(e,t,r),s=yr(i);if(s.length>0){let l=s[0];throw new n({code:l.code,message:l.message,hint:l.hint})}let a=$r(i),d=`${L(`removing ${e} will:`,!0)}
171
- ${vr(i)}
170
+ `)}return r.every((a)=>a.stopped)?o:E}async function Wa(e,t){let s=`${A.slug}.agent.`,i=new Map;for(let r of e?.labels(s)??[]){let a=r.slice(s.length);i.set(a,{agentId:a,service:!0})}try{let r=await re.open({path:t??G()});for(let a of await r.leases.all()){if(a.pid===process.pid||!ee(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await r.close()}catch{}return[...i.values()].sort((r,a)=>r.agentId.localeCompare(a.agentId))}async function Ga(e,t){let s=[];if(e.service&&t!==void 0)try{t.stop(tr(A.slug,e.agentId)),s.push("service disabled and unloaded")}catch(a){s.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:s.join(" · ")||"no process was running"};if(!ee(e.pid))return{...e,stopped:!0,note:s.join(" · ")||`pid ${e.pid} exited`};if(await $n(e.pid,"SIGTERM"))return s.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:s.join(" · ")};let r=await $n(e.pid,"SIGKILL",!0);return s.push(r?`pid ${e.pid} did not stop in ${Math.round(Ts/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:r,forced:!0,note:s.join(" · ")}}async function $n(e,t,s=!1){try{process.kill(s?-e:e,t)}catch(r){if(r.code==="ESRCH")return!0;if(s)try{process.kill(e,t)}catch{return!ee(e)}}let i=Date.now()+(t==="SIGKILL"?3000:Ts);while(Date.now()<i){if(!ee(e))return!0;await new Promise((r)=>setTimeout(r,Ma))}return!ee(e)}function Ba(e){let t=[];if(e.service)t.push("background service");if(e.pid!==void 0)t.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${xs(e.agentId)} — ${t.join(", ")}`}function xs(e){return e===Ut?"(host, no agents)":e}function qa(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_stop_agent_id_missing",message:`${e} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${A.slug} stop\` with no argument to stop everything.`});return t.id}async function js(e){let t=await re.open({path:e.store??G()});try{if(e.prune===!0)return await Ya(e,t);if(e.all===!0)return await za(e,t);if(e.ref===void 0)throw new n({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${A.slug} remove <name>\` takes a sandbox agent's name — the ones \`${A.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await Xa(e.ref,e,t)}finally{await t.close()}}async function Xa(e,t,s){let i=await Ls(e,t,s),r=Ss(i);if(r.length>0){let l=r[0];throw new n({code:l.code,message:l.message,hint:l.hint})}let a=ks(i),d=`${L(`removing ${e} will:`,!0)}
171
+ ${Ps(i)}
172
172
 
173
- ${a.map((l)=>w(l.detail)).join(`
173
+ ${a.map((l)=>D(l.detail)).join(`
174
174
  `)}
175
175
  `;if(t.dryRun===!0)return process.stdout.write(t.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
176
176
  `:`${d}
177
177
  Nothing was deleted — this was --dry-run.
178
- `),o;if(process.stdout.write(d),!await nt(t,e,"type the agent's name to confirm:"))return process.stdout.write(`
178
+ `),o;if(process.stdout.write(d),!await tt(t,e,"type the agent's name to confirm:"))return process.stdout.write(`
179
179
  Nothing was deleted.
180
- `),o;return await Fr(i,t,r)}async function Fr(e,t,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await $n({manifestPath:e.manifestPath,...t.exec===void 0?{}:{exec:t.exec},...t.platform===void 0?{}:{platform:t.platform}})!==o)return process.stderr.write(`
180
+ `),o;return await Fs(i,t,s)}async function Fs(e,t,s){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await vn({manifestPath:e.manifestPath,...t.exec===void 0?{}:{exec:t.exec},...t.platform===void 0?{}:{platform:t.platform}})!==o)return process.stderr.write(`
181
181
  Stopping ${e.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
182
182
  hint: check what is still running with \`${A.slug} stop --dry-run\`, then run remove again.
183
- `),E;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=Ur(t);try{s?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let s=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let a of e.logs)et(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(et(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),t.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
183
+ `),E;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let r=Us(t);try{r?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let r=await s.purgeAgent(e.agentId);i.push({label:"store",value:`${r.sessions} conversation(s), ${r.messages} message(s), ${r.passages} passage(s)`});for(let a of e.logs)nt(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(nt(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),t.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
184
184
  `),o;if(process.stdout.write(`
185
185
  ${e.ref} removed.
186
- ${C(i)}
186
+ ${p(i)}
187
187
  `),e.filesOnly)process.stdout.write(`
188
188
  Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
189
- `);return o}async function Wa(e,t){let r=oe();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
189
+ `);return o}async function za(e,t){let s=oe();if(s.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
190
190
  `),o;if(process.stdout.write(`${L(`removing every agent in ${W()}:`,!0)}
191
- ${r.map((s)=>w(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).join(`
191
+ ${s.map((r)=>D(`${r.ref}${r.id===void 0||r.id===r.ref?"":` (id ${r.id})`}`)).join(`
192
192
  `)}
193
193
  `),e.dryRun===!0)return process.stdout.write(`
194
194
  Nothing was deleted — this was --dry-run.
195
- `),o;if(!await nt(e,"all",`type \`all\` to remove all ${r.length}:`))return process.stdout.write(`
195
+ `),o;if(!await tt(e,"all",`type \`all\` to remove all ${s.length}:`))return process.stdout.write(`
196
196
  Nothing was deleted.
197
- `),o;let i=o;for(let s of r){let a=await Kr(s.ref,e,t),d=await Fr({...a,sharesIdWith:[]},e,t);if(d!==o)i=d}return i}async function Ba(e,t){let r=new Set(oe().map((d)=>d.id??d.ref).filter((d)=>d!=="")),i=new Set((await t.agentIds()).filter((d)=>!r.has(d)));for(let d of Va())if(!r.has(d))i.add(d);let s=[];for(let d of[...i].sort())s.push({agentId:d,footprint:await t.agentFootprint(d),logs:Lr(d)});if(s.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
197
+ `),o;let i=o;for(let r of s){let a=await Ls(r.ref,e,t),d=await Fs({...a,sharesIdWith:[]},e,t);if(d!==o)i=d}return i}async function Ya(e,t){let s=new Set(oe().map((d)=>d.id??d.ref).filter((d)=>d!=="")),i=new Set((await t.agentIds()).filter((d)=>!s.has(d)));for(let d of Za())if(!s.has(d))i.add(d);let r=[];for(let d of[...i].sort())r.push({agentId:d,footprint:await t.agentFootprint(d),logs:Ms(d)});if(r.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
198
198
  `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${W()}.
199
199
  `),o;if(process.stdout.write(`${L("no sandbox directory claims these:",!0)}
200
- ${Sr(s)}
200
+ ${Rs(r)}
201
201
  `),e.dryRun===!0)return process.stdout.write(`
202
202
  Nothing was deleted — this was --dry-run.
203
- `),o;if(!await nt(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
203
+ `),o;if(!await tt(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
204
204
  Nothing was deleted.
205
- `),o;let a=[];for(let d of s){let l=await t.purgeAgent(d.agentId);for(let u of d.logs)et(u.path,{force:!0});a.push({label:d.agentId,value:`${l.sessions} conversation(s), ${l.passages} passage(s), ${d.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:s.map((d)=>d.agentId)},null,2)}
205
+ `),o;let a=[];for(let d of r){let l=await t.purgeAgent(d.agentId);for(let u of d.logs)nt(u.path,{force:!0});a.push({label:d.agentId,value:`${l.sessions} conversation(s), ${l.passages} passage(s), ${d.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:r.map((d)=>d.agentId)},null,2)}
206
206
  `:`
207
- pruned ${s.length} agent id(s).
208
- ${C(a)}
209
- `),o}async function Kr(e,t,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new n({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${W()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${A.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=oe(),s=i.find((m)=>m.ref===e);if(s===void 0){let m=i.map((g)=>g.ref);throw new n({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${m.length===0?", which is empty":""}.`,hint:m.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${m.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=s.id;if(a===void 0)try{a=U(s.manifestPath).id}catch{}let d=t.filesOnly===!0||a===void 0,l=a??e,u=await r.agentFootprint(l),p=u.lease?await r.leases.get(l):void 0,c=Ur(t),f=Ar(A.slug,l);return{ref:e,agentId:l,manifestPath:s.manifestPath,dir:s.dir,files:qa(s.dir),footprint:u,logs:Lr(l),sharesIdWith:i.filter((m)=>m.ref!==e&&(m.id??"")===l).map((m)=>m.ref),...p!==void 0&&ee(p.pid)?{running:{pid:p.pid,mode:p.mode}}:{},...c?.state(f).installed===!0?{service:f}:{},filesOnly:d}}function Ur(e){let t=e.platform??process.platform;if(t!=="darwin")return;return sn(t,{home:Ha(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function qa(e){let t=0,r=0,i=(s)=>{let a;try{a=Rr(s)}catch{return}for(let d of a){let l=Tr(s,d);try{let u=xr(l);if(u.isDirectory()){i(l);continue}t+=1,r+=u.size}catch{}}};return i(e),{count:t,bytes:r}}function Lr(e){let t=fn(e),r=[];for(let i of[t.out,t.err])try{if(!Da(i))continue;r.push({path:i,bytes:xr(i).size})}catch{}return r}function Va(){let e;try{e=Rr(Tr(Oe(),"logs"))}catch{return[]}let t=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))t.add(r.slice(0,-i.length));return[...t]}async function nt(e,t,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,t)}async function Mr(e){if(e.manifestPath===void 0)return await Ut({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let t=De(e.manifestPath),r=await MA(e.manifestPath,e.store),i,s,a=o;switch(r.kind){case"reloaded":i="reloaded",s=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",s=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",s=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=E;break;case"failed":i="not reloaded",s=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=E;break;case"no-host":{let d=await ze(e.store);if(d===void 0)throw new n({code:"cli_restart_nothing_running",message:`Nothing is hosting ${t}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${t}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${t}\` reloads it in place.`});let l=await NA(d,e.manifestPath,e.store);if(l.ok)i="started",s=`nothing was hosting it — adopted by pid ${d.pid}`;else i="not started",s=`pid ${d.pid} did not adopt it${l.detail===void 0?"":`: ${l.detail}`}`,a=E;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:t,result:r,ok:a===o},null,2)}
210
- `);else process.stdout.write(`${C([{label:t,value:i,note:s}])}
211
- `);return a}import{randomBytes as st}from"node:crypto";import{existsSync as nd}from"node:fs";import{resolve as Zr}from"node:path";import{createInterface as eo}from"node:readline";class fe extends Error{code;hint;field;details;status;request;constructor(e,t={}){super([e.message,...(e.details??[]).map((r)=>` - ${r.field===void 0?"":`${r.field}: `}${r.message}`),...e.hint===void 0?[]:[` hint: ${e.hint}`]].join(`
212
- `));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=t.status,this.request=t.method===void 0||t.path===void 0?void 0:{method:t.method,path:t.path},t.cause!==void 0)this.cause=t.cause}}function Ja(e,t){let r=e instanceof Error?e.message:String(e);return new fe({code:"transport_failed",message:`${t.method} ${t.path} did not reach ${t.baseUrl}: ${r}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...t,cause:e})}async function Xa(e,t){let r;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")r={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new fe(r??{code:`http_${e.status}`,message:`${t.method} ${t.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...t})}var Wr=new Set(qt);async function*Br(e){for await(let t of pr(za(e))){if(t.event===void 0||t.data==="")continue;let r;try{r=JSON.parse(t.data)}catch{continue}yield{name:t.event,data:r}}}async function*za(e){let t=e.getReader();try{while(!0){let{done:r,value:i}=await t.read();if(r)return;if(i!==void 0)yield i}}finally{t.releaseLock()}}async function*Ya(e){for await(let{name:t,data:r}of Br(e)){if(Wr.has(t)){yield{kind:"event",event:r};continue}let i=r??{};switch(t){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Qa(e){for await(let{name:t,data:r}of Br(e)){if(Wr.has(t)){yield{kind:"event",event:r};continue}if(t==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*Za(e,t={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&t.allowTruncated!==!0)throw new fe({code:"replay_truncated",message:`This turn's replay is missing its oldest ${r.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,hint:"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds."});if(r.kind==="unavailable")throw new fe({code:"turn_not_observable",message:`Turn ${r.turnId} is recorded as running but is not observable here: ${r.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(r.kind!=="event")continue;if(r.event.type!=="model.chunk")continue;let i=r.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function Vr(e){let t=e.baseUrl.length;while(t>0&&e.baseUrl[t-1]==="/")t-=1;let r=e.baseUrl.slice(0,t),i=e.fetch??fetch,s=(c={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...c});async function a(c,f,m={}){let g;try{g=await i(`${r}${f}`,{method:c,headers:s({...m.body===void 0?{}:{"content-type":"application/json"},...m.accept===void 0?{}:{accept:m.accept},...m.headers}),...m.body===void 0?{}:{body:JSON.stringify(m.body)},...m.signal===void 0?{}:{signal:m.signal}})}catch(R){throw Ja(R,{method:c,path:f,baseUrl:r})}if(!g.ok)throw await Xa(g,{method:c,path:f});return g}async function d(c,f,m){return await(await a(c,f,m??{})).json()}async function l(c,f){let m=await a("GET",c,{accept:"text/event-stream",...f===void 0?{}:{signal:f}});if(m.body===null)throw new fe({code:"no_response_body",message:`GET ${c} returned ${m.status} with no body to read.`,hint:"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled."},{status:m.status,method:"GET",path:c});return m.body}function u(c,f,m,g={}){let R=(y)=>{let j=new URLSearchParams;if(y?.chunks===!0)j.set("chunks","true");if(y?.children===!0)j.set("children","true");let D=j.toString();return D===""?"":`?${D}`},P={turnId:f,sessionKey:m,replayed:g.replayed===!0,async*stream(y){let j=await l(`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stream${R(y)}`,y?.signal);yield*Ya(j)},async*tokens(y){yield*Za(P.stream({chunks:!0,...y,children:!1}),{...y?.allowTruncated===void 0?{}:{allowTruncated:y.allowTruncated}})},async text(){for await(let y of P.stream()){if(y.kind==="ended")break;if(y.kind==="unavailable")break;if(y.kind==="event"&&y.event.type==="turn.end")break}return(await P.get()).text},get:()=>d("GET",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stop`)}};return P}function p(c){let f=(m)=>`/v1/agents/${encodeURIComponent(c)}${m}`;return{id:c,async send(m,g){let R=await d("POST",f("/messages"),{body:{text:m,...g?.sessionKey===void 0?{}:{sessionKey:g.sessionKey},...g?.deliver===void 0?{}:{deliver:g.deliver},...g?.from===void 0?{}:{from:g.from},...g?.images===void 0?{}:{images:g.images},...g?.runtimeNote===void 0?{}:{runtimeNote:g.runtimeNote},...g?.chunks===!0?{chunks:!0}:{},...g?.role===void 0?{}:{role:g.role}},...g?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":g.idempotencyKey}},...g?.signal===void 0?{}:{signal:g.signal}});return u(c,R.turnId,R.sessionKey,{replayed:R.replayed===!0})},turn:(m)=>u(c,m,""),describe:()=>d("GET",f("")),tools:()=>d("GET",f("/tools")),skills:()=>d("GET",f("/skills")),sessions:()=>d("GET",f("/sessions")),messages:(m,g)=>{let R=new URLSearchParams;if(g?.before!==void 0)R.set("before",String(g.before));if(g?.limit!==void 0)R.set("limit",String(g.limit));let P=R.size===0?"":`?${R.toString()}`;return d("GET",f(`/sessions/${encodeURIComponent(m)}/messages${P}`))},clearSession:(m)=>d("DELETE",f(`/sessions/${encodeURIComponent(m)}`)),reload:()=>d("POST",f("/reload"),{body:{}}),usage:(m)=>d("GET",f(`/usage${Gr(m)}`)),turns:(m)=>{let g=new URLSearchParams;if(m?.limit!==void 0)g.set("limit",String(m.limit));if(m?.before!==void 0)g.set("before",String(m.before));let R=g.size===0?"":`?${g.toString()}`;return d("GET",f(`/turns${R}`))},secrets:async()=>(await d("GET",f("/secrets"))).secrets,setSecrets:(m)=>d("PUT",f("/secrets"),{body:{values:m}}),schedules:async()=>(await d("GET",f("/schedules"))).schedules,approvals:async()=>(await d("GET",f("/approvals"))).approvals,createSchedule:(m)=>d("POST",f("/schedules"),{body:m}),updateSchedule:(m,g)=>d("PATCH",f(`/schedules/${encodeURIComponent(m)}`),{body:g}),deleteSchedule:async(m)=>{await d("DELETE",f(`/schedules/${encodeURIComponent(m)}`))},refreshTools:(m)=>d("POST",f("/tools/refresh"),{body:m?.providers===void 0?{}:{providers:m.providers}}),previewSchedule:(m)=>{let g=new URLSearchParams({kind:m.kind,expr:m.expr});if(m.timezone!==void 0)g.set("timezone",m.timezone);if(m.count!==void 0)g.set("count",String(m.count));return d("GET",f(`/schedules/preview?${g.toString()}`))},runSchedule:(m)=>d("POST",f(`/schedules/${encodeURIComponent(m)}/run`),{body:{}}),config:()=>d("GET",f("/config")),setConfig:(m,g,R)=>d("PATCH",f("/config"),{body:{path:m,value:g,...R?.confirm===void 0?{}:{confirm:R.confirm}}}),removeConfig:(m,g)=>d("PATCH",f("/config"),{body:{path:m,remove:!0,...g?.confirm===void 0?{}:{confirm:g.confirm}}}),setConfigs:(m)=>d("PATCH",f("/config"),{body:{changes:m.map((g)=>({...g}))}}),setChannel:(m,g)=>d("PATCH",f(`/channels/${encodeURIComponent(m)}`),{body:{...g}}),unpairChannel:(m)=>d("POST",f(`/channels/${encodeURIComponent(m)}/unpair`)),session:(m)=>d("GET",f(`/sessions/${encodeURIComponent(m)}`)),setPhase:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/phase`),{body:{phase:g}}),setRecall:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/recall`),{body:{recall:g}}),resolveSessionKey:async(m)=>(await d("POST",f("/sessions/resolve"),{body:{sessionKey:m}})).sessionKey,compactSession:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/compact`),{body:g?.keepTurns===void 0?{}:{keepTurns:g.keepTurns}}),rotateSession:(m)=>d("POST",f("/sessions/rotate"),{body:m?.from===void 0?{}:{from:m.from}}),approve:async(m,g)=>{await d("POST",f(`/approvals/${encodeURIComponent(m)}`),{body:{granted:g}})},stop:(m)=>d("POST",f("/stop"),{body:m===void 0?{}:{reason:m}}),start:()=>d("POST",f("/start"),{body:{}}),assign:(m)=>d("PUT",f("/assignee"),{body:{participantId:m}}),unassign:()=>d("DELETE",f("/assignee")),assignment:()=>d("GET",f("/assignee")),workspaceFiles:()=>d("GET",f("/workspace")),workspaceFile:(m)=>d("GET",f(`/workspace/${encodeURIComponent(m)}`)),putWorkspaceFile:(m,g)=>d("PUT",f(`/workspace/${encodeURIComponent(m)}`),{body:{content:g}}),exportBundle:(m)=>d("GET",f(`/export${m===void 0?"":`?paths=${encodeURIComponent(m.join(","))}`}`)),importBundle:(m,g)=>d("POST",f("/import"),{body:{bundle:m,...g===void 0?{}:{mode:g}}}),setVars:(m)=>d("PATCH",f("/vars"),{body:{vars:m}}),vars:()=>d("GET",f("/vars")),deliver:(m)=>d("POST",f("/deliveries"),{body:m}),context:(m)=>{let g=new URLSearchParams;if(m?.sessionKey!==void 0)g.set("sessionKey",m.sessionKey);if(m?.input!==void 0)g.set("input",m.input);let R=g.size===0?"":`?${g.toString()}`;return d("GET",f(`/context${R}`))}}}return{agent:p,agents:()=>d("GET","/v1/agents"),health:()=>d("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(c){if(c instanceof fe&&c.status===503)return!1;throw c}},provision:()=>d("GET","/v1/provision"),keys:()=>d("GET","/v1/keys"),createKey:(c)=>d("POST","/v1/keys",{body:c}),revokeKey:(c)=>d("DELETE",`/v1/keys/${encodeURIComponent(c)}`),deleteAgent:(c,f)=>d("DELETE",`/v1/agents/${encodeURIComponent(c)}?confirm=${encodeURIComponent(f)}`),backup:async(c)=>(await a("GET",`/v1/backup${c===void 0||c.length===0?"":`?include=${c.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(c)=>d("DELETE",`/v1/participants/${encodeURIComponent(c)}`),createAgent:(c)=>d("POST","/v1/agents",{body:{answers:c}}),usage:(c)=>d("GET",`/v1/usage${Gr(c)}`),activity:()=>d("GET","/v1/activity"),participants:async()=>(await d("GET","/v1/participants")).participants,registerParticipant:(c)=>d("POST","/v1/participants",{body:c}),conversations:async()=>(await d("GET","/v1/conversations")).conversations,createConversation:(c)=>d("POST","/v1/conversations",{body:c}),conversation:(c)=>d("GET",`/v1/conversations/${encodeURIComponent(c)}`),setMembers:(c,f)=>d("PATCH",`/v1/conversations/${encodeURIComponent(c)}/members`,{body:f}),postMessage:(c,f)=>d("POST",`/v1/conversations/${encodeURIComponent(c)}/messages`,{body:f}),conversationMessages:(c,f={})=>{let m=new URLSearchParams;if(f.after!==void 0)m.set("after",String(f.after));if(f.limit!==void 0)m.set("limit",String(f.limit));let g=m.size===0?"":`?${m}`;return d("GET",`/v1/conversations/${encodeURIComponent(c)}/messages${g}`)},setPresence:(c,f)=>d("PUT",`/v1/participants/${encodeURIComponent(c)}/presence`,{body:{presence:f}}),actions:async(c={})=>(await d("GET",`/v1/actions${c.status===void 0?"":`?status=${c.status}`}`)).actions,decideAction:(c,f)=>d("POST",`/v1/actions/${encodeURIComponent(c)}`,{body:{approve:f}}),addNote:(c)=>d("POST","/v1/memory/notes",{body:c}),notes:async(c)=>(await d("GET",`/v1/memory/notes?scope=${encodeURIComponent(c)}`)).notes,deleteNote:(c)=>d("DELETE",`/v1/memory/notes/${encodeURIComponent(c)}`),memoryReads:async(c)=>(await d("GET",`/v1/participants/${encodeURIComponent(c)}/memory/reads`)).reads,projects:async()=>(await d("GET","/v1/projects")).projects,putProject:(c,f)=>d("PUT",`/v1/projects/${encodeURIComponent(c)}`,{body:f}),deleteProject:(c)=>d("DELETE",`/v1/projects/${encodeURIComponent(c)}`),setSpaceWriter:(c)=>d("PUT","/v1/memory/space/writer",{body:{writer:c}}),webhooks:async()=>(await d("GET","/v1/webhooks")).webhooks,createWebhook:(c)=>d("POST","/v1/webhooks",{body:c}),deleteWebhook:(c)=>d("DELETE",`/v1/webhooks/${encodeURIComponent(c)}`),templates:async()=>(await d("GET","/v1/templates")).templates,createAgentFromTemplate:(c)=>d("POST","/v1/agents",{body:c}),async*events(c){let f=new URLSearchParams;if(c?.agentId!==void 0)f.set("agentId",c.agentId);if(c?.types!==void 0&&c.types.length>0)f.set("types",c.types.join(","));if(c?.chunks===!0)f.set("chunks","true");let m=f.size===0?"":`?${f.toString()}`,g=await l(`/v1/events${m}`,c?.signal);yield*Qa(g)}}}function Gr(e){let t=new URLSearchParams;if(e?.by!==void 0)t.set("by",e.by.join(","));if(e?.from!==void 0)t.set("from",e.from);if(e?.to!==void 0)t.set("to",e.to);return t.size===0?"":`?${t.toString()}`}function Te(e,t){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let s=Bi(i,t);if(s==="")continue;r.push({role:i.role,text:s})}return r}function Xr(e){let t=e.ref??"<your agent>",r=`${A.slug} run ${t} --session ${e.sessionKey}`;return`
213
- ${da}Resume this session with:
214
- ${r}${vo}
215
- `}function tt(e,t){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return t===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${t}, still in the store. /sessions goes back to it.`}}function ed(e){return e==="nlt"?fr():Cr()}function zr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(t)=>e.bus.on("*",t,{chunks:!0}),send:(t,r)=>e.send(t,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,ownConversation:e.ownConversation,resolveSessionKey:e.resolveSessionKey,rotateSession:e.rotateSession,tools:async()=>er(e.agent),context:e.context,close:async()=>{}}}function Yr(e){let t=e.client.agent(e.agentId),r=new Set,i=new AbortController,s,a=()=>{if(s!==void 0)return;s=(async()=>{for await(let d of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(d.kind!=="event"||d.event===void 0)continue;for(let l of r)l(d.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(d)=>(r.add(d),a(),()=>r.delete(d)),send:async(d,l)=>{let u=!1,p,c=()=>{if(u=!0,p!==void 0)t.turn(p).stop().catch(()=>{})};l.signal.addEventListener("abort",c,{once:!0});let f,m=new Promise((g)=>{let R=(P)=>{if(p!==void 0&&P.turnId!==void 0&&P.turnId!==p)return;if(P.type==="error"){f=P.data;return}if(P.type!=="turn.end")return;r.delete(R),g({text:"",reason:P.data.reason,steps:P.data.steps,durationMs:P.data.durationMs,tokens:P.data.tokens,...f===void 0?{}:{error:f}})};r.add(R),a()});try{if(p=(await t.send(d,{sessionKey:l.sessionKey})).turnId,u)t.turn(p).stop().catch(()=>{});return await m}finally{l.signal.removeEventListener("abort",c)}},streamFilter:()=>ed(e.description.dialect),history:async(d)=>{let l=await t.messages(d);return Te([...l.messages].reverse().map((u)=>({role:u.role,content:u.content,...u.origin===void 0?{}:{origin:u.origin}})),e.description.dialect)},sessions:()=>t.sessions(),clearSession:async(d)=>{await t.clearSession(d)},ownConversation:async()=>(await t.sessions()).find((d)=>d.head!==!1&&d.sessionKey.startsWith("owner:"))?.sessionKey,resolveSessionKey:async(d)=>{try{return await t.resolveSessionKey(d)}catch{return d}},rotateSession:async()=>{try{return(await t.rotateSession()).sessionKey}catch{return}},tools:async()=>{let d=await t.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:d.map((l)=>({slug:l.slug,mutating:l.mutating,trust:l.trust,...l.trustReason===void 0?{}:{trustReason:l.trustReason},summary:l.summary}))}},context:async(d)=>{let l=await t.context({sessionKey:d});return{...l,windowSource:"as the host resolved it",...l.lastCompaction===void 0&&l.compactions!==void 0?{lastCompaction:l.compactions===0?void 0:`${l.compactions} stage${l.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await t.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Qr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function td(e,t,r,i,s,a=[],d){let l=e.describe(),[u,p]=await Promise.all([e.turns(t,1),e.store.messages.count(e.id,t)]),c=[`${A.name} ${q} · ${l.id} · ${l.model}`,`session ${t} · ${p} message(s) · window ${l.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],f=tt(s,d);if(f!==void 0)c.push(f);if(u[0]?.errorCode==="turn_abandoned")c.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let m of[...e.warnings,...e.tools.warnings])c.push(`note: ${m.message}
207
+ pruned ${r.length} agent id(s).
208
+ ${p(a)}
209
+ `),o}async function Ls(e,t,s){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new n({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${W()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${A.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=oe(),r=i.find((m)=>m.ref===e);if(r===void 0){let m=i.map((y)=>y.ref);throw new n({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${m.length===0?", which is empty":""}.`,hint:m.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${m.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=r.id;if(a===void 0)try{a=U(r.manifestPath).id}catch{}let d=t.filesOnly===!0||a===void 0,l=a??e,u=await s.agentFootprint(l),g=u.lease?await s.leases.get(l):void 0,c=Us(t),f=tr(A.slug,l);return{ref:e,agentId:l,manifestPath:r.manifestPath,dir:r.dir,files:Qa(r.dir),footprint:u,logs:Ms(l),sharesIdWith:i.filter((m)=>m.ref!==e&&(m.id??"")===l).map((m)=>m.ref),...g!==void 0&&ee(g.pid)?{running:{pid:g.pid,mode:g.mode}}:{},...c?.state(f).installed===!0?{service:f}:{},filesOnly:d}}function Us(e){let t=e.platform??process.platform;if(t!=="darwin")return;return rn(t,{home:Ja(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Qa(e){let t=0,s=0,i=(r)=>{let a;try{a=Os(r)}catch{return}for(let d of a){let l=Ns(r,d);try{let u=_s(l);if(u.isDirectory()){i(l);continue}t+=1,s+=u.size}catch{}}};return i(e),{count:t,bytes:s}}function Ms(e){let t=pn(e),s=[];for(let i of[t.out,t.err])try{if(!Va(i))continue;s.push({path:i,bytes:_s(i).size})}catch{}return s}function Za(){let e;try{e=Os(Ns(Oe(),"logs"))}catch{return[]}let t=new Set;for(let s of e)for(let i of[".out.log",".err.log"])if(s.endsWith(i))t.add(s.slice(0,-i.length));return[...t]}async function tt(e,t,s){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(s,t)}async function Ds(e){if(e.manifestPath===void 0)return await Ft({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let t=De(e.manifestPath),s=await NA(e.manifestPath,e.store),i,r,a=o;switch(s.kind){case"reloaded":i="reloaded",r=`pid ${s.pid} rebuilt it from disk${s.adopted.length>0?` · adopted ${s.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",r=`pid ${s.pid} applies it when its ${s.running} running turn(s) finish`;break;case"busy":i="not reloaded",r=`pid ${s.pid} has a turn in flight — try again when it finishes`,a=E;break;case"failed":i="not reloaded",r=`pid ${s.pid} answered ${s.status}${s.detail===void 0?"":`: ${s.detail}`}${s.hint===void 0?"":` — ${s.hint}`}`,a=E;break;case"no-host":{let d=await ze(e.store);if(d===void 0)throw new n({code:"cli_restart_nothing_running",message:`Nothing is hosting ${t}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${t}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${t}\` reloads it in place.`});let l=await OA(d,e.manifestPath,e.store);if(l.ok)i="started",r=`nothing was hosting it — adopted by pid ${d.pid}`;else i="not started",r=`pid ${d.pid} did not adopt it${l.detail===void 0?"":`: ${l.detail}`}`,a=E;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:t,result:s,ok:a===o},null,2)}
210
+ `);else process.stdout.write(`${p([{label:t,value:i,note:r}])}
211
+ `);return a}import{randomBytes as ot}from"node:crypto";import{existsSync as ad}from"node:fs";import{resolve as Zs}from"node:path";import{createInterface as no}from"node:readline";class me extends Error{code;hint;field;details;status;request;constructor(e,t={}){super([e.message,...(e.details??[]).map((s)=>` - ${s.field===void 0?"":`${s.field}: `}${s.message}`),...e.hint===void 0?[]:[` hint: ${e.hint}`]].join(`
212
+ `));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=t.status,this.request=t.method===void 0||t.path===void 0?void 0:{method:t.method,path:t.path},t.cause!==void 0)this.cause=t.cause}}function ed(e,t){let s=e instanceof Error?e.message:String(e);return new me({code:"transport_failed",message:`${t.method} ${t.path} did not reach ${t.baseUrl}: ${s}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...t,cause:e})}async function nd(e,t){let s;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")s={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new me(s??{code:`http_${e.status}`,message:`${t.method} ${t.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...t})}var Gs=new Set(Jt);async function*Bs(e){for await(let t of Er(td(e))){if(t.event===void 0||t.data==="")continue;let s;try{s=JSON.parse(t.data)}catch{continue}yield{name:t.event,data:s}}}async function*td(e){let t=e.getReader();try{while(!0){let{done:s,value:i}=await t.read();if(s)return;if(i!==void 0)yield i}}finally{t.releaseLock()}}async function*rd(e){for await(let{name:t,data:s}of Bs(e)){if(Gs.has(t)){yield{kind:"event",event:s};continue}let i=s??{};switch(t){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*sd(e){for await(let{name:t,data:s}of Bs(e)){if(Gs.has(t)){yield{kind:"event",event:s};continue}if(t==="stream.subscribed"){let i=s??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*od(e,t={}){for await(let s of e){if(s.kind==="replay"&&s.report.truncated&&t.allowTruncated!==!0)throw new me({code:"replay_truncated",message:`This turn's replay is missing its oldest ${s.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,hint:"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds."});if(s.kind==="unavailable")throw new me({code:"turn_not_observable",message:`Turn ${s.turnId} is recorded as running but is not observable here: ${s.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(s.kind!=="event")continue;if(s.event.type!=="model.chunk")continue;let i=s.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function qs(e){let t=e.baseUrl.length;while(t>0&&e.baseUrl[t-1]==="/")t-=1;let s=e.baseUrl.slice(0,t),i=e.fetch??fetch,r=(c={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...c});async function a(c,f,m={}){let y;try{y=await i(`${s}${f}`,{method:c,headers:r({...m.body===void 0?{}:{"content-type":"application/json"},...m.accept===void 0?{}:{accept:m.accept},...m.headers}),...m.body===void 0?{}:{body:JSON.stringify(m.body)},...m.signal===void 0?{}:{signal:m.signal}})}catch(R){throw ed(R,{method:c,path:f,baseUrl:s})}if(!y.ok)throw await nd(y,{method:c,path:f});return y}async function d(c,f,m){return await(await a(c,f,m??{})).json()}async function l(c,f){let m=await a("GET",c,{accept:"text/event-stream",...f===void 0?{}:{signal:f}});if(m.body===null)throw new me({code:"no_response_body",message:`GET ${c} returned ${m.status} with no body to read.`,hint:"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled."},{status:m.status,method:"GET",path:c});return m.body}function u(c,f,m,y={}){let R=(b)=>{let N=new URLSearchParams;if(b?.chunks===!0)N.set("chunks","true");if(b?.children===!0)N.set("children","true");let M=N.toString();return M===""?"":`?${M}`},T={turnId:f,sessionKey:m,replayed:y.replayed===!0,async*stream(b){let N=await l(`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stream${R(b)}`,b?.signal);yield*rd(N)},async*tokens(b){yield*od(T.stream({chunks:!0,...b,children:!1}),{...b?.allowTruncated===void 0?{}:{allowTruncated:b.allowTruncated}})},async text(){for await(let b of T.stream()){if(b.kind==="ended")break;if(b.kind==="unavailable")break;if(b.kind==="event"&&b.event.type==="turn.end")break}return(await T.get()).text},get:()=>d("GET",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stop`)}};return T}function g(c){let f=(m)=>`/v1/agents/${encodeURIComponent(c)}${m}`;return{id:c,async send(m,y){let R=await d("POST",f("/messages"),{body:{text:m,...y?.sessionKey===void 0?{}:{sessionKey:y.sessionKey},...y?.deliver===void 0?{}:{deliver:y.deliver},...y?.from===void 0?{}:{from:y.from},...y?.images===void 0?{}:{images:y.images},...y?.runtimeNote===void 0?{}:{runtimeNote:y.runtimeNote},...y?.chunks===!0?{chunks:!0}:{},...y?.role===void 0?{}:{role:y.role}},...y?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":y.idempotencyKey}},...y?.signal===void 0?{}:{signal:y.signal}});return u(c,R.turnId,R.sessionKey,{replayed:R.replayed===!0})},turn:(m)=>u(c,m,""),describe:()=>d("GET",f("")),tools:()=>d("GET",f("/tools")),skills:()=>d("GET",f("/skills")),sessions:()=>d("GET",f("/sessions")),messages:(m,y)=>{let R=new URLSearchParams;if(y?.before!==void 0)R.set("before",String(y.before));if(y?.limit!==void 0)R.set("limit",String(y.limit));let T=R.size===0?"":`?${R.toString()}`;return d("GET",f(`/sessions/${encodeURIComponent(m)}/messages${T}`))},clearSession:(m)=>d("DELETE",f(`/sessions/${encodeURIComponent(m)}`)),reload:()=>d("POST",f("/reload"),{body:{}}),usage:(m)=>d("GET",f(`/usage${Ws(m)}`)),turns:(m)=>{let y=new URLSearchParams;if(m?.limit!==void 0)y.set("limit",String(m.limit));if(m?.before!==void 0)y.set("before",String(m.before));let R=y.size===0?"":`?${y.toString()}`;return d("GET",f(`/turns${R}`))},secrets:async()=>(await d("GET",f("/secrets"))).secrets,setSecrets:(m)=>d("PUT",f("/secrets"),{body:{values:m}}),schedules:async()=>(await d("GET",f("/schedules"))).schedules,approvals:async()=>(await d("GET",f("/approvals"))).approvals,createSchedule:(m)=>d("POST",f("/schedules"),{body:m}),updateSchedule:(m,y)=>d("PATCH",f(`/schedules/${encodeURIComponent(m)}`),{body:y}),deleteSchedule:async(m)=>{await d("DELETE",f(`/schedules/${encodeURIComponent(m)}`))},refreshTools:(m)=>d("POST",f("/tools/refresh"),{body:m?.providers===void 0?{}:{providers:m.providers}}),previewSchedule:(m)=>{let y=new URLSearchParams({kind:m.kind,expr:m.expr});if(m.timezone!==void 0)y.set("timezone",m.timezone);if(m.count!==void 0)y.set("count",String(m.count));return d("GET",f(`/schedules/preview?${y.toString()}`))},runSchedule:(m)=>d("POST",f(`/schedules/${encodeURIComponent(m)}/run`),{body:{}}),config:()=>d("GET",f("/config")),setConfig:(m,y,R)=>d("PATCH",f("/config"),{body:{path:m,value:y,...R?.confirm===void 0?{}:{confirm:R.confirm}}}),removeConfig:(m,y)=>d("PATCH",f("/config"),{body:{path:m,remove:!0,...y?.confirm===void 0?{}:{confirm:y.confirm}}}),setConfigs:(m)=>d("PATCH",f("/config"),{body:{changes:m.map((y)=>({...y}))}}),setChannel:(m,y)=>d("PATCH",f(`/channels/${encodeURIComponent(m)}`),{body:{...y}}),unpairChannel:(m)=>d("POST",f(`/channels/${encodeURIComponent(m)}/unpair`)),session:(m)=>d("GET",f(`/sessions/${encodeURIComponent(m)}`)),setPhase:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/phase`),{body:{phase:y}}),setRecall:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/recall`),{body:{recall:y}}),resolveSessionKey:async(m)=>(await d("POST",f("/sessions/resolve"),{body:{sessionKey:m}})).sessionKey,compactSession:(m,y)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/compact`),{body:y?.keepTurns===void 0?{}:{keepTurns:y.keepTurns}}),rotateSession:(m)=>d("POST",f("/sessions/rotate"),{body:m?.from===void 0?{}:{from:m.from}}),approve:async(m,y)=>{await d("POST",f(`/approvals/${encodeURIComponent(m)}`),{body:{granted:y}})},stop:(m)=>d("POST",f("/stop"),{body:m===void 0?{}:{reason:m}}),start:()=>d("POST",f("/start"),{body:{}}),assign:(m)=>d("PUT",f("/assignee"),{body:{participantId:m}}),unassign:()=>d("DELETE",f("/assignee")),assignment:()=>d("GET",f("/assignee")),workspaceFiles:()=>d("GET",f("/workspace")),workspaceFile:(m)=>d("GET",f(`/workspace/${encodeURIComponent(m)}`)),putWorkspaceFile:(m,y)=>d("PUT",f(`/workspace/${encodeURIComponent(m)}`),{body:{content:y}}),exportBundle:(m)=>d("GET",f(`/export${m===void 0?"":`?paths=${encodeURIComponent(m.join(","))}`}`)),importBundle:(m,y)=>d("POST",f("/import"),{body:{bundle:m,...y===void 0?{}:{mode:y}}}),setVars:(m)=>d("PATCH",f("/vars"),{body:{vars:m}}),vars:()=>d("GET",f("/vars")),deliver:(m)=>d("POST",f("/deliveries"),{body:m}),context:(m)=>{let y=new URLSearchParams;if(m?.sessionKey!==void 0)y.set("sessionKey",m.sessionKey);if(m?.input!==void 0)y.set("input",m.input);let R=y.size===0?"":`?${y.toString()}`;return d("GET",f(`/context${R}`))}}}return{agent:g,agents:()=>d("GET","/v1/agents"),health:()=>d("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(c){if(c instanceof me&&c.status===503)return!1;throw c}},provision:()=>d("GET","/v1/provision"),keys:()=>d("GET","/v1/keys"),createKey:(c)=>d("POST","/v1/keys",{body:c}),revokeKey:(c)=>d("DELETE",`/v1/keys/${encodeURIComponent(c)}`),deleteAgent:(c,f)=>d("DELETE",`/v1/agents/${encodeURIComponent(c)}?confirm=${encodeURIComponent(f)}`),backup:async(c)=>(await a("GET",`/v1/backup${c===void 0||c.length===0?"":`?include=${c.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(c)=>d("DELETE",`/v1/participants/${encodeURIComponent(c)}`),createAgent:(c)=>d("POST","/v1/agents",{body:{answers:c}}),usage:(c)=>d("GET",`/v1/usage${Ws(c)}`),activity:()=>d("GET","/v1/activity"),participants:async()=>(await d("GET","/v1/participants")).participants,registerParticipant:(c)=>d("POST","/v1/participants",{body:c}),conversations:async()=>(await d("GET","/v1/conversations")).conversations,createConversation:(c)=>d("POST","/v1/conversations",{body:c}),conversation:(c)=>d("GET",`/v1/conversations/${encodeURIComponent(c)}`),setMembers:(c,f)=>d("PATCH",`/v1/conversations/${encodeURIComponent(c)}/members`,{body:f}),postMessage:(c,f)=>d("POST",`/v1/conversations/${encodeURIComponent(c)}/messages`,{body:f}),conversationMessages:(c,f={})=>{let m=new URLSearchParams;if(f.after!==void 0)m.set("after",String(f.after));if(f.limit!==void 0)m.set("limit",String(f.limit));let y=m.size===0?"":`?${m}`;return d("GET",`/v1/conversations/${encodeURIComponent(c)}/messages${y}`)},setPresence:(c,f)=>d("PUT",`/v1/participants/${encodeURIComponent(c)}/presence`,{body:{presence:f}}),actions:async(c={})=>(await d("GET",`/v1/actions${c.status===void 0?"":`?status=${c.status}`}`)).actions,decideAction:(c,f)=>d("POST",`/v1/actions/${encodeURIComponent(c)}`,{body:{approve:f}}),addNote:(c)=>d("POST","/v1/memory/notes",{body:c}),notes:async(c)=>(await d("GET",`/v1/memory/notes?scope=${encodeURIComponent(c)}`)).notes,deleteNote:(c)=>d("DELETE",`/v1/memory/notes/${encodeURIComponent(c)}`),memoryReads:async(c)=>(await d("GET",`/v1/participants/${encodeURIComponent(c)}/memory/reads`)).reads,projects:async()=>(await d("GET","/v1/projects")).projects,putProject:(c,f)=>d("PUT",`/v1/projects/${encodeURIComponent(c)}`,{body:f}),deleteProject:(c)=>d("DELETE",`/v1/projects/${encodeURIComponent(c)}`),setSpaceWriter:(c)=>d("PUT","/v1/memory/space/writer",{body:{writer:c}}),webhooks:async()=>(await d("GET","/v1/webhooks")).webhooks,createWebhook:(c)=>d("POST","/v1/webhooks",{body:c}),deleteWebhook:(c)=>d("DELETE",`/v1/webhooks/${encodeURIComponent(c)}`),templates:async()=>(await d("GET","/v1/templates")).templates,createAgentFromTemplate:(c)=>d("POST","/v1/agents",{body:c}),async*events(c){let f=new URLSearchParams;if(c?.agentId!==void 0)f.set("agentId",c.agentId);if(c?.types!==void 0&&c.types.length>0)f.set("types",c.types.join(","));if(c?.chunks===!0)f.set("chunks","true");let m=f.size===0?"":`?${f.toString()}`,y=await l(`/v1/events${m}`,c?.signal);yield*sd(y)}}}function Ws(e){let t=new URLSearchParams;if(e?.by!==void 0)t.set("by",e.by.join(","));if(e?.from!==void 0)t.set("from",e.from);if(e?.to!==void 0)t.set("to",e.to);return t.size===0?"":`?${t.toString()}`}function _e(e,t){let s=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let r=Ci(i,t);if(r==="")continue;s.push({role:i.role,text:r})}return s}function Vs(e){let t=e.ref??"<your agent>",s=`${A.slug} run ${t} --session ${e.sessionKey}`;return`
213
+ ${Ia}Resume this session with:
214
+ ${s}${ko}
215
+ `}function rt(e,t){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return t===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${t}, still in the store. /sessions goes back to it.`}}function id(e){return e==="nlt"?pr():fr()}function zs(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(t)=>e.bus.on("*",t,{chunks:!0}),send:(t,s)=>e.send(t,{...s,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,ownConversation:e.ownConversation,resolveSessionKey:e.resolveSessionKey,rotateSession:e.rotateSession,tools:async()=>Xo(e.agent),context:e.context,close:async()=>{}}}function Ys(e){let t=e.client.agent(e.agentId),s=new Set,i=new AbortController,r,a=()=>{if(r!==void 0)return;r=(async()=>{for await(let d of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(d.kind!=="event"||d.event===void 0)continue;for(let l of s)l(d.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(d)=>(s.add(d),a(),()=>s.delete(d)),send:async(d,l)=>{let u=!1,g,c=()=>{if(u=!0,g!==void 0)t.turn(g).stop().catch(()=>{})};l.signal.addEventListener("abort",c,{once:!0});let f,m=new Promise((y)=>{let R=(T)=>{if(g!==void 0&&T.turnId!==void 0&&T.turnId!==g)return;if(T.type==="error"){f=T.data;return}if(T.type!=="turn.end")return;s.delete(R),y({text:"",reason:T.data.reason,steps:T.data.steps,durationMs:T.data.durationMs,tokens:T.data.tokens,...f===void 0?{}:{error:f}})};s.add(R),a()});try{if(g=(await t.send(d,{sessionKey:l.sessionKey})).turnId,u)t.turn(g).stop().catch(()=>{});return await m}finally{l.signal.removeEventListener("abort",c)}},streamFilter:()=>id(e.description.dialect),history:async(d)=>{let l=await t.messages(d);return _e([...l.messages].reverse().map((u)=>({role:u.role,content:u.content,...u.origin===void 0?{}:{origin:u.origin}})),e.description.dialect)},sessions:()=>t.sessions(),clearSession:async(d)=>{await t.clearSession(d)},ownConversation:async()=>(await t.sessions()).find((d)=>d.head!==!1&&d.sessionKey.startsWith("owner:"))?.sessionKey,resolveSessionKey:async(d)=>{try{return await t.resolveSessionKey(d)}catch{return d}},rotateSession:async()=>{try{return(await t.rotateSession()).sessionKey}catch{return}},tools:async()=>{let d=await t.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:d.map((l)=>({slug:l.slug,mutating:l.mutating,trust:l.trust,...l.trustReason===void 0?{}:{trustReason:l.trustReason},summary:l.summary}))}},context:async(d)=>{let l=await t.context({sessionKey:d});return{...l,windowSource:"as the host resolved it",...l.lastCompaction===void 0&&l.compactions!==void 0?{lastCompaction:l.compactions===0?void 0:`${l.compactions} stage${l.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await t.reload()).adopted,close:async()=>{i.abort(),s.clear()}}}function Qs(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function dd(e,t,s,i,r,a=[],d){let l=e.describe(),[u,g]=await Promise.all([e.turns(t,1),e.store.messages.count(e.id,t)]),c=[`${A.name} ${q} · ${l.id} · ${l.model}`,`session ${t} · ${g} message(s) · window ${l.window} · store ${s}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],f=rt(r,d);if(f!==void 0)c.push(f);if(u[0]?.errorCode==="turn_abandoned")c.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let m of[...e.warnings,...e.tools.warnings])c.push(`note: ${m.message}
216
216
  ${m.hint}`);if(a.length>0)c.push(`note: ${a.join(", ")} in the .env here ${a.length===1?"was":"were"} ignored — this agent's own .env sets ${a.length===1?"it":"them"}.
217
- A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return c}async function rt(e){let t=e.once!==void 0,r=gt({json:!1,plain:e.plain===!0,oneShot:t}),{mode:i}=r;if(e.manifestPath===void 0){let P=await rd(i,r.because,e);if(typeof P==="number")return P;return rt({...e,manifestPath:P})}let s=fi();if(e.store===void 0&&e.ephemeral!==!0&&Zr(s)!==Zr(G())&&nd(s))process.stdout.write(`note: a session store exists at ${s} from an earlier version — pass --store ${s} to keep using it; the default is now ${G()}
218
- `);let a;H(()=>a?.stop("cli-exit"));let d={current:void 0},l={current:""},u={current:e.sessionKey},p={current:!1},c={current:void 0},f=e.quiet===!0,m="first",g={current:void 0},R=e.ephemeral===!0?void 0:Qr(await We(De(e.manifestPath),e.store));if(R!==void 0)return await dd({...e,host:R,mode:i==="rich"?"rich":"plain",quiet:f,oneShot:t,reader:d,draft:l,session:u,random:st});for(;;){let P=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=P;let y=P.list()[0];if(y===void 0)throw Error("The manifest produced no agent.");if(u.current===void 0||u.current===""){let N=await so({list:async()=>lo(await y.store.sessions.list(y.id)),mode:i,asked:u.current,wantsContinue:e.continueSession===!0,random:st});if(typeof N==="number")return await P.stop("cli-exit"),N;if(u.current=N.sessionKey,p.current=N.fresh,N.fresh)u.current=await no(y)??N.sessionKey}if(m==="new"){let N=await y.rotateSession({source:"repl"});if(N!==void 0)u.current=N.sessionKey}u.current=await y.resolveSessionKey(u.current??"",{source:"repl"});let j=u.current,D=y.roles.main.capabilities.thinking!=="none",b=e.noReasoning===!0?!1:D,x=f||t?[]:await td(y,j,P.store.location,m==="first"?P.boot.processMs:P.boot.bootMs,m,qs([e.manifestPath]),c.current),I=i==="rich"&&!f&&!t?Te(await y.history(j),y.describe().dialect):[],_=zr({agent:y,bus:P.bus,send:(N,Z)=>y.send(N,Z),history:async(N)=>Te(await y.history(N),y.describe().dialect),sessions:async()=>{let N=await y.store.sessions.heads(y.id);return(await y.store.sessions.list(y.id)).map((Z)=>({...Z,head:si(Z.sessionKey,N)}))},clearSession:async(N)=>{await y.clearSession(N)},ownConversation:()=>no(y),resolveSessionKey:(N)=>y.resolveSessionKey(N,{source:"repl"}),rotateSession:async()=>(await y.rotateSession({source:"repl"}))?.sessionKey,context:async(N)=>ld(y,N),streamFilter:()=>y.streamFilter(),description:{agentId:y.id,name:y.describe().name,model:y.describe().model,dialect:y.describe().dialect,window:y.describe().window,catalogueTokens:y.describe().catalogueTokens,thinking:y.roles.main.capabilities.thinking,warnings:[...y.warnings,...y.tools.warnings]}}),F={...e,source:_,embedded:{agent:y,runtime:P},sessionKey:j,banner:x,prior:I,quiet:f,reader:d,draft:l,showReasoning:b,freshSession:p.current,switchTo:g,random:st},V=i==="rich"?await oo(F):await io(F);if(await P.stop(V===me?"restart":"cli-exit"),V!==me)return V;if(g.current===void 0)m="restart";else m=g.current.reason,c.current=j,u.current=g.current.key,g.current=void 0;p.current=!1}}function sd(e,t){let r=[];for(let i of e)Yt({action:"install",manifestPath:t,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var me=Symbol("restart");async function rd(e,t,r){let i=oe();if(i.length===0){if(e==="rich"){let c=await Un({plain:r.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
217
+ A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return c}async function it(e){let t=e.once!==void 0,s=at({json:!1,plain:e.plain===!0,oneShot:t}),{mode:i}=s;if(e.manifestPath===void 0){let T=await cd(i,s.because,e);if(typeof T==="number")return T;return it({...e,manifestPath:T})}let r=fi();if(e.store===void 0&&e.ephemeral!==!0&&Zs(r)!==Zs(G())&&ad(r))process.stdout.write(`note: a session store exists at ${r} from an earlier version — pass --store ${r} to keep using it; the default is now ${G()}
218
+ `);let a;H(()=>a?.stop("cli-exit"));let d={current:void 0},l={current:""},u={current:e.sessionKey},g={current:!1},c={current:void 0},f=e.quiet===!0,m="first",y={current:void 0},R=e.ephemeral===!0?void 0:Qs(await We(De(e.manifestPath),e.store));if(R!==void 0)return await pd({...e,host:R,mode:i==="rich"?"rich":"plain",quiet:f,oneShot:t,reader:d,draft:l,session:u,random:ot});for(;;){let T=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=T;let b=T.list()[0];if(b===void 0)throw Error("The manifest produced no agent.");if(u.current===void 0||u.current===""){let C=await so({list:async()=>co(await b.store.sessions.list(b.id)),mode:i,asked:u.current,wantsContinue:e.continueSession===!0,random:ot});if(typeof C==="number")return await T.stop("cli-exit"),C;if(u.current=C.sessionKey,g.current=C.fresh,C.fresh)u.current=await ro(b)??C.sessionKey}if(m==="new"){let C=await b.rotateSession({source:"repl"});if(C!==void 0)u.current=C.sessionKey}u.current=await b.resolveSessionKey(u.current??"",{source:"repl"});let N=u.current,M=b.roles.main.capabilities.thinking!=="none",S=e.noReasoning===!0?!1:M,P=f||t?[]:await dd(b,N,T.store.location,m==="first"?T.boot.processMs:T.boot.bootMs,m,Js([e.manifestPath]),c.current),I=i==="rich"&&!f&&!t?_e(await b.history(N),b.describe().dialect):[],O=zs({agent:b,bus:T.bus,send:(C,ne)=>b.send(C,ne),history:async(C)=>_e(await b.history(C),b.describe().dialect),sessions:async()=>{let C=await b.store.sessions.heads(b.id);return(await b.store.sessions.list(b.id)).map((ne)=>({...ne,head:si(ne.sessionKey,C)}))},clearSession:async(C)=>{await b.clearSession(C)},ownConversation:()=>ro(b),resolveSessionKey:(C)=>b.resolveSessionKey(C,{source:"repl"}),rotateSession:async()=>(await b.rotateSession({source:"repl"}))?.sessionKey,context:async(C)=>hd(b,C),streamFilter:()=>b.streamFilter(),description:{agentId:b.id,name:b.describe().name,model:b.describe().model,dialect:b.describe().dialect,window:b.describe().window,catalogueTokens:b.describe().catalogueTokens,thinking:b.roles.main.capabilities.thinking,warnings:[...b.warnings,...b.tools.warnings]}}),j={...e,source:O,embedded:{agent:b,runtime:T},sessionKey:N,banner:P,prior:I,quiet:f,reader:d,draft:l,showReasoning:S,freshSession:g.current,switchTo:y,random:ot},V=i==="rich"?await io(j):await ao(j);if(await T.stop(V===he?"restart":"cli-exit"),V!==he)return V;if(y.current===void 0)m="restart";else m=y.current.reason,c.current=N,u.current=y.current.key,y.current=void 0;g.current=!1}}function ld(e,t){let s=[];for(let i of e)Kt({action:"install",manifestPath:t,name:`${i.source}/${i.skill}`,quiet:!0,collect:s});return s}var he=Symbol("restart");async function cd(e,t,s){let i=oe();if(i.length===0){if(e==="rich"){let c=await Mn({plain:s.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
219
219
  `),o;if(c.kind==="failed")return c.code;return c.manifestPath}throw new n({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${A.slug} init\`, or pass a path to an agent.yaml.`})}if(i.length===1&&i[0]!==void 0)return process.stdout.write(`running ${i[0].ref} — the only agent in the sandbox
220
220
  `),i[0].manifestPath;if(e!=="rich"){for(let c of i)process.stdout.write(`${c.ref} ${c.problem??c.modelId??"?"} ${c.dir}
221
221
  `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${t})
222
- `),E}let[{render:s},{createElement:a},{Picker:d}]=await Promise.all([import("ink"),import("react"),import("./Picker-32m79nmp.js")]),l={kind:"quit"};ro();let u=s(a(d,{title:`${A.name} ${q}`,agents:i,onDone:(c)=>{l=c}}),{exitOnCtrlC:!1,...Ke(r.noEnhancedKeys)});H(()=>u.unmount()),await u.waitUntilExit(),u.unmount();let p=l;if(p.kind==="quit")return process.stdout.write(`nothing run
223
- `),o;if(p.kind==="create"){let c=await Un({plain:r.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
224
- `),o;if(c.kind==="failed")return c.code;return c.manifestPath}return p.manifestPath}async function no(e){let r=await e.resolveSessionKey("local:-",{source:"repl"});return r==="local:-"?void 0:r}async function so(e){let t=()=>({sessionKey:Xo(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new n({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let r=await e.list(),i=od(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
225
- `),t();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let r=await e.list();if(r.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
226
- `),t();if(e.mode!=="rich"){for(let s of[...r].sort(vn))process.stdout.write(`${s.sessionKey} ${s.messages} ${s.turns} ${s.lastActivityAt}
222
+ `),E}let[{render:r},{createElement:a},{Picker:d}]=await Promise.all([import("ink"),import("react"),import("./Picker-x6aj42tc.js")]),l={kind:"quit"};oo();let u=r(a(d,{title:`${A.name} ${q}`,agents:i,onDone:(c)=>{l=c}}),{exitOnCtrlC:!1,...Ke(s.noEnhancedKeys)});H(()=>u.unmount()),await u.waitUntilExit(),u.unmount();let g=l;if(g.kind==="quit")return process.stdout.write(`nothing run
223
+ `),o;if(g.kind==="create"){let c=await Mn({plain:s.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
224
+ `),o;if(c.kind==="failed")return c.code;return c.manifestPath}return g.manifestPath}async function ro(e){let s=await e.resolveSessionKey("local:-",{source:"repl"});return s==="local:-"?void 0:s}async function so(e){let t=()=>({sessionKey:$o(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new n({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let s=await e.list(),i=ud(s);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
225
+ `),t();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let s=await e.list();if(s.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
226
+ `),t();if(e.mode!=="rich"){for(let r of[...s].sort(kn))process.stdout.write(`${r.sessionKey} ${r.messages} ${r.turns} ${r.lastActivityAt}
227
227
  `);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
228
- `),E}let i=await id([...r].sort(vn));return i===void 0?t():{sessionKey:i,fresh:!1}}return e.asked===void 0?t():{sessionKey:e.asked,fresh:!1}}function vn(e,t){return Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)}function od(e){return[...e].sort(vn)[0]}async function id(e){let[{render:t},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-9p06npt5.js")]),s;ro();let a=t(r(i,{sessions:e,now:Date.now(),columns:Ue(process.stdout.columns,Me),maxRows:wn,onDone:(d)=>{s=d,a.unmount()}}),{exitOnCtrlC:!1,...Ke()});return H(()=>a.unmount()),await a.waitUntilExit(),s}function ad(e,t,r,i,s){let a=e.describe(),d=[`${A.name} ${q} · ${a.agentId} · ${a.model}`,`session ${t} · window ${a.window} · attached to ${r.baseUrl} (pid ${r.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],l=tt(i,s);if(l!==void 0)d.push(l);for(let u of a.warnings)d.push(`warning: ${u.message}`);return d}async function dd(e){let t=e.manifestPath??"",r=De(t),i=_A(t),s=Vr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await s.agent(r).describe();if(a.status==="disabled")throw new n({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${r}\`, then run again.`});let d=Yr({client:s,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),l={current:void 0},u="first",p={current:void 0},c={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let y=await so({list:()=>co(d),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof y==="number")return y;if(e.session.current=y.sessionKey,c.current=y.fresh,y.fresh)e.session.current=await d.ownConversation()??y.sessionKey}if(u==="new"){let y=await d.rotateSession();if(y!==void 0)e.session.current=y}e.session.current=await d.resolveSessionKey(e.session.current??"");let f=e.session.current??"",m=e.quiet||e.oneShot?[]:ad(d,f,e.host,u,p.current),g=e.mode==="rich"&&!e.quiet&&!e.oneShot?await d.history(f):[],R={...e,source:d,sessionKey:f,banner:m,prior:g,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:c.current,switchTo:l,random:e.random},P=e.mode==="rich"?await oo(R):await io(R);if(P!==me)return await d.close(),P;if(l.current===void 0)u="restart";else u=l.current.reason,p.current=f,e.session.current=l.current.key,l.current=void 0;c.current=!1}}async function oo(e){let[{render:t},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-wkpkwgjt.js")]),s=tn();H(()=>{s.close()}),wt(),Cs(),process.stdout.write(`${_t}${ra}`);let a=!1,d=t(r(i,{source:e.source,onSwitch:(l,u)=>{a=!0,e.switchTo.current={key:l,reason:"switch"},e.draft.current=u},onNew:(l)=>{a=!0,e.switchTo.current={key:Xo(e.random),reason:"new"},e.draft.current=l},sessions:async()=>[...await co(e.source)].sort(vn),onRestart:(l)=>{a=!0,e.draft.current=l},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((l)=>l.message),initial:zi(Wi(e.banner.slice(1)),e.prior),correctKeys:s.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(l)=>PA({onStatus:l}),install:async(l,u)=>Sn(sd(l,u))},status:()=>e.embedded===void 0?fo(e.source):ao(e.embedded),contextView:()=>po(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Ke(e.noEnhancedKeys)});if(H(()=>d.unmount()),await d.waitUntilExit(),Ze(),!a)process.stdout.write(Xr({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?me:o}async function io(e){let{source:t,sessionKey:r,quiet:i}=e,s=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),s=x.endsWith(`
229
- `)},d=(x)=>{if(!s)a(`
230
- `);a(`${x}
228
+ `),E}let i=await fd([...s].sort(kn));return i===void 0?t():{sessionKey:i,fresh:!1}}return e.asked===void 0?t():{sessionKey:e.asked,fresh:!1}}function kn(e,t){return Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)}function ud(e){return[...e].sort(kn)[0]}async function fd(e){let[{render:t},{createElement:s},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-pngdv97x.js")]),r;oo();let a=t(s(i,{sessions:e,now:Date.now(),columns:Ue(process.stdout.columns,Me),maxRows:Sn,onDone:(d)=>{r=d,a.unmount()}}),{exitOnCtrlC:!1,...Ke()});return H(()=>a.unmount()),await a.waitUntilExit(),r}function md(e,t,s,i,r){let a=e.describe(),d=[`${A.name} ${q} · ${a.agentId} · ${a.model}`,`session ${t} · window ${a.window} · attached to ${s.baseUrl} (pid ${s.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],l=rt(i,r);if(l!==void 0)d.push(l);for(let u of a.warnings)d.push(`warning: ${u.message}`);return d}async function pd(e){let t=e.manifestPath??"",s=De(t),i=RA(t),r=qs({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await r.agent(s).describe();if(a.status==="disabled")throw new n({code:"agent_disabled",message:`${s} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${s}\`, then run again.`});let d=Ys({client:r,agentId:s,host:e.host,description:{agentId:s,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),l={current:void 0},u="first",g={current:void 0},c={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let b=await so({list:()=>mo(d),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof b==="number")return b;if(e.session.current=b.sessionKey,c.current=b.fresh,b.fresh)e.session.current=await d.ownConversation()??b.sessionKey}if(u==="new"){let b=await d.rotateSession();if(b!==void 0)e.session.current=b}e.session.current=await d.resolveSessionKey(e.session.current??"");let f=e.session.current??"",m=e.quiet||e.oneShot?[]:md(d,f,e.host,u,g.current),y=e.mode==="rich"&&!e.quiet&&!e.oneShot?await d.history(f):[],R={...e,source:d,sessionKey:f,banner:m,prior:y,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:c.current,switchTo:l,random:e.random},T=e.mode==="rich"?await io(R):await ao(R);if(T!==he)return await d.close(),T;if(l.current===void 0)u="restart";else u=l.current.reason,g.current=f,e.session.current=l.current.key,l.current=void 0;c.current=!1}}async function io(e){let[{render:t},{createElement:s},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-18dvbyev.js")]),r=un();H(()=>{r.close()}),wt(),Es(),process.stdout.write(`${Rt}${oa}`);let a=!1,d=t(s(i,{source:e.source,onSwitch:(l,u)=>{a=!0,e.switchTo.current={key:l,reason:"switch"},e.draft.current=u},onNew:(l)=>{a=!0,e.switchTo.current={key:$o(e.random),reason:"new"},e.draft.current=l},sessions:async()=>[...await mo(e.source)].sort(kn),onRestart:(l)=>{a=!0,e.draft.current=l},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((l)=>l.message),initial:Vi(qi(e.banner.slice(1)),e.prior),correctKeys:r.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(l)=>LA({onStatus:l}),install:async(l,u)=>mn(ld(l,u))},status:()=>e.embedded===void 0?po(e.source):lo(e.embedded),contextView:()=>go(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Ke(e.noEnhancedKeys)});if(H(()=>d.unmount()),await d.waitUntilExit(),Ze(),!a)process.stdout.write(Vs({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?he:o}async function ao(e){let{source:t,sessionKey:s,quiet:i}=e,r=!0,a=(P)=>{if(P==="")return;process.stdout.write(P),r=P.endsWith(`
229
+ `)},d=(P)=>{if(!r)a(`
230
+ `);a(`${P}
231
231
  `)};if(e.banner.length>0)a(`${e.banner.join(`
232
232
  `)}
233
233
 
234
- `);let l=!i&&e.once===void 0,u=!1,p,c=t.streamFilter(),f=(x)=>{if(x==="")return;a(x),u=!0},m=e.source.subscribe((x)=>{if(x.sessionKey!==void 0&&x.sessionKey!==r)return;switch(x.type){case"model.result":f(c.endStep());return;case"model.chunk":{let{delta:I,kind:_}=x.data;if(_==="reasoning"&&e.showReasoning!==!0)return;if(_!==p){if(p!==void 0)a(`
234
+ `);let l=!i&&e.once===void 0,u=!1,g,c=t.streamFilter(),f=(P)=>{if(P==="")return;a(P),u=!0},m=e.source.subscribe((P)=>{if(P.sessionKey!==void 0&&P.sessionKey!==s)return;switch(P.type){case"model.result":f(c.endStep());return;case"model.chunk":{let{delta:I,kind:O}=P.data;if(O==="reasoning"&&e.showReasoning!==!0)return;if(O!==g){if(g!==void 0)a(`
235
235
 
236
- `);if(e.showReasoning===!0)a(_==="reasoning"?`· reasoning ·
236
+ `);if(e.showReasoning===!0)a(O==="reasoning"?`· reasoning ·
237
237
  `:`· reply ·
238
- `);p=_}if(_==="reasoning"){a(I),u=!0;return}f(c.push(I));return}case"tool.result":{if(!l)return;let{slug:I,ok:_,latencyMs:F,truncated:V}=x.data;d(` · ${I} — ${_?"ok":"failed"} · ${F} ms${V?" · observation trimmed":""}`);return}case"agent.warning":d(` · ${x.data.message}
239
- ${x.data.hint}`);return;case"tool.repair":if(l)d(x.data.slugs.length===0?` · reply stopped short (${x.data.errors.join("; ")}), asking again`:` · ${x.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":d(` · ${x.data.slug} — blocked: ${x.data.reason}`);return;case"context.dropped":d(` · context: ${x.data.messages} older message(s) did not fit the ${x.data.budget}-token budget and were left out`);return;default:return}}),g=async(x)=>{let I=Kn(x,jn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let _=t.reload;if(_===void 0)return"restart";try{let F=await _();d(`reloaded ${F.join(", ")} — this conversation continues`)}catch(F){d(`could not reload: ${F instanceof Error?F.message:String(F)}`)}return"handled"}case"new":return e.switchTo.current={key:Xo(e.random),reason:"new"},"restart";case"help":return d(Yn()),"handled";case"tools":return d(bA(await t.tools())),"handled";case"status":return d(e.embedded===void 0?await fo(t):await ao(e.embedded)),"handled";case"context":return d(await po(e,r)),"handled";case"reset":return await t.clearSession(r),d("session cleared — memory files on disk are untouched"),"handled";case"unknown":return d(on(I)),"handled";case"command":return d(`${I.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${A.slug} ${I.name}${I.rest===""?"":` ${I.rest}`}\``),"handled"}},R,P=0,y=o,j=(x=e.reader.current)=>{if(R!==void 0&&!R.signal.aborted){P=performance.now(),R.abort();return}x?.close(),a(`
240
- `)},D=async(x)=>{R=new AbortController,u=!1,p=void 0,c=t.streamFilter();let I=await t.send(x,{sessionKey:r,signal:R.signal});if(R=void 0,f(c.end()),u&&!s)a(`
238
+ `);g=O}if(O==="reasoning"){a(I),u=!0;return}f(c.push(I));return}case"tool.result":{if(!l)return;let{slug:I,ok:O,latencyMs:j,truncated:V}=P.data;d(` · ${I} — ${O?"ok":"failed"} · ${j} ms${V?" · observation trimmed":""}`);return}case"agent.warning":d(` · ${P.data.message}
239
+ ${P.data.hint}`);return;case"tool.repair":if(l)d(P.data.slugs.length===0?` · reply stopped short (${P.data.errors.join("; ")}), asking again`:` · ${P.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":d(` · ${P.data.slug} — blocked: ${P.data.reason}`);return;case"context.dropped":d(` · context: ${P.data.messages} older message(s) did not fit the ${P.data.budget}-token budget and were left out`);return;default:return}}),y=async(P)=>{let I=Hn(P,Yn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let O=t.reload;if(O===void 0)return"restart";try{let j=await O();d(`reloaded ${j.join(", ")} — this conversation continues`)}catch(j){d(`could not reload: ${j instanceof Error?j.message:String(j)}`)}return"handled"}case"new":return e.switchTo.current={key:$o(e.random),reason:"new"},"restart";case"help":return d(Kn()),"handled";case"tools":return d(DA(await t.tools())),"handled";case"status":return d(e.embedded===void 0?await po(t):await lo(e.embedded)),"handled";case"context":return d(await go(e,s)),"handled";case"reset":return await t.clearSession(s),d("session cleared — memory files on disk are untouched"),"handled";case"unknown":return d(nn(I)),"handled";case"command":return d(`${I.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${A.slug} ${I.name}${I.rest===""?"":` ${I.rest}`}\``),"handled"}},R,T=0,b=o,N=(P=e.reader.current)=>{if(R!==void 0&&!R.signal.aborted){T=performance.now(),R.abort();return}P?.close(),a(`
240
+ `)},M=async(P)=>{R=new AbortController,u=!1,g=void 0,c=t.streamFilter();let I=await t.send(P,{sessionKey:s,signal:R.signal});if(R=void 0,f(c.end()),u&&!r)a(`
241
241
  `);else if(!u&&I.text!=="")a(`${I.text}
242
- `);let _=Tt(I.reason,{steps:I.steps,durationMs:I.durationMs,...P===0?{}:{cancelledAfterMs:performance.now()-P}});if(_!==void 0)a(`
243
- (${_})
242
+ `);let O=Mt(I.reason,{steps:I.steps,durationMs:I.durationMs,...T===0?{}:{cancelledAfterMs:performance.now()-T}});if(O!==void 0)a(`
243
+ (${O})
244
244
  `);if(I.reason==="error"&&I.error!==void 0)process.stderr.write(`
245
245
  ${I.error.code}: ${I.error.message}
246
246
  hint: ${I.error.hint}
247
- `);if(yo(I.reason))y=E;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
247
+ `);if(Bo(I.reason))b=E;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
248
248
 
249
- `);await ht()},b=()=>j();process.on("SIGINT",b);try{if(e.once!==void 0)return await D(e.once),y;if(process.stdin.isTTY!==!0){let I=e.reader.current??eo({input:process.stdin});e.reader.current=I;for await(let _ of I){let F=_.trim();if(F==="")continue;let V=await g(F);if(V==="exit")break;if(V==="restart"){y=me;break}if(V==="handled")continue;await D(F)}return y}let x=e.reader.current??eo({input:process.stdin,output:process.stdout,prompt:Go,terminal:!1});e.reader.current=x,x.prompt();for await(let I of x){let _=I.trim();if(_===""){x.prompt();continue}let F=await g(_);if(F==="exit")break;if(F==="restart"){y=me;break}if(F==="handled"){x.prompt();continue}await D(_),x.prompt()}if(y!==me)x.close(),e.reader.current=void 0;return y}finally{process.off("SIGINT",b),m()}}async function ao(e){let{agent:t,runtime:r}=e,i=t.describe(),s=t.manifest,a=s.channels.filter((c)=>c.enabled).map((c)=>`${c.id} (${c.type})`).join(", "),d=a===""?"none — reached through this session and the HTTP API only":r.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,l=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,u=Mt(s),p=u.filter((c)=>c.role!=="main"&&c.role===c.configuredAs);return C([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${s.tools.dialect} · ${i.window} token window (${cA(u[0]?.window)})`},...p.map((c)=>({label:c.role,value:`${c.modelId} · ${c.window.contextWindow} token window (${cA(c.window)})`})),{label:"channels",value:d},{label:"http api",value:l},{label:"store",value:r.store.location},{label:"background",value:await cd(r,i.id)}])}function lo(e){return e.filter((t)=>!hi(t.sessionKey))}async function co(e){return lo(await e.sessions())}async function fo(e){let t=e.describe(),r=e.host,[i,s]=await Promise.all([e.tools(),e.sessions()]);return C([{label:"agent",value:`${t.agentId} (${t.name})`},{label:"attached to",value:r===void 0?"a host":`${r.baseUrl} · pid ${r.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${t.model} · ${t.window} token window`},{label:"dialect",value:t.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:t.warnings.length===0?"none":t.warnings.map((a)=>a.message).join("; ")}])}async function ld(e,t){let r=await e.previewContext({sessionKey:t}),[i]=Mt(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:cA(i?.window),wireTokens:r.wireTokens,reserveOutput:r.reserveOutput,calibration:r.calibration,lastCompaction:r.compactions===0?void 0:`${r.compactions} stage${r.compactions===1?"":"s"} run this session`}}async function po(e,t){return Ji(await e.source.context(t))}async function cd(e,t){if(e.owned.includes(t))return"this session is serving this agent";let r=await e.store.leases.get(t);if(r!==void 0&&ee(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${A.slug} daemon status ${t}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${A.slug} daemon install ${t}\` keeps it running without a terminal`}function ne(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ud(e,t){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-t;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let s=Math.round(r/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function fd(e,t){if(e.lastFiredAt===void 0)return"never run";let r=sA(e.lastFiredAt,t);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function md(e,t){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let r=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${ne("SCHEDULE",r)} ${ne("WHEN",i)} ${ne("NEXT",7)} LAST
250
- `);for(let a of e)process.stdout.write(`${ne(a.id,r)} ${ne(`${a.kind} ${a.expr}`,i)} ${ne(ud(a,t),7)} ${fd(a,t)}
251
- `);let s=e.filter((a)=>a.lastStatus==="error");if(s.length>0)process.stdout.write(`
252
- ${s.length} failing — \`schedules --id ${s[0]?.id}\` for the error
253
- `)}function pd(e){let t=[["kind",`${e.kind} ${e.expr}`],["timezone",e.timezone??"(host)"],["task",e.task],["deliver",e.deliverChannel===void 0?"none — the reply reaches the event stream only":`${e.deliverChannel} → ${e.deliverTo}`],["session",e.sessionMode],["model role",e.role??"main"],["enabled",e.enabled?"yes":"no"],["declared in",e.origin==="manifest"?"agent.yaml":"the API"],["next run",e.nextRunAt??"(never again)"],["runs",String(e.runs)],["last run",e.lastFiredAt??"never"],["last status",e.lastStatus??"-"]];if(e.lastError!==void 0)t.push(["last error",e.lastError]);let r=Math.max(...t.map(([i])=>i.length));process.stdout.write(`${e.id}
254
- `);for(let[i,s]of t)process.stdout.write(` ${ne(i,r)} ${s}
255
- `)}function hd(e,t){let r=new Set(t),i=new Map;for(let s of e){if(!r.has(s.channel))continue;let a=`${s.channel}\x00${s.peerId}`,d=i.get(a);if(d!==void 0&&d.lastSeen>=s.lastActivityAt)continue;i.set(a,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...i.values()].sort((s,a)=>s.channelId===a.channelId?a.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(a.channelId))}function gd(e,t){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
249
+ `);await Ct()},S=()=>N();process.on("SIGINT",S);try{if(e.once!==void 0)return await M(e.once),b;if(process.stdin.isTTY!==!0){let I=e.reader.current??no({input:process.stdin});e.reader.current=I;for await(let O of I){let j=O.trim();if(j==="")continue;let V=await y(j);if(V==="exit")break;if(V==="restart"){b=he;break}if(V==="handled")continue;await M(j)}return b}let P=e.reader.current??no({input:process.stdin,output:process.stdout,prompt:Po,terminal:!1});e.reader.current=P,P.prompt();for await(let I of P){let O=I.trim();if(O===""){P.prompt();continue}let j=await y(O);if(j==="exit")break;if(j==="restart"){b=he;break}if(j==="handled"){P.prompt();continue}await M(O),P.prompt()}if(b!==he)P.close(),e.reader.current=void 0;return b}finally{process.off("SIGINT",S),m()}}async function lo(e){let{agent:t,runtime:s}=e,i=t.describe(),r=t.manifest,a=r.channels.filter((c)=>c.enabled).map((c)=>`${c.id} (${c.type})`).join(", "),d=a===""?"none — reached through this session and the HTTP API only":s.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,l=!r.server.enabled?"off":`enabled on ${r.server.host}:${r.server.port}, NOT bound here — \`serve\` binds it`,u=Nt(r),g=u.filter((c)=>c.role!=="main"&&c.role===c.configuredAs);return p([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${r.tools.dialect} · ${i.window} token window (${gA(u[0]?.window)})`},...g.map((c)=>({label:c.role,value:`${c.modelId} · ${c.window.contextWindow} token window (${gA(c.window)})`})),{label:"channels",value:d},{label:"http api",value:l},{label:"store",value:s.store.location},{label:"background",value:await gd(s,i.id)}])}function co(e){return e.filter((t)=>!pi(t.sessionKey))}async function mo(e){return co(await e.sessions())}async function po(e){let t=e.describe(),s=e.host,[i,r]=await Promise.all([e.tools(),e.sessions()]);return p([{label:"agent",value:`${t.agentId} (${t.name})`},{label:"attached to",value:s===void 0?"a host":`${s.baseUrl} · pid ${s.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${t.model} · ${t.window} token window`},{label:"dialect",value:t.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${r.length} on this agent`},{label:"warnings",value:t.warnings.length===0?"none":t.warnings.map((a)=>a.message).join("; ")}])}async function hd(e,t){let s=await e.previewContext({sessionKey:t}),[i]=Nt(e.manifest);return{slots:s.slots,history:s.history,cache:s.cache,total:s.total,window:s.window,windowSource:gA(i?.window),wireTokens:s.wireTokens,reserveOutput:s.reserveOutput,calibration:s.calibration,lastCompaction:s.compactions===0?void 0:`${s.compactions} stage${s.compactions===1?"":"s"} run this session`}}async function go(e,t){return Yi(await e.source.context(t))}async function gd(e,t){if(e.owned.includes(t))return"this session is serving this agent";let s=await e.store.leases.get(t);if(s!==void 0&&ee(s.pid))return s.mode==="daemon"?`running as a background service · pid ${s.pid} · \`${A.slug} daemon status ${t}\``:`served by another session · pid ${s.pid} (${s.mode})`;return`not supervised — \`${A.slug} daemon install ${t}\` keeps it running without a terminal`}function Z(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function yd(e,t){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let s=Date.parse(e.nextRunAt)-t;if(s<=0)return"due";let i=Math.round(s/60000);if(i<60)return`in ${i}m`;let r=Math.round(s/3600000);return r<48?`in ${r}h`:`in ${Math.round(r/24)}d`}function wd(e,t){if(e.lastFiredAt===void 0)return"never run";let s=iA(e.lastFiredAt,t);if(e.lastStatus==="error")return`FAILED ${s}`;return`ok ${s}`}function bd(e,t){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let s=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${Z("SCHEDULE",s)} ${Z("WHEN",i)} ${Z("NEXT",7)} LAST
250
+ `);for(let a of e)process.stdout.write(`${Z(a.id,s)} ${Z(`${a.kind} ${a.expr}`,i)} ${Z(yd(a,t),7)} ${wd(a,t)}
251
+ `);let r=e.filter((a)=>a.lastStatus==="error");if(r.length>0)process.stdout.write(`
252
+ ${r.length} failing — \`schedules --id ${r[0]?.id}\` for the error
253
+ `)}function $d(e){let t=[["kind",`${e.kind} ${e.expr}`],["timezone",e.timezone??"(host)"],["task",e.task],["deliver",e.deliverChannel===void 0?"none — the reply reaches the event stream only":`${e.deliverChannel} → ${e.deliverTo}`],["session",e.sessionMode],["model role",e.role??"main"],["enabled",e.enabled?"yes":"no"],["declared in",e.origin==="manifest"?"agent.yaml":"the API"],["next run",e.nextRunAt??"(never again)"],["runs",String(e.runs)],["last run",e.lastFiredAt??"never"],["last status",e.lastStatus??"-"]];if(e.lastError!==void 0)t.push(["last error",e.lastError]);let s=Math.max(...t.map(([i])=>i.length));process.stdout.write(`${e.id}
254
+ `);for(let[i,r]of t)process.stdout.write(` ${Z(i,s)} ${r}
255
+ `)}function vd(e,t){let s=new Set(t),i=new Map;for(let r of e){if(!s.has(r.channel))continue;let a=`${r.channel}\x00${r.peerId}`,d=i.get(a);if(d!==void 0&&d.lastSeen>=r.lastActivityAt)continue;i.set(a,{channelId:r.channel,address:r.peerId,lastSeen:r.lastActivityAt})}return[...i.values()].sort((r,a)=>r.channelId===a.channelId?a.lastSeen.localeCompare(r.lastSeen):r.channelId.localeCompare(a.channelId))}function Sd(e,t){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
256
256
  `+` An address appears here once a first message arrives on one.
257
- `);return}let r=Math.max(7,...e.map((s)=>s.channelId.length)),i=Math.max(7,...e.map((s)=>s.address.length));process.stdout.write(`${ne("CHANNEL",r)} ${ne("ADDRESS",i)} LAST SEEN
258
- `);for(let s of e)process.stdout.write(`${ne(s.channelId,r)} ${ne(s.address,i)} ${sA(s.lastSeen,t)}
257
+ `);return}let s=Math.max(7,...e.map((r)=>r.channelId.length)),i=Math.max(7,...e.map((r)=>r.address.length));process.stdout.write(`${Z("CHANNEL",s)} ${Z("ADDRESS",i)} LAST SEEN
258
+ `);for(let r of e)process.stdout.write(`${Z(r.channelId,s)} ${Z(r.address,i)} ${iA(r.lastSeen,t)}
259
259
  `);process.stdout.write(`
260
260
  Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
261
261
  `+`never a person — a private chat is reached by the numeric id above.
262
- `)}async function go(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),lease:!1});H(()=>t.stop("cli-exit"));let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,d]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let l=await r.store.schedules.get(r.id,a);if(l===void 0)return process.stderr.write(`no schedule "${a}" on ${r.id}
262
+ `)}async function vo(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath]),lease:!1});H(()=>t.stop("cli-exit"));let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,d]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let l=await s.store.schedules.get(s.id,a);if(l===void 0)return process.stderr.write(`no schedule "${a}" on ${s.id}
263
263
  hint: run \`schedules\` with no flags to see what this agent has.
264
264
  `),E;if(l.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
265
265
  `+` Writing it here would last until the next start — reconciliation restores every
@@ -267,223 +267,236 @@ Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
267
267
 
268
268
  hint: set \`enabled: ${d}\` on the "${a}" entry under schedules: in
269
269
  ${e.manifestPath}
270
- `),E;await r.store.schedules.setEnabled(r.id,a,d,new Date(i).toISOString()),process.stdout.write(d?`${a} enabled — it fires at its next occurrence, not now
270
+ `),E;await s.store.schedules.setEnabled(s.id,a,d,new Date(i).toISOString()),process.stdout.write(d?`${a} enabled — it fires at its next occurrence, not now
271
271
  `:`${a} disabled — still listed, and it keeps its place in the sequence
272
- `)}if(e.recipients===!0){let a=hd(await r.store.sessions.list(r.id),r.manifest.channels.map((d)=>d.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
273
- `),o;return gd(a,i),o}let s=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:s},null,2)}
274
- `),o;if(e.id!==void 0){let a=s.find((d)=>d.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
275
- `),E;return pd(a),o}if(e.enable===void 0&&e.disable===void 0)md(s,i);return o}import{rmSync as Td}from"node:fs";import{dirname as Uo,join as Id}from"node:path";import{readFileSync as yd}from"node:fs";var wd="server.tokenEnv";function ot(e){let t=yd(e,"utf8"),r=Ft(e),i=new Map,s=new Set(JA(t).filter((a)=>a.path===wd).map((a)=>a.name));for(let a of JA(t)){if(s.has(a.name))continue;let d=i.get(a.name)??[];d.push(a.path),i.set(a.name,d)}return[...i].map(([a,d])=>({name:a,set:rn(r,a),usedBy:d}))}function wo(e,t){let r=ot(e).map((d)=>d.name);for(let[d,l]of Object.entries(t)){if(!r.includes(d))throw new n({code:"secret_not_referenced",message:`"${d}" is not a variable this agent's manifest reads.`,hint:r.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${r.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${d}`});if(l==="")throw new n({code:"secret_value_empty",message:`An empty value for ${d} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${d}`})}let i=v([e]),s=[],a=[];for(let[d,l]of Object.entries(t))if(Ve(e,d,l),s.push(d),rn(i,d))a.push(d);return{written:s,shadowed:a}}import{createHash as bd}from"node:crypto";import{existsSync as he,lstatSync as ct,mkdirSync as it,readdirSync as So,readFileSync as Ne,renameSync as $d,rmSync as ko,writeFileSync as _e}from"node:fs";import{basename as je,dirname as Po,join as X}from"node:path";var Ae="template.yaml",Ro=/^[a-z0-9][a-z0-9-]*$/;function ut(e){let t;try{t=So(e)}catch{return[]}let r=[];for(let i of t.sort()){if(!Ro.test(i))continue;let s=X(e,i);if(!ct(s).isDirectory())continue;try{let a=Pn(s);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((d)=>({name:d.name,...d.description===void 0?{}:{description:d.description},required:d.required,...d.default===void 0?{}:{default:d.default},secret:d.secret!==void 0}))})}catch(a){if(!h(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function Pn(e){let t=X(e,Ae);if(!he(t))throw new n({code:"template_spec_missing",message:`${je(e)} has no ${Ae}.`,hint:`A template is an agent directory with a ${Ae} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return ui(Ne(t,"utf8"),`${je(e)}/${Ae}`)}function mt(e,t=""){let r=[];for(let i of So(X(e,t)).sort()){let s=t===""?i:`${t}/${i}`;if(s===Ae)continue;let a=X(e,s),d=ct(a);if(d.isSymbolicLink())throw new n({code:"template_symlink",message:`${s} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:s});if(d.isDirectory()){r.push(...mt(e,s));continue}let l=Ne(a);if(l.includes(0))throw new n({code:"template_binary_file",message:`${s} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:s});r.push({relPath:s,contents:l.toString("utf8")})}return r}function xo(e){if(!Ro.test(e.template))throw dt(e.template,e.templatesDir);let t=X(e.templatesDir,e.template);if(!he(t)||!ct(t).isDirectory())throw dt(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new n({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=lt(r),s=X(e.agentDirBase,i);if(he(s))throw new n({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Nr({spec:Pn(t),files:mt(t),id:i,name:r,vars:e.vars}),d=X(Po(e.agentDirBase),`.${je(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);it(d,{recursive:!0});try{ke(d,a.files),Io(d,{template:e.template,name:r,vars:To(Pn(t),e.vars),files:vd(a.files)});let l=X(d,"agent.yaml");for(let[c,f]of Object.entries(a.env))Ve(l,c,f);let u=a.files.find((c)=>c.relPath==="agent.yaml"),p={};for(let c of JA(u?.contents??""))if(a.env[c.name]===void 0&&!process.env[c.name])p[c.name]="(pending)";Xe(l,p),it(e.agentDirBase,{recursive:!0}),$d(d,s)}catch(l){throw ko(d,{recursive:!0,force:!0}),l}return{agentId:i,dir:s,manifestPath:X(s,"agent.yaml"),files:[...a.files.map((l)=>l.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function dt(e,t){let r=ut(t).map((i)=>i.name);return new n({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:r.length===0?`This server has no templates. An operator adds one as a directory under ${t}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var pt=".template.json";function kn(e){return bd("sha256").update(e).digest("hex")}function vd(e){return Object.fromEntries(e.map((t)=>[t.relPath,kn(t.contents)]))}function To(e,t){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(t).filter(([i])=>!r.has(i)))}function Io(e,t){_e(X(e,pt),`${JSON.stringify({version:1,...t},null,2)}
276
- `,{mode:384})}function _o(e){let t=X(e,pt);if(!he(t))return;let r=JSON.parse(Ne(t,"utf8"));return{template:r.template,vars:r.vars}}function jo(e){let t=X(e.agentDir,pt);if(!he(t))throw new n({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, because re-rendering needs the hash of every file as it was rendered. For an older agent, edit the files directly or create it again from the template."});let r=JSON.parse(Ne(t,"utf8")),i=X(e.templatesDir,r.template);if(!he(i))throw dt(r.template,e.templatesDir);let s=Pn(i);for(let f of Object.keys(e.vars)){let m=s.vars.find((g)=>g.name===f);if(m?.secret!==void 0)throw new n({code:"template_var_secret",message:`"${f}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${m.secret}.`,field:`vars.${f}`})}let a={...r.vars,...e.vars},d=Nr({spec:s,files:mt(i),id:je(e.agentDir),name:r.name,vars:{...Object.fromEntries(s.vars.filter((f)=>f.secret!==void 0&&f.required).map((f)=>[f.name,"(in .env)"])),...a}}),l=[],u=[],p=[],c={...r.files};try{for(let f of d.files){let m=X(e.agentDir,f.relPath),g=r.files[f.relPath];if(!he(m)){if(g!==void 0){p.push({file:f.relPath,reason:"removed"});continue}it(Po(m),{recursive:!0}),_e(m,f.contents),l.push({path:m,before:void 0}),c[f.relPath]=kn(f.contents),u.push(f.relPath);continue}let R=Ne(m,"utf8");if(Sd(f.relPath,R)){p.push({file:f.relPath,reason:"memory"});continue}if(g===void 0||kn(R)!==g){p.push({file:f.relPath,reason:"edited"});continue}if(R===f.contents)continue;_e(m,f.contents),l.push({path:m,before:R}),c[f.relPath]=kn(f.contents),u.push(f.relPath)}Io(e.agentDir,{template:r.template,name:r.name,vars:To(s,a),files:c})}catch(f){throw $o(l),f}return{rendered:u,skipped:p,undo:()=>{$o(l),_e(t,`${JSON.stringify(r,null,2)}
277
- `,{mode:384})}}}function $o(e){for(let t of e)if(t.before===void 0)ko(t.path,{force:!0});else _e(t.path,t.before)}function Sd(e,t){if(je(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return KA(e,t).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as kd,renameSync as Pd,writeFileSync as Ed}from"node:fs";function Rd(e){try{let t=JSON.parse(kd(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}async function xd(e,t){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${t}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Fo(e){let t=e.fetch??globalThis.fetch,r=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},s=Rd(e.cacheFile);return{cachedPeers:(a)=>s[a]??[],async refreshPeers(a,d){let l=await t(`${r}/v1/relay/peers?participant=${encodeURIComponent(d)}`,{headers:i});if(!l.ok)throw await xd(l,"the peer list");let{peers:u}=await l.json();s[a]=u;let p=`${e.cacheFile}.partial`;return Ed(p,`${JSON.stringify(s,null,2)}
278
- `,{mode:384}),Pd(p,e.cacheFile),u},async ask(a){let d=await t(`${r}/v1/relay/ask`,{method:"POST",headers:{...i,"content-type":"application/json"},body:JSON.stringify({participant:a.participantId,toSilo:a.silo,toAgent:a.agent,question:a.question,askedBy:a.fromAgent,sessionKey:a.sessionKey}),...a.signal===void 0?{}:{signal:a.signal}});if(!d.ok){let l=await d.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:l.error??{code:"relay_unavailable",message:`The control plane answered ${d.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await d.json()}}}function Od(){return YA.shape.server.parse({})}async function Lo(e){let t=v(e.manifestPaths),r=Ad(t),i=e.store??G(),s=await cs(e.manifestPaths,t,i),a=s.filter((k)=>!k.enabled),d=s.filter((k)=>k.enabled),l=e.manifestPaths.length===0,u=[],p=[];for(let k of d)try{u.push({path:k.manifestPath,loaded:z(k.manifestPath,{env:t})})}catch(T){if(!l)throw T;p.push({path:k.manifestPath,detail:h(T)?T.message:String(T),...h(T)&&T.hint!==void 0?{hint:T.hint}:{}})}let c=u[0],f=c?.loaded,m=f?.manifest.server??Od();for(let k of u.slice(1)){let T=k.loaded.manifest.server;for(let[O,Y,Be,ye]of[["server.port",m.port,T.port,e.port!==void 0],["server.host",m.host,T.host,e.host!==void 0],["server.tokenEnv",m.tokenEnv,T.tokenEnv,!1]]){if(ye||Y===Be)continue;throw new n({code:"serve_bind_conflict",message:`${c?.path??"the first manifest"} sets ${O} to ${String(Y)} and ${k.path} sets it to ${String(Be)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:O})}}let g=e.port??m.port,R=e.port===void 0,P=e.host??m.host,y=f===void 0?t[m.tokenEnv]:f.env[m.tokenEnv],j=t[m.tokenEnv],D=u.every((k)=>Xt(Uo(k.path),t)),b=y;if(D&&(j===void 0||j==="")){let k=hn(W(t));if(k!==void 0)b=k;else if(y!==void 0&&y!=="")ii(W(t),y)}let x=t[`${A.envPrefix}SERVICE`]!==void 0,I=new bt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)I.on("agent.channel.status",(k)=>{let T=k.data,O=T.input===void 0?"":T.input.kind==="pairing_code"?`
272
+ `)}if(e.recipients===!0){let a=vd(await s.store.sessions.list(s.id),s.manifest.channels.map((d)=>d.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
273
+ `),o;return Sd(a,i),o}let r=await s.store.schedules.list(s.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:r},null,2)}
274
+ `),o;if(e.id!==void 0){let a=r.find((d)=>d.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${s.id}
275
+ `),E;return $d(a),o}if(e.enable===void 0&&e.disable===void 0)bd(r,i);return o}import{rmSync as Fd}from"node:fs";import{dirname as qo,join as Ld}from"node:path";import{readFileSync as kd}from"node:fs";var Pd="server.tokenEnv";function dt(e){let t=kd(e,"utf8"),s=Gt(e),i=new Map,r=new Set(jA(t).filter((a)=>a.path===Pd).map((a)=>a.name));for(let a of jA(t)){if(r.has(a.name))continue;let d=i.get(a.name)??[];d.push(a.path),i.set(a.name,d)}return[...i].map(([a,d])=>({name:a,set:on(s,a),usedBy:d}))}function So(e,t){let s=dt(e).map((d)=>d.name);for(let[d,l]of Object.entries(t)){if(!s.includes(d))throw new n({code:"secret_not_referenced",message:`"${d}" is not a variable this agent's manifest reads.`,hint:s.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${s.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${d}`});if(l==="")throw new n({code:"secret_value_empty",message:`An empty value for ${d} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${d}`})}let i=v([e]),r=[],a=[];for(let[d,l]of Object.entries(t))if(Ve(e,d,l),r.push(d),on(i,d))a.push(d);return{written:r,shadowed:a}}import{createHash as Ed}from"node:crypto";import{existsSync as ye,lstatSync as mt,mkdirSync as lt,readdirSync as Ro,readFileSync as je,renameSync as Rd,rmSync as To,writeFileSync as Ne}from"node:fs";import{basename as Le,dirname as xo,join as X}from"node:path";var Ce="template.yaml",Ao=/^[a-z0-9][a-z0-9-]*$/;function ht(e){let t;try{t=Ro(e)}catch{return[]}let s=[];for(let i of t.sort()){if(!Ao.test(i))continue;let r=X(e,i);if(!mt(r).isDirectory())continue;try{let a=Rn(r);s.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((d)=>({name:d.name,...d.description===void 0?{}:{description:d.description},required:d.required,...d.default===void 0?{}:{default:d.default},secret:d.secret!==void 0}))})}catch(a){if(!h(a))throw a;s.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return s}function Rn(e){let t=X(e,Ce);if(!ye(t))throw new n({code:"template_spec_missing",message:`${Le(e)} has no ${Ce}.`,hint:`A template is an agent directory with a ${Ce} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return Ii(je(t,"utf8"),`${Le(e)}/${Ce}`)}function gt(e,t=""){let s=[];for(let i of Ro(X(e,t)).sort()){let r=t===""?i:`${t}/${i}`;if(r===Ce)continue;let a=X(e,r),d=mt(a);if(d.isSymbolicLink())throw new n({code:"template_symlink",message:`${r} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:r});if(d.isDirectory()){s.push(...gt(e,r));continue}let l=je(a);if(l.includes(0))throw new n({code:"template_binary_file",message:`${r} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:r});s.push({relPath:r,contents:l.toString("utf8")})}return s}function _o(e){if(!Ao.test(e.template))throw ut(e.template,e.templatesDir);let t=X(e.templatesDir,e.template);if(!ye(t)||!mt(t).isDirectory())throw ut(e.template,e.templatesDir);let s=e.name.trim();if(s==="")throw new n({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=ct(s),r=X(e.agentDirBase,i);if(ye(r))throw new n({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Or({spec:Rn(t),files:gt(t),id:i,name:s,vars:e.vars}),d=X(xo(e.agentDirBase),`.${Le(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);lt(d,{recursive:!0});try{Te(d,a.files),Fo(d,{template:e.template,name:s,vars:jo(Rn(t),e.vars),files:Td(a.files)});let l=X(d,"agent.yaml");for(let[c,f]of Object.entries(a.env))Ve(l,c,f);let u=a.files.find((c)=>c.relPath==="agent.yaml"),g={};for(let c of jA(u?.contents??""))if(a.env[c.name]===void 0&&!process.env[c.name])g[c.name]="(pending)";en(l,g),lt(e.agentDirBase,{recursive:!0}),Rd(d,r)}catch(l){throw To(d,{recursive:!0,force:!0}),l}return{agentId:i,dir:r,manifestPath:X(r,"agent.yaml"),files:[...a.files.map((l)=>l.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ut(e,t){let s=ht(t).map((i)=>i.name);return new n({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:s.length===0?`This server has no templates. An operator adds one as a directory under ${t}.`:`Templates here: ${s.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var yt=".template.json";function Pn(e){return Ed("sha256").update(e).digest("hex")}function Td(e){return Object.fromEntries(e.map((t)=>[t.relPath,Pn(t.contents)]))}function jo(e,t){let s=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(t).filter(([i])=>!s.has(i)))}function Fo(e,t){Ne(X(e,yt),`${JSON.stringify({version:1,...t},null,2)}
276
+ `,{mode:384})}function Lo(e){let t=X(e,yt);if(!ye(t))return;let s=JSON.parse(je(t,"utf8"));return{template:s.template,vars:s.vars}}function Ko(e){let t=X(e.agentDir,yt);if(!ye(t))throw new n({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, because re-rendering needs the hash of every file as it was rendered. For an older agent, edit the files directly or create it again from the template."});let s=JSON.parse(je(t,"utf8")),i=X(e.templatesDir,s.template);if(!ye(i))throw ut(s.template,e.templatesDir);let r=Rn(i);for(let f of Object.keys(e.vars)){let m=r.vars.find((y)=>y.name===f);if(m?.secret!==void 0)throw new n({code:"template_var_secret",message:`"${f}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${m.secret}.`,field:`vars.${f}`})}let a={...s.vars,...e.vars},d=Or({spec:r,files:gt(i),id:Le(e.agentDir),name:s.name,vars:{...Object.fromEntries(r.vars.filter((f)=>f.secret!==void 0&&f.required).map((f)=>[f.name,"(in .env)"])),...a}}),l=[],u=[],g=[],c={...s.files};try{for(let f of d.files){let m=X(e.agentDir,f.relPath),y=s.files[f.relPath];if(!ye(m)){if(y!==void 0){g.push({file:f.relPath,reason:"removed"});continue}lt(xo(m),{recursive:!0}),Ne(m,f.contents),l.push({path:m,before:void 0}),c[f.relPath]=Pn(f.contents),u.push(f.relPath);continue}let R=je(m,"utf8");if(xd(f.relPath,R)){g.push({file:f.relPath,reason:"memory"});continue}if(y===void 0||Pn(R)!==y){g.push({file:f.relPath,reason:"edited"});continue}if(R===f.contents)continue;Ne(m,f.contents),l.push({path:m,before:R}),c[f.relPath]=Pn(f.contents),u.push(f.relPath)}Fo(e.agentDir,{template:s.template,name:s.name,vars:jo(r,a),files:c})}catch(f){throw Eo(l),f}return{rendered:u,skipped:g,undo:()=>{Eo(l),Ne(t,`${JSON.stringify(s,null,2)}
277
+ `,{mode:384})}}}function Eo(e){for(let t of e)if(t.before===void 0)To(t.path,{force:!0});else Ne(t.path,t.before)}function xd(e,t){if(Le(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return HA(e,t).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as Id,renameSync as Od,writeFileSync as Ad}from"node:fs";function _d(e){try{let t=JSON.parse(Id(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}async function Cd(e,t){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${t}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Uo(e){let t=e.fetch??globalThis.fetch,s=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},r=_d(e.cacheFile);return{cachedPeers:(a)=>r[a]??[],async refreshPeers(a,d){let l=await t(`${s}/v1/relay/peers?participant=${encodeURIComponent(d)}`,{headers:i});if(!l.ok)throw await Cd(l,"the peer list");let{peers:u}=await l.json();r[a]=u;let g=`${e.cacheFile}.partial`;return Ad(g,`${JSON.stringify(r,null,2)}
278
+ `,{mode:384}),Od(g,e.cacheFile),u},async ask(a){let d=await t(`${s}/v1/relay/ask`,{method:"POST",headers:{...i,"content-type":"application/json"},body:JSON.stringify({participant:a.participantId,toSilo:a.silo,toAgent:a.agent,question:a.question,askedBy:a.fromAgent,sessionKey:a.sessionKey}),...a.signal===void 0?{}:{signal:a.signal}});if(!d.ok){let l=await d.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:l.error??{code:"relay_unavailable",message:`The control plane answered ${d.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await d.json()}}}import{Worker as Nd}from"node:worker_threads";var Mo=60;function Wo(e){let t=`${A.envPrefix}LOOP_STALL_S`,s=e[t];if(s===void 0||s==="")return Mo;if(!/^\d+$/.test(s))throw new n({code:"serve_loop_stall_invalid",message:`${t} is "${s}", which is not a whole number of seconds.`,hint:`Set it to the seconds a frozen server may stay frozen before it is killed and restarted (default ${Mo}), or 0 to switch the watchdog off.`,field:t});return Number(s)}var jd=`
279
+ const { workerData } = require("node:worker_threads")
280
+ const { writeSync } = require("node:fs")
281
+ const beat = new Float64Array(workerData.beat)
282
+ setInterval(() => {
283
+ const stalled = Date.now() - beat[0]
284
+ if (stalled < workerData.limitMs) return
285
+ try {
286
+ writeSync(2, workerData.prefix + "event loop stalled for " + Math.round(stalled / 1000) + "s; killing the process so its supervisor restarts it\\n")
287
+ } finally {
288
+ process.kill(workerData.pid, "SIGKILL")
289
+ }
290
+ }, 1000)
291
+ `;function Go(e,t=`${A.slug}: `){if(e<=0)return()=>{};let s=new Float64Array(new SharedArrayBuffer(Float64Array.BYTES_PER_ELEMENT));s[0]=Date.now();let i=setInterval(()=>{s[0]=Date.now()},1000);i.unref();let r=new Nd(jd,{eval:!0,workerData:{beat:s.buffer,limitMs:e*1000,pid:process.pid,prefix:t}});return r.unref(),()=>{clearInterval(i),r.terminate()}}function Kd(){return KA.shape.server.parse({})}async function Vo(e){let t=v(e.manifestPaths),s=Ud(t),i=Wo(t),r=e.store??G(),a=await as(e.manifestPaths,t,r),d=a.filter((k)=>!k.enabled),l=a.filter((k)=>k.enabled),u=e.manifestPaths.length===0,g=[],c=[];for(let k of l)try{g.push({path:k.manifestPath,loaded:z(k.manifestPath,{env:t})})}catch(x){if(!u)throw x;c.push({path:k.manifestPath,detail:h(x)?x.message:String(x),...h(x)&&x.hint!==void 0?{hint:x.hint}:{}})}let f=g[0],m=f?.loaded,y=m?.manifest.server??Kd();for(let k of g.slice(1)){let x=k.loaded.manifest.server;for(let[_,Y,qe,$e]of[["server.port",y.port,x.port,e.port!==void 0],["server.host",y.host,x.host,e.host!==void 0],["server.tokenEnv",y.tokenEnv,x.tokenEnv,!1]]){if($e||Y===qe)continue;throw new n({code:"serve_bind_conflict",message:`${f?.path??"the first manifest"} sets ${_} to ${String(Y)} and ${k.path} sets it to ${String(qe)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:_})}}let R=e.port??y.port,T=e.port===void 0,b=e.host??y.host,N=m===void 0?t[y.tokenEnv]:m.env[y.tokenEnv],M=t[y.tokenEnv],S=g.every((k)=>$t(qo(k.path),t)),P=N;if(S&&(M===void 0||M==="")){let k=Cn(W(t));if(k!==void 0)P=k;else if(N!==void 0&&N!=="")ii(W(t),N)}let I=t[`${A.envPrefix}SERVICE`]!==void 0,O=new bt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)O.on("agent.channel.status",(k)=>{let x=k.data,_=x.input===void 0?"":x.input.kind==="pairing_code"?`
279
292
 
280
- ${T.input.payload}
281
- ${T.input.expiresAt===void 0?"":`
282
- expires ${T.input.expiresAt}`}`:` (${T.input.kind}${T.input.expiresAt===void 0?"":`, expires ${T.input.expiresAt}`} — GET /v1/agents/${k.agentId??""} carries it)`;process.stdout.write(` ${T.channelId}: ${T.status}${T.detail===void 0?"":` — ${T.detail}`}${O}
283
- `)}),I.on("agent.channel.error",(k)=>{let T=k.data;process.stderr.write(` ${T.channelId}: ${T.message}
284
- hint: ${T.hint}
285
- `)}),I.on("error",(k)=>{let T=k.data,O=k.sessionKey===void 0?"":` [${k.sessionKey}]`;process.stderr.write(` turn failed${O}: ${T.code}: ${T.message}
286
- hint: ${T.hint}
287
- `)}),I.on("agent.channel.rejected",(k)=>{let T=k.data;process.stdout.write(` ${T.channelId}: ${T.reason} — ${T.detail}
288
- `)});let _=jr(),F=t[`${A.envPrefix}RELAY_URL`],V=t[`${A.envPrefix}RELAY_TOKEN`],N=F===void 0||F===""||V===void 0||V===""?void 0:Fo({url:F,token:V,cacheFile:Id(Uo(i),"relay-peers.json")}),Z=(k)=>({agents:k,...N===void 0?{}:{relay:N},approve:_.approver,env:t,bus:I,toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),K;try{K=await Ce.create(Z(u.map((k)=>k.path)))}catch(k){if(!l||u.length===0)throw k;let T=[];for(let O of u)try{await(await Ce.create({...Z([O.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),T.push(O)}catch(Y){p.push({path:O.path,detail:h(Y)?Y.message:String(Y),...h(Y)&&Y.hint!==void 0?{hint:Y.hint}:{}})}if(T.length===u.length)throw k;u.splice(0,u.length,...T),K=await Ce.create(Z(T.map((O)=>O.path)))}hs();let Le=_d(),$e=await K.store.operatorKeys.liveCount(),te=$e===0||e.claim===!0?ns():void 0,se,Rn=[];try{se=await Nd(g,R,(k)=>(Rn.push(k),is({runtime:K,host:P,port:k,approvals:_,allowedOrigins:m.allowedOrigins,allowedHosts:m.allowedHosts,resolveAgent:(T)=>to(T,t),provision:{steps:()=>Dt({agentDirBase:W(t)}),create:(T)=>Gt({answers:T,defaults:{agentDirBase:W(t)}}),claim:async(T)=>{await we(K.store,T,W(t))},templates:()=>ut(br(t)),createFromTemplate:(T)=>xo({...T,templatesDir:br(t),agentDirBase:W(t)}),rerender:(T)=>jo({...T,templatesDir:br(t)}),templateOf:_o},secrets:{status:ot,write:wo},remover:Fd(t),home:Oe(t),channels:{setEnabled:Wn,setCredential:zn,unpair:Zn},...te===void 0?{}:{claim:te},...b===void 0||b===""?{}:{token:b}})))}catch(k){if(await K.stop("server failed to bind"),h(k))throw k;let T=Rn.length>1?` — also tried ${Rn.slice(1).join(", ")}`:"";throw new n({code:"server_bind_failed",message:`Could not bind ${P}:${g}${T}: ${k instanceof Error?k.message:String(k)}`,hint:R?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${A.slug} stop\` releases one this runtime started.`:"Another process is on that port, and --port was given explicitly so nothing else was tried. Drop the flag to let it walk to the next free port, or name a different one.",cause:k})}let ri=K.owned.length===0&&await ls(K.store.leases,{runtimeId:K.runtimeId,mode:x?"daemon":"terminal"});await K.publishAddress(se.url);let de=K.list(),yt=de[0];if(yt!==void 0)process.title=de.length===1?`${A.slug} ${yt.id}`:`${A.slug} ${de.length} agents`;for(let k of de)k.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:se.url,websocket:se.websocket,authenticated:b!==void 0&&b!=="",keys:$e,...te===void 0?{}:{claim:te.token},agents:de.map((k)=>({id:k.id,channels:K.channels.statusOf(k.id)})),declined:K.declined.map((k)=>({agentId:k.agentId,pid:k.pid,mode:k.mode,since:k.startedAt})),disabled:a.map((k)=>({agentId:k.agentId,...k.reason===void 0?{}:{reason:k.reason}})),broken:p.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
289
- `);else{let k=`http://${gn(P)}:${se.port}`,T=k===se.url?"":` (bound ${P} — every interface)`;if(process.stdout.write(`${A.name} serving on ${k}${T}
290
- `),se.port!==g)process.stdout.write(` moved from ${g} — something else is on it. \`--port ${g}\` would refuse instead of moving.
293
+ ${x.input.payload}
294
+ ${x.input.expiresAt===void 0?"":`
295
+ expires ${x.input.expiresAt}`}`:` (${x.input.kind}${x.input.expiresAt===void 0?"":`, expires ${x.input.expiresAt}`} — GET /v1/agents/${k.agentId??""} carries it)`;process.stdout.write(` ${x.channelId}: ${x.status}${x.detail===void 0?"":` — ${x.detail}`}${_}
296
+ `)}),O.on("agent.channel.error",(k)=>{let x=k.data;process.stderr.write(` ${x.channelId}: ${x.message}
297
+ hint: ${x.hint}
298
+ `)}),O.on("error",(k)=>{let x=k.data,_=k.sessionKey===void 0?"":` [${k.sessionKey}]`;process.stderr.write(` turn failed${_}: ${x.code}: ${x.message}
299
+ hint: ${x.hint}
300
+ `)}),O.on("agent.channel.rejected",(k)=>{let x=k.data;process.stdout.write(` ${x.channelId}: ${x.reason} — ${x.detail}
301
+ `)});let j=Yr(),V=t[`${A.envPrefix}RELAY_URL`],C=t[`${A.envPrefix}RELAY_TOKEN`],ne=V===void 0||V===""||C===void 0||C===""?void 0:Uo({url:V,token:C,cacheFile:Ld(qo(r),"relay-peers.json")}),we=(k)=>({agents:k,...ne===void 0?{}:{relay:ne},approve:j.approver,env:t,bus:O,toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,startChannels:!0,startSchedules:!0,store:r,mode:I?"daemon":"terminal"}),F;try{F=await pe.create(we(g.map((k)=>k.path)))}catch(k){if(!u||g.length===0)throw k;let x=[];for(let _ of g)try{await(await pe.create({...we([_.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),x.push(_)}catch(Y){c.push({path:_.path,detail:h(Y)?Y.message:String(Y),...h(Y)&&Y.hint!==void 0?{hint:Y.hint}:{}})}if(x.length===g.length)throw k;g.splice(0,g.length,...x),F=await pe.create(we(x.map((_)=>_.path)))}ps();let Be=Md(),ke=await F.store.operatorKeys.liveCount(),le=ke===0||e.claim===!0?ts():void 0,te,xn=[];try{te=await Hd(R,T,(k)=>(xn.push(k),os({runtime:F,host:b,port:k,approvals:j,allowedOrigins:y.allowedOrigins,allowedHosts:y.allowedHosts,resolveAgent:(x)=>eo(x,t),provision:{steps:()=>qt({agentDirBase:W(t)}),create:(x)=>Vt({answers:x,defaults:{agentDirBase:W(t)}}),claim:async(x)=>{await ve(F.store,x,W(t))},templates:()=>ht(Dr(t)),createFromTemplate:(x)=>_o({...x,templatesDir:Dr(t),agentDirBase:W(t)}),rerender:(x)=>Ko({...x,templatesDir:Dr(t)}),templateOf:Lo},secrets:{status:dt,write:So},remover:Gd(t),home:Oe(t),channels:{setEnabled:Vn,setCredential:Wn,unpair:zn},...le===void 0?{}:{claim:le},...P===void 0||P===""?{}:{token:P}})))}catch(k){if(await F.stop("server failed to bind"),h(k))throw k;let x=xn.length>1?` — also tried ${xn.slice(1).join(", ")}`:"";throw new n({code:"server_bind_failed",message:`Could not bind ${b}:${R}${x}: ${k instanceof Error?k.message:String(k)}`,hint:T?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${A.slug} stop\` releases one this runtime started.`:"Another process is on that port, and --port was given explicitly so nothing else was tried. Drop the flag to let it walk to the next free port, or name a different one.",cause:k})}let ci=F.owned.length===0&&await gs(F.store.leases,{runtimeId:F.runtimeId,mode:I?"daemon":"terminal"});await F.publishAddress(te.url);let ie=F.list(),vt=ie[0];if(vt!==void 0)process.title=ie.length===1?`${A.slug} ${vt.id}`:`${A.slug} ${ie.length} agents`;for(let k of ie)k.reportRuntimeState({serverListening:!0});let ui=Go(i);if(e.json===!0)process.stdout.write(`${JSON.stringify({url:te.url,websocket:te.websocket,authenticated:P!==void 0&&P!=="",keys:ke,...le===void 0?{}:{claim:le.token},agents:ie.map((k)=>({id:k.id,channels:F.channels.statusOf(k.id)})),declined:F.declined.map((k)=>({agentId:k.agentId,pid:k.pid,mode:k.mode,since:k.startedAt})),disabled:d.map((k)=>({agentId:k.agentId,...k.reason===void 0?{}:{reason:k.reason}})),broken:c.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
302
+ `);else{let k=`http://${an(b)}:${te.port}`,x=k===te.url?"":` (bound ${b} — every interface)`;if(process.stdout.write(`${A.name} serving on ${k}${x}
303
+ `),te.port!==R)process.stdout.write(` moved from ${R} — something else is on it. \`--port ${R}\` would refuse instead of moving.
291
304
  `);process.stdout.write(` web UI ${k}/ · API reference ${k}/docs
292
- `);for(let O of de){let Y=K.channels.statusOf(O.id),Be=Y.length===0?"no channels":Y.map((ve)=>`${ve.id} (${ve.type}${ve.status==="error"?", BROKEN":""})`).join(", "),ye=O.manifest.schedules.filter((ve)=>ve.enabled),oi=O.manifest.schedules.length===0?"":`, ${ye.length} schedule${ye.length===1?"":"s"}${O.manifest.schedules.length>ye.length?` (+${O.manifest.schedules.length-ye.length} disabled)`:""}`;process.stdout.write(` ${O.id} — ${Be}${oi}
293
- `)}for(let O of a)process.stdout.write(` ${O.agentId} — stopped${O.reason===void 0?"":` (${O.reason})`}, \`${A.slug} start ${O.agentId}\`
294
- `);for(let O of p)if(process.stdout.write(` ${O.path} — NOT served: ${O.detail}
295
- `),O.hint!==void 0)process.stdout.write(` hint: ${O.hint}
296
- `);for(let O of K.declined)process.stdout.write(` ${O.agentId} — NOT served here: pid ${O.pid} (${O.mode}) already has it
297
- `);if(K.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
298
- `);if(te!==void 0){if(process.stdout.write(` open once to claim this server:
299
- ${os(P,se.port,te.token)}
300
- without a browser: ${rs(P,se.port,te.token)}
301
- `),b===void 0||b==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
302
- `)}if(b===void 0||b==="")process.stdout.write(` unauthenticated — loopback only. Set ${m.tokenEnv} to bind a public host.
303
- `);if(x)process.stdout.write(` running as a background service · ${A.slug} daemon status ${de[0]?.id??""}
304
- `);else if(Hr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
305
- `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${de[0]?.id===void 0?"":` ${de[0].id}`}\` keeps it running.
306
- `)}let vt=!1,St=async()=>{if(vt)return;if(vt=!0,r>0&&K.all().some((k)=>k.inFlight>0)){let k=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
307
- `);let T=await K.drain(r);process.stdout.write(T===0?`drained in ${Date.now()-k} ms
308
- `:`${T} turn(s) still running after ${r} ms; the next start marks them interrupted
309
- `)}if(await se.stop(),ri)await K.store.leases.release(xt,K.runtimeId).catch(()=>{});await K.stop("interrupted")};return H(St),await Le,process.stdout.write(`stopping
310
- `),await St(),o}function Ad(e){let t=`${A.envPrefix}DRAIN_MS`,r=e[t];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new n({code:"serve_drain_invalid",message:`${t} is "${r}", which is not a number of milliseconds.`,hint:"Set it to a whole number, a few seconds under the orchestrator's grace period — 25000 beside Kubernetes' default terminationGracePeriodSeconds of 30. Unset, a stop does not wait.",field:t});return Number(r)}function _d(){return new Promise((e)=>{let t=()=>{process.off("SIGINT",t),process.off("SIGTERM",t),e()};process.once("SIGINT",t),process.once("SIGTERM",t)})}var Cd=16;async function Nd(e,t,r){let i=t&&e!==0?e+Cd:e;for(let s=e;;s+=1)try{return await r(s)}catch(a){if(s>=i||!jd(a))throw a}}function jd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let t=e instanceof Error?e.message:String(e);return t.includes("EADDRINUSE")||t.includes("in use")}function Fd(e){return{locate(t){let r=oe(e).filter((s)=>s.id===t),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${t}" in the sandbox, so there are no files here to delete.`,hint:"Only sandbox agents are deleted over the API. An agent elsewhere is removed by deleting its directory yourself."}};if(r.length>1)return{ok:!1,status:409,error:{code:"agent_remove_shared_id",message:`${r.length} sandbox directories declare id "${t}": ${r.map((s)=>s.dir).join(", ")}.`,hint:"They share one conversation history, so deleting either would delete the other's too. Give one a different id first."}};return{ok:!0,dir:i.dir}},async deleteDir(t){if(!Xt(t,e))throw Error(`refusing to delete ${t}: it is outside the sandbox`);Td(t,{recursive:!0,force:!0})}}}function B(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Kd(e){let t=new Map,r=[];for(let i of e){let s=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){r.push(a);continue}let d=`schedule:${s[1]}`,l=t.get(d);if(l===void 0){let u={...a,sessionKey:`${d}:*`,runs:1};t.set(d,u),r.push(u);continue}if(l.runs=(l.runs??1)+1,l.messages+=i.messages,l.turns+=i.turns,i.lastActivityAt>l.lastActivityAt)l.lastActivityAt=i.lastActivityAt}return r}function Ud(e){if(e.length===0){process.stdout.write(`no sessions yet
311
- `);return}let t=Kd(e),r=Math.max(7,...t.map((i)=>i.sessionKey.length));process.stdout.write(`${B("SESSION",r)} ${B("MSGS",5)} ${B("TURNS",5)} ${B("PHASE",8)} LAST
312
- `);for(let i of t){let s=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${B(i.sessionKey,r)} ${B(String(i.messages),5)} ${B(String(i.turns),5)} ${B(i.phase??"-",8)} ${sA(i.lastActivityAt,Date.now())}${s}
313
- `)}}async function Ld(e,t,r){let i=await e.store.messages.page(e.id,t,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${t}
314
- `);return}for(let s of[...i.messages].reverse())process.stdout.write(`${s.role}: ${s.content}
305
+ `);for(let _ of ie){let Y=F.channels.statusOf(_.id),qe=Y.length===0?"no channels":Y.map((Pe)=>`${Pe.id} (${Pe.type}${Pe.status==="error"?", BROKEN":""})`).join(", "),$e=_.manifest.schedules.filter((Pe)=>Pe.enabled),mi=_.manifest.schedules.length===0?"":`, ${$e.length} schedule${$e.length===1?"":"s"}${_.manifest.schedules.length>$e.length?` (+${_.manifest.schedules.length-$e.length} disabled)`:""}`;process.stdout.write(` ${_.id} — ${qe}${mi}
306
+ `)}for(let _ of d)process.stdout.write(` ${_.agentId} — stopped${_.reason===void 0?"":` (${_.reason})`}, \`${A.slug} start ${_.agentId}\`
307
+ `);for(let _ of c)if(process.stdout.write(` ${_.path} — NOT served: ${_.detail}
308
+ `),_.hint!==void 0)process.stdout.write(` hint: ${_.hint}
309
+ `);for(let _ of F.declined)process.stdout.write(` ${_.agentId} — NOT served here: pid ${_.pid} (${_.mode}) already has it
310
+ `);if(F.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
311
+ `);if(le!==void 0){if(process.stdout.write(` open once to claim this server:
312
+ ${As(b,te.port,le.token)}
313
+ without a browser: ${ns(b,te.port,le.token)}
314
+ `),P===void 0||P==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
315
+ `)}if(P===void 0||P==="")process.stdout.write(` unauthenticated — loopback only. Set ${y.tokenEnv} to bind a public host.
316
+ `);if(I)process.stdout.write(` running as a background service · ${A.slug} daemon status ${ie[0]?.id??""}
317
+ `);else if(xr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
318
+ `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${ie[0]?.id===void 0?"":` ${ie[0].id}`}\` keeps it running.
319
+ `)}let St=!1,kt=async()=>{if(St)return;if(St=!0,ui(),s>0&&F.all().some((k)=>k.inFlight>0)){let k=Date.now();process.stdout.write(`draining — waiting up to ${s} ms for running turns
320
+ `);let x=await F.drain(s);process.stdout.write(x===0?`drained in ${Date.now()-k} ms
321
+ `:`${x} turn(s) still running after ${s} ms; the next start marks them interrupted
322
+ `)}if(await te.stop(),ci)await F.store.leases.release(Ut,F.runtimeId).catch(()=>{});await F.stop("interrupted")};return H(kt),await Be,process.stdout.write(`stopping
323
+ `),await kt(),o}function Ud(e){let t=`${A.envPrefix}DRAIN_MS`,s=e[t];if(s===void 0||s==="")return 0;if(!/^\d+$/.test(s))throw new n({code:"serve_drain_invalid",message:`${t} is "${s}", which is not a number of milliseconds.`,hint:"Set it to a whole number, a few seconds under the orchestrator's grace period — 25000 beside Kubernetes' default terminationGracePeriodSeconds of 30. Unset, a stop does not wait.",field:t});return Number(s)}function Md(){return new Promise((e)=>{let t=()=>{process.off("SIGINT",t),process.off("SIGTERM",t),e()};process.once("SIGINT",t),process.once("SIGTERM",t)})}var Dd=16;async function Hd(e,t,s){let i=t&&e!==0?e+Dd:e;for(let r=e;;r+=1)try{return await s(r)}catch(a){if(r>=i||!Wd(a))throw a}}function Wd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let t=e instanceof Error?e.message:String(e);return t.includes("EADDRINUSE")||t.includes("in use")}function Gd(e){return{locate(t){let s=oe(e).filter((r)=>r.id===t),i=s[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${t}" in the sandbox, so there are no files here to delete.`,hint:"Only sandbox agents are deleted over the API. An agent elsewhere is removed by deleting its directory yourself."}};if(s.length>1)return{ok:!1,status:409,error:{code:"agent_remove_shared_id",message:`${s.length} sandbox directories declare id "${t}": ${s.map((r)=>r.dir).join(", ")}.`,hint:"They share one conversation history, so deleting either would delete the other's too. Give one a different id first."}};return{ok:!0,dir:i.dir}},async deleteDir(t){if(!$t(t,e))throw Error(`refusing to delete ${t}: it is outside the sandbox`);Fd(t,{recursive:!0,force:!0})}}}function B(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Bd(e){let t=new Map,s=[];for(let i of e){let r=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(r.length!==3||r[0]!=="schedule"){s.push(a);continue}let d=`schedule:${r[1]}`,l=t.get(d);if(l===void 0){let u={...a,sessionKey:`${d}:*`,runs:1};t.set(d,u),s.push(u);continue}if(l.runs=(l.runs??1)+1,l.messages+=i.messages,l.turns+=i.turns,i.lastActivityAt>l.lastActivityAt)l.lastActivityAt=i.lastActivityAt}return s}function qd(e){if(e.length===0){process.stdout.write(`no sessions yet
324
+ `);return}let t=Bd(e),s=Math.max(7,...t.map((i)=>i.sessionKey.length));process.stdout.write(`${B("SESSION",s)} ${B("MSGS",5)} ${B("TURNS",5)} ${B("PHASE",8)} LAST
325
+ `);for(let i of t){let r=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${B(i.sessionKey,s)} ${B(String(i.messages),5)} ${B(String(i.turns),5)} ${B(i.phase??"-",8)} ${iA(i.lastActivityAt,Date.now())}${r}
326
+ `)}}async function Vd(e,t,s){let i=await e.store.messages.page(e.id,t,{limit:s});if(i.messages.length===0){process.stdout.write(`no messages in ${t}
327
+ `);return}for(let r of[...i.messages].reverse())process.stdout.write(`${r.role}: ${r.content}
315
328
  `);if(i.nextBefore!==void 0)process.stdout.write(`
316
329
  … older messages exist; raise --limit
317
- `)}async function Md(e,t,r){let i=await e.turns(t,r);if(i.length===0){process.stdout.write(`no turns in ${t}
330
+ `)}async function Jd(e,t,s){let i=await e.turns(t,s);if(i.length===0){process.stdout.write(`no turns in ${t}
318
331
  `);return}process.stdout.write(`${B("TURN",22)} ${B("STATUS",9)} ${B("STEPS",5)} ${B("TOKENS",13)} ${B("MS",6)} SOURCE
319
- `);for(let s of i)if(process.stdout.write(`${B(s.turnId,22)} ${B(s.status,9)} ${B(String(s.steps),5)} ${B(`${s.promptTokens}/${s.outputTokens}`,13)} ${B(String(s.durationMs??"-"),6)} ${s.source}
320
- `),s.errorCode!==void 0){if(process.stdout.write(` ${s.errorCode}: ${s.errorMessage}
321
- `),s.errorHint!==void 0)process.stdout.write(` hint: ${s.errorHint}
322
- `)}}async function Ho(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});H(()=>t.stop("cli-exit"));let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ko;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await r.store.messages.count(r.id,e.sessionKey);return await r.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
323
- `),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:t.store.location,sessions:await r.sessions()}:{store:t.store.location,session:await r.store.sessions.get(r.id,e.sessionKey),messages:(await r.store.messages.page(r.id,e.sessionKey,{limit:i})).messages,turns:await r.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
332
+ `);for(let r of i)if(process.stdout.write(`${B(r.turnId,22)} ${B(r.status,9)} ${B(String(r.steps),5)} ${B(`${r.promptTokens}/${r.outputTokens}`,13)} ${B(String(r.durationMs??"-"),6)} ${r.source}
333
+ `),r.errorCode!==void 0){if(process.stdout.write(` ${r.errorCode}: ${r.errorMessage}
334
+ `),r.errorHint!==void 0)process.stdout.write(` hint: ${r.errorHint}
335
+ `)}}async function Jo(e){let t=await pe.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});H(()=>t.stop("cli-exit"));let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ho;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await s.store.messages.count(s.id,e.sessionKey);return await s.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
336
+ `),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:t.store.location,sessions:await s.sessions()}:{store:t.store.location,session:await s.store.sessions.get(s.id,e.sessionKey),messages:(await s.store.messages.page(s.id,e.sessionKey,{limit:i})).messages,turns:await s.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
324
337
  `),o}if(process.stdout.write(`store: ${t.store.location}
325
338
 
326
- `),e.sessionKey===void 0)return Ud(await r.sessions()),o;if(await r.store.sessions.get(r.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${r.id}
339
+ `),e.sessionKey===void 0)return qd(await s.sessions()),o;if(await s.store.sessions.get(s.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${s.id}
327
340
  hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
328
- `),E;if(e.turns===!0)await Md(r,e.sessionKey,i);else await Ld(r,e.sessionKey,i);return o}import{existsSync as Dd,readFileSync as Hd,writeFileSync as Gd}from"node:fs";import{basename as Wd,dirname as Bd,join as qd}from"node:path";var Vd=/^(#{1,6})\s+(.*)$/,Jd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Xd=/^[ \t]*<\/rules>[ \t]*$/,zd=/^\s*(?:```|~~~)/;function Wo(e){if(e.action!=="distill")throw new n({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${e.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let t;try{t=Hd(e.file,"utf8")}catch{throw new n({code:"cli_soul_file_missing",message:`${e.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let r=Wd(e.file),i=e.out??qd(Bd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(Dd(i))throw new n({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:s}=KA(r,t),a=Yd(r,s);return Gd(i,a,"utf8"),process.stdout.write(`wrote ${i}
341
+ `),E;if(e.turns===!0)await Jd(s,e.sessionKey,i);else await Vd(s,e.sessionKey,i);return o}import{existsSync as Xd,readFileSync as zd,writeFileSync as Yd}from"node:fs";import{basename as Qd,dirname as Zd,join as el}from"node:path";var nl=/^(#{1,6})\s+(.*)$/,tl=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,rl=/^[ \t]*<\/rules>[ \t]*$/,sl=/^\s*(?:```|~~~)/;function zo(e){if(e.action!=="distill")throw new n({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${e.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let t;try{t=zd(e.file,"utf8")}catch{throw new n({code:"cli_soul_file_missing",message:`${e.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let s=Qd(e.file),i=e.out??el(Zd(e.file),`${s.replace(/\.md$/i,"")}.compact.md`);if(Xd(i))throw new n({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:r}=HA(s,t),a=ol(s,r);return Yd(i,a,"utf8"),process.stdout.write(`wrote ${i}
329
342
 
330
- The scaffold copies ${r}'s headings and its <rules> blocks verbatim, and leaves a
343
+ The scaffold copies ${s}'s headings and its <rules> blocks verbatim, and leaves a
331
344
  {{PLACEHOLDER}} under each heading. Now:
332
345
  `+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
333
346
  `+` document's own voice. The workspace command warns until none are left.
334
347
  2. Name the file in context.soul.distilled.
335
- `),o}function Yd(e,t){let r=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,s=!1,a=0,d=!1;for(let l of t.split(`
336
- `)){if(zd.test(l)){if(i=!i,s)r.push(l);continue}if(i){if(s)r.push(l);continue}if(Jd.test(l)){s=!0,r.push(l);continue}if(s){if(r.push(l),Xd.test(l))s=!1,r.push("");continue}if(Vd.exec(l)!==null)d=!0,a+=1,r.push(l),r.push(""),r.push(`{{SECTION_${a}}}`),r.push("")}if(!d)r.push("{{ESSENCE}}"),r.push("");return`${r.join(`
348
+ `),o}function ol(e,t){let s=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,r=!1,a=0,d=!1;for(let l of t.split(`
349
+ `)){if(sl.test(l)){if(i=!i,r)s.push(l);continue}if(i){if(r)s.push(l);continue}if(tl.test(l)){r=!0,s.push(l);continue}if(r){if(s.push(l),rl.test(l))r=!1,s.push("");continue}if(nl.exec(l)!==null)d=!0,a+=1,s.push(l),s.push(""),s.push(`{{SECTION_${a}}}`),s.push("")}if(!d)s.push("{{ESSENCE}}"),s.push("");return`${s.join(`
337
350
  `).replace(/\n{3,}/g,`
338
351
 
339
352
  `).trimEnd()}
340
- `}var Qd=["list","add","remove","update","search"],Zd=12;async function qo(e){try{switch(e.action){case"list":return el(e);case"add":return nl(e);case"remove":return sl(e);case"update":return await rl(e);case"search":return await ol(e);default:throw new n({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Qd.join(", ")}.`})}}catch(t){if(h(t))return process.stdout.write(`${t.message}
353
+ `}var il=["list","add","remove","update","search"],al=12;async function Yo(e){try{switch(e.action){case"list":return dl(e);case"add":return ll(e);case"remove":return ul(e);case"update":return await fl(e);case"search":return await ml(e);default:throw new n({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${il.join(", ")}.`})}}catch(t){if(h(t))return process.stdout.write(`${t.message}
341
354
 
342
355
  ${t.hint}
343
- `),E;throw t}}function el(e){let r=He(e.env).map((i)=>{let s=gr(i.name,e.env);return{...i,cached:ft(i.name,e.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:Ao(e.env),sources:r},null,2)}
344
- `),o;if(r.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
356
+ `),E;throw t}}function dl(e){let s=He(e.env).map((i)=>{let r=ar(i.name,e.env);return{...i,cached:pt(i.name,e.env),commit:r.commit,fetchedAt:r.fetchedAt,skills:r.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:to(e.env),sources:s},null,2)}
357
+ `),o;if(s.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
345
358
 
346
- \`sources add <name> <url>\` to add one, or \`sources add ${kA[0]?.name??"anthropic"} ${kA[0]?.url??""}\` to put a built-in back.
347
- `),o;process.stdout.write(L("sources",!0));for(let i of r)process.stdout.write(`
348
- ${w(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
349
- `),process.stdout.write(S(C([{label:"url",value:i.url},...i.path===void 0?[]:[{label:"path",value:i.path}],...i.ref===void 0?[]:[{label:"branch",value:i.ref}],{label:"cached",value:i.cached?`${i.skills??"?"} skills at ${i.commit??"?"}, fetched ${i.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
359
+ \`sources add <name> <url>\` to add one, or \`sources add ${_A[0]?.name??"anthropic"} ${_A[0]?.url??""}\` to put a built-in back.
360
+ `),o;process.stdout.write(L("sources",!0));for(let i of s)process.stdout.write(`
361
+ ${D(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
362
+ `),process.stdout.write(w(p([{label:"url",value:i.url},...i.path===void 0?[]:[{label:"path",value:i.path}],...i.ref===void 0?[]:[{label:"branch",value:i.ref}],{label:"cached",value:i.cached?`${i.skills??"?"} skills at ${i.commit??"?"}, fetched ${i.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
350
363
  ${L("registry")}
351
- ${S(Ao(e.env))}
352
- `),o}function nl(e){let[t,r]=e.rest;if(t===void 0)throw new n({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=r!==void 0,s=i?r:t,a=ar(s),d=i?t:tl(a.url);if(!vA(d))throw new n({code:"sources_name_invalid",message:`${JSON.stringify(d)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let l=He(e.env).find((f)=>f.name===d);if(l!==void 0&&!i)throw new n({code:"sources_name_taken",message:`${d} is already a source, pointing at ${l.url}`,hint:`Give this one its own name: \`sources add <name> ${s}\`.`});let u=e.path??a.path,p=e.ref??a.ref,c={name:d,url:a.url,...u===void 0?{}:{path:u},...p===void 0?{}:{ref:p}};if(Is(c,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:c},null,2)}
353
- `),o;return process.stdout.write(`${C([{label:l===void 0?"added":"replaced",value:d},{label:"url",value:c.url},...c.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:c.path}],...c.ref===void 0?[]:[{label:"branch",value:c.ref}]])}
364
+ ${w(to(e.env))}
365
+ `),o}function ll(e){let[t,s]=e.rest;if(t===void 0)throw new n({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=s!==void 0,r=i?s:t,a=sr(r),d=i?t:cl(a.url);if(!kA(d))throw new n({code:"sources_name_invalid",message:`${JSON.stringify(d)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let l=He(e.env).find((f)=>f.name===d);if(l!==void 0&&!i)throw new n({code:"sources_name_taken",message:`${d} is already a source, pointing at ${l.url}`,hint:`Give this one its own name: \`sources add <name> ${r}\`.`});let u=e.path??a.path,g=e.ref??a.ref,c={name:d,url:a.url,...u===void 0?{}:{path:u},...g===void 0?{}:{ref:g}};if(cs(c,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:c},null,2)}
366
+ `),o;return process.stdout.write(`${p([{label:l===void 0?"added":"replaced",value:d},{label:"url",value:c.url},...c.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:c.path}],...c.ref===void 0?[]:[{label:"branch",value:c.ref}]])}
354
367
  `),process.stdout.write(`${L("next")}
355
- ${w(`sources update ${d}`)}
356
- ${w("sources search <what you need>")}
357
- `),o}function tl(e){let t=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(t[t.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function sl(e){let t=e.rest[0];if(t===void 0)throw new n({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=He(e.env).map((s)=>s.name);if(!ds(t,e.env)){let s=J(t,r);throw new n({code:"sources_unknown",message:`no source called ${t}`,hint:s===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${s}?`})}let i=kA.some((s)=>s.name===t);return process.stdout.write(`removed ${t}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
368
+ ${D(`sources update ${d}`)}
369
+ ${D("sources search <what you need>")}
370
+ `),o}function cl(e){let t=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(t[t.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ul(e){let t=e.rest[0];if(t===void 0)throw new n({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let s=He(e.env).map((r)=>r.name);if(!ls(t,e.env)){let r=J(t,s);throw new n({code:"sources_unknown",message:`no source called ${t}`,hint:r===void 0?`Configured: ${s.join(", ")||"none"}.`:`Did you mean ${r}?`})}let i=_A.some((r)=>r.name===t);return process.stdout.write(`removed ${t}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
358
371
  `),process.stdout.write(`
359
372
  The cached copy is left on disk; nothing already installed into an agent is touched.
360
- `),o}async function rl(e){let t=He(e.env),r=e.rest.length===0?t:e.rest.map((a)=>{let d=t.find((l)=>l.name===a);if(d===void 0){let l=J(a,t.map((u)=>u.name));throw new n({code:"sources_unknown",message:`no source called ${a}`,hint:l===void 0?`Configured: ${t.map((u)=>u.name).join(", ")||"none"}.`:`Did you mean ${l}?`})}return d});if(r.length===0)return process.stdout.write(`no sources configured
373
+ `),o}async function fl(e){let t=He(e.env),s=e.rest.length===0?t:e.rest.map((a)=>{let d=t.find((l)=>l.name===a);if(d===void 0){let l=J(a,t.map((u)=>u.name));throw new n({code:"sources_unknown",message:`no source called ${a}`,hint:l===void 0?`Configured: ${t.map((u)=>u.name).join(", ")||"none"}.`:`Did you mean ${l}?`})}return d});if(s.length===0)return process.stdout.write(`no sources configured
361
374
 
362
375
  \`sources add <url>\` to add one.
363
- `),o;let i=[],s=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let d=await LA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:d.commit,skills:d.skills}),e.json!==!0)process.stdout.write(`${d.skills} skills at ${d.commit}${d.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
364
- `)}catch(d){let l=d instanceof Error?d.message:String(d);if(s.push({name:a.name,reason:l}),e.json!==!0)process.stdout.write(`failed
365
- `);if(e.json!==!0&&h(d))process.stdout.write(`${S(d.message)}
366
- ${S(d.hint,4)}
367
- `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:s},null,2)}
368
- `);return i.length===0?E:o}async function ol(e){let t=e.rest.join(" ").trim(),r=He(e.env);if(r.length===0)return process.stdout.write(`no sources configured
376
+ `),o;let i=[],r=[];for(let a of s){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let d=await vA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:d.commit,skills:d.skills}),e.json!==!0)process.stdout.write(`${d.skills} skills at ${d.commit}${d.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
377
+ `)}catch(d){let l=d instanceof Error?d.message:String(d);if(r.push({name:a.name,reason:l}),e.json!==!0)process.stdout.write(`failed
378
+ `);if(e.json!==!0&&h(d))process.stdout.write(`${w(d.message)}
379
+ ${w(d.hint,4)}
380
+ `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:r},null,2)}
381
+ `);return i.length===0?E:o}async function ml(e){let t=e.rest.join(" ").trim(),s=He(e.env);if(s.length===0)return process.stdout.write(`no sources configured
369
382
 
370
383
  \`sources add <url>\` to add one.
371
- `),E;let i=r.filter((l)=>!ft(l.name,e.env));for(let l of i){if(e.json!==!0)process.stdout.write(`fetching ${l.name} for the first time … `);try{let u=await LA(l,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${u.skills} skills
384
+ `),E;let i=s.filter((l)=>!pt(l.name,e.env));for(let l of i){if(e.json!==!0)process.stdout.write(`fetching ${l.name} for the first time … `);try{let u=await vA(l,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${u.skills} skills
372
385
  `)}catch(u){if(e.json!==!0){if(process.stdout.write(`failed
373
- `),h(u))process.stdout.write(`${S(u.message)}
374
- `)}}}let s=r.flatMap((l)=>Kt(l,e.env));if(s.length===0)return process.stdout.write(`
386
+ `),h(u))process.stdout.write(`${w(u.message)}
387
+ `)}}}let r=s.flatMap((l)=>Ht(l,e.env));if(r.length===0)return process.stdout.write(`
375
388
  nothing to search — no source has been fetched successfully
376
389
 
377
390
  \`sources update\` reports why.
378
- `),E;let a=t.length===0?s:il(t,s);if(a.length===0)return process.stdout.write(`
379
- nothing in ${s.length} skills across ${r.length} sources matches ${JSON.stringify(t)}
391
+ `),E;let a=t.length===0?r:pl(t,r);if(a.length===0)return process.stdout.write(`
392
+ nothing in ${r.length} skills across ${s.length} sources matches ${JSON.stringify(t)}
380
393
 
381
394
  Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
382
- `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:t,searched:s.length,results:a.map((l)=>({source:l.source,skill:l.skill,description:l.description,tokens:l.tokens,scripts:l.scripts.length,repoPath:l.repoPath,...l.problem===void 0?{}:{problem:l.problem}}))},null,2)}
383
- `),o;let d=a.slice(0,Zd);process.stdout.write(`
384
- ${L(t.length===0?`${s.length} skills`:`${a.length} of ${s.length} skills match ${JSON.stringify(t)}`,!0)}
385
- `);for(let l of d){process.stdout.write(`${w(`${l.source}/${l.skill}`)} ${l.tokens} tokens${l.scripts.length===0?"":`, ${l.scripts.length} runnable file${l.scripts.length===1?"":"s"}`}${l.problem===void 0?"":" — will not load"}
386
- `);let u=l.problem??l.description;process.stdout.write(`${S(u.length>160?`${u.slice(0,157)}…`:u,4)}
395
+ `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:t,searched:r.length,results:a.map((l)=>({source:l.source,skill:l.skill,description:l.description,tokens:l.tokens,scripts:l.scripts.length,repoPath:l.repoPath,...l.problem===void 0?{}:{problem:l.problem}}))},null,2)}
396
+ `),o;let d=a.slice(0,al);process.stdout.write(`
397
+ ${L(t.length===0?`${r.length} skills`:`${a.length} of ${r.length} skills match ${JSON.stringify(t)}`,!0)}
398
+ `);for(let l of d){process.stdout.write(`${D(`${l.source}/${l.skill}`)} ${l.tokens} tokens${l.scripts.length===0?"":`, ${l.scripts.length} runnable file${l.scripts.length===1?"":"s"}`}${l.problem===void 0?"":" — will not load"}
399
+ `);let u=l.problem??l.description;process.stdout.write(`${w(u.length>160?`${u.slice(0,157)}…`:u,4)}
387
400
  `)}if(a.length>d.length)process.stdout.write(`
388
- ${S(`… and ${a.length-d.length} more; narrow the query or use --json`)}
401
+ ${w(`… and ${a.length-d.length} more; narrow the query or use --json`)}
389
402
  `);return process.stdout.write(`
390
403
  ${L("install")}
391
- ${S(`skills install <agent> ${d[0]?.source}/${d[0]?.skill}`)}
392
- `),o}function il(e,t){let r=new Map,i=t.map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return qA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}async function Vo(e){let t=al(e.manifestPath),r=await sr(t,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await ir(t,!0,void 0,e.store);let s=await ze(e.store),a=!1;if(s===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)i.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let d=await Ct(s,`/v1/agents/${encodeURIComponent(t)}/start`,{},e.manifestPath);if(d.ok)a=!0,i.push(`adopted by pid ${s.pid}, live now`);else if(d.status===501)i.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(d.status===401)i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${s.pid} could not adopt it${d.detail===void 0?"":`: ${d.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:t,enabled:!0,running:a,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:i.join(" · ")}]},null,2)}
393
- `);else if(process.stdout.write(`${C([{label:t,value:a?"running":"switched on",note:i.join(" · ")}])}
394
- `),!a&&s!==void 0&&s.baseUrl!==void 0)process.stdout.write(`
404
+ ${w(`skills install <agent> ${d[0]?.source}/${d[0]?.skill}`)}
405
+ `),o}function pl(e,t){let s=new Map,i=t.map((r)=>{let a=`${r.source}/${r.skill}`;return s.set(a,r),{name:a,dir:r.dir,tokens:r.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:r.description,metadata:{}}}});return JA(e,i).filter((r)=>r.score>0).map((r)=>s.get(r.skill.name)).filter((r)=>r!==void 0)}async function Zo(e){let t=hl(e.manifestPath),s=await ir(t,e.store),i=[];if(s?.enabled===!0)i.push("was already switched on");await rr(t,!0,void 0,e.store);let r=await ze(e.store),a=!1;if(r===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(r.baseUrl===void 0)i.push(`pid ${r.pid} is a ${r.mode} session, which serves no HTTP to adopt into`);else{let d=await ft(r,`/v1/agents/${encodeURIComponent(t)}/start`,{},e.manifestPath);if(d.ok)a=!0,i.push(`adopted by pid ${r.pid}, live now`);else if(d.status===501)i.push(`pid ${r.pid} cannot look up manifests — restart it to pick this up`);else if(d.status===401)i.push(`pid ${r.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${r.pid} could not adopt it${d.detail===void 0?"":`: ${d.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:t,enabled:!0,running:a,...r===void 0?{}:{pid:r.pid,mode:r.mode},note:i.join(" · ")}]},null,2)}
406
+ `);else if(process.stdout.write(`${p([{label:t,value:a?"running":"switched on",note:i.join(" · ")}])}
407
+ `),!a&&r!==void 0&&r.baseUrl!==void 0)process.stdout.write(`
395
408
  Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
396
- `);return s!==void 0&&s.baseUrl!==void 0&&!a?E:o}function al(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_start_agent_id_missing",message:`${e} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return t.id}async function Jo(e){let t=await xn(e.store),r=new Map;for(let a of t){if(a.serving===void 0)continue;let d=await an(a.manifestPath,e.store);if(d!==void 0)r.set(a.ref,d)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:t.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
397
- `),o;let i=await Ut({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${C(Tn(t))}
398
- `);let s=[];for(let[a,d]of r)for(let l of d.values())s.push({label:`${a} / ${l.id}`,value:l.status,note:l.input!==void 0?`${l.detail??"enter this code"}: ${l.input.payload}`:l.detail??""});if(s.length>0)process.stdout.write(`
399
- ${C(s)}
400
- `);return i}import{copyFileSync as dl,existsSync as ll,mkdirSync as cl,readFileSync as ul,writeFileSync as fl}from"node:fs";import{dirname as ml,join as zo}from"node:path";async function Yo(e){let t=e.env??v([]),r=e.home??t.HOME??"",i=dn(t),s=mn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:zo(r,s.configPath),line:s?.line,steps:s?.steps},null,2)}
401
- `),s===void 0?E:o;if(process.stdout.write(`${L("shift+enter",!0)}
402
- ${S("⌥ or ⇧ ⏎ already puts a new line in a message, everywhere, with no setup. This command is for shift+⏎, which a terminal can only send once it has been given a key binding.")}
403
- `),s===void 0)return process.stdout.write(`
409
+ `);return r!==void 0&&r.baseUrl!==void 0&&!a?E:o}function hl(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_start_agent_id_missing",message:`${e} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return t.id}async function ei(e){let t=await In(e.store),s=new Map;for(let a of t){if(a.serving===void 0)continue;let d=await sn(a.manifestPath,e.store);if(d!==void 0)s.set(a.ref,d)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:t.map((a)=>({...a,channels:[...s.get(a.ref)?.values()??[]]}))},null,2)}
410
+ `),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${p(On(t))}
411
+ `);let r=[];for(let[a,d]of s)for(let l of d.values())r.push({label:`${a} / ${l.id}`,value:l.status,note:l.input!==void 0?`${l.detail??"enter this code"}: ${l.input.payload}`:l.detail??""});if(r.length>0)process.stdout.write(`
412
+ ${p(r)}
413
+ `);return i}import{copyFileSync as gl,existsSync as yl,mkdirSync as wl,readFileSync as bl,writeFileSync as $l}from"node:fs";import{dirname as vl,join as ni}from"node:path";async function ti(e){let t=e.env??v([]),s=e.home??t.HOME??"",i=hn(t),r=wn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:r?.how??"unknown",configPath:r?.configPath===void 0?void 0:ni(s,r.configPath),line:r?.line,steps:r?.steps},null,2)}
414
+ `),r===void 0?E:o;if(process.stdout.write(`${L("shift+enter",!0)}
415
+ ${w("⌥ or ⇧ ⏎ already puts a new line in a message, everywhere, with no setup. This command is for shift+⏎, which a terminal can only send once it has been given a key binding.")}
416
+ `),r===void 0)return process.stdout.write(`
404
417
  ${L("this terminal was not recognised")}
405
- ${S(`TERM_PROGRAM=${t.TERM_PROGRAM??"(unset)"} TERM=${t.TERM??"(unset)"}`)}
406
- ${S(`known: ${Qt().map((a)=>a.name).join(", ")}`)}
407
- ${w("⌥⏎ works here regardless — nothing needs configuring for it")}
418
+ ${w(`TERM_PROGRAM=${t.TERM_PROGRAM??"(unset)"} TERM=${t.TERM??"(unset)"}`)}
419
+ ${w(`known: ${or().map((a)=>a.name).join(", ")}`)}
420
+ ${D("⌥⏎ works here regardless — nothing needs configuring for it")}
408
421
  `),E;if(process.stdout.write(`
409
- ${L(s.name)}
410
- `),s.how!=="write"){process.stdout.write(`${S(s.how==="unverified"?`no verified recipe for this one — ${s.reason??"nobody has checked it"}`:`this one has to be done by hand — ${s.reason??"its settings are not a text file"}`)}
422
+ ${L(r.name)}
423
+ `),r.how!=="write"){process.stdout.write(`${w(r.how==="unverified"?`no verified recipe for this one — ${r.reason??"nobody has checked it"}`:`this one has to be done by hand — ${r.reason??"its settings are not a text file"}`)}
411
424
 
412
- `);for(let[a,d]of(s.steps??[]).entries())process.stdout.write(`${S(`${a+1}. ${d}`)}
413
- `);return process.stdout.write(s.how==="unverified"?`
414
- ${w("⌥⏎ works here today — nothing has to be configured for it")}
425
+ `);for(let[a,d]of(r.steps??[]).entries())process.stdout.write(`${w(`${a+1}. ${d}`)}
426
+ `);return process.stdout.write(r.how==="unverified"?`
427
+ ${D("⌥⏎ works here today — nothing has to be configured for it")}
415
428
  `:`
416
- ${w("then restart the terminal and press shift+⏎ in a session to check it")}
417
- `),o}return await pl(s,{...e,env:t,home:r})}async function pl(e,t){let r=zo(t.home,e.configPath??""),i=ll(r)?ul(r,"utf8"):"";if(as(i,e))return process.stdout.write(`${S("already configured — a binding for shift+enter is present")}
418
- ${S(iA(r,t.home),4)}
419
- `),o;let s=fs(i,e);if(s===void 0)return process.stdout.write(`${S("this file is not in a shape this command can edit safely:")}
420
- ${S(iA(r,t.home),4)}
421
- ${w("add the line below by hand:")}
422
- ${S(e.line??"",4)}
423
- `),E;if(process.stdout.write(`${C([{label:"file",value:iA(r,t.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
429
+ ${D("then restart the terminal and press shift+⏎ in a session to check it")}
430
+ `),o}return await Sl(r,{...e,env:t,home:s})}async function Sl(e,t){let s=ni(t.home,e.configPath??""),i=yl(s)?bl(s,"utf8"):"";if(mr(i,e))return process.stdout.write(`${w("already configured — a binding for shift+enter is present")}
431
+ ${w(rA(s,t.home),4)}
432
+ `),o;let r=hr(i,e);if(r===void 0)return process.stdout.write(`${w("this file is not in a shape this command can edit safely:")}
433
+ ${w(rA(s,t.home),4)}
434
+ ${D("add the line below by hand:")}
435
+ ${w(e.line??"",4)}
436
+ `),E;if(process.stdout.write(`${p([{label:"file",value:rA(s,t.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
424
437
  `),t.dryRun===!0)return process.stdout.write(`
425
- ${w("--dry-run: nothing was written")}
438
+ ${D("--dry-run: nothing was written")}
426
439
  `),o;if(t.yes!==!0){if(!(t.confirm===void 0?!1:await t.confirm("write this change?")))return process.stdout.write(`
427
- ${w("nothing was written")}
428
- `),o}try{if(cl(ml(r),{recursive:!0}),i!=="")dl(r,`${r}.${A.slug}-backup`);fl(r,s,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
440
+ ${D("nothing was written")}
441
+ `),o}try{if(wl(vl(s),{recursive:!0}),i!=="")gl(s,`${s}.${A.slug}-backup`);$l(s,r,"utf8")}catch(a){return process.stderr.write(`could not write ${s}: ${a instanceof Error?a.message:String(a)}
429
442
  `),E}return process.stdout.write(`
430
443
  ${L("done")}
431
- ${i===""?"":`${S(`a copy of the old file is at ${iA(`${r}.${A.slug}-backup`,t.home)}`)}
432
- `}${w("restart the terminal, then press shift+⏎ in a session to check it")}
433
- `),o}async function Zo(e){return e.warm===!0?await hl(e):await gl(e)}async function hl(e){let t=z(e.manifestPath,{env:v([e.manifestPath])}),r=Bt(t.manifest.tools).selections,i=t.manifest.tools.pinned;if(r.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
434
- `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((l)=>l.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
435
- `),o;let s=[],a=new Set;for(let l of r){let u=ae[l.id];if(u===void 0)return E;let p;try{let c=u({dir:t.dir,env:t.env,config:l.config,agentId:t.manifest.id});if(c.refresh===void 0){for(let f of await c.resolve(i))a.add(f.spec.slug);if(e.json!==!0)process.stdout.write(`${l.id}: nothing to warm — it resolves without a cache.
436
- `);continue}p=await c.refresh(i)}catch(c){let f=h(c)?`${c.message}
444
+ ${i===""?"":`${w(`a copy of the old file is at ${rA(`${s}.${A.slug}-backup`,t.home)}`)}
445
+ `}${D("restart the terminal, then press shift+⏎ in a session to check it")}
446
+ `),o}async function ri(e){return e.warm===!0?await kl(e):await Pl(e)}async function kl(e){let t=z(e.manifestPath,{env:v([e.manifestPath])}),s=Bt(t.manifest.tools).selections,i=t.manifest.tools.pinned;if(s.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
447
+ `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${s.map((l)=>l.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
448
+ `),o;let r=[],a=new Set;for(let l of s){let u=ae[l.id];if(u===void 0)return E;let g;try{let c=u({dir:t.dir,env:t.env,config:l.config,agentId:t.manifest.id});if(c.refresh===void 0){for(let f of await c.resolve(i))a.add(f.spec.slug);if(e.json!==!0)process.stdout.write(`${l.id}: nothing to warm — it resolves without a cache.
449
+ `);continue}g=await c.refresh(i)}catch(c){let f=h(c)?`${c.message}
437
450
  hint: ${c.hint}`:c instanceof Error?c.message:String(c);process.stdout.write(`${l.id}: not warmed — ${f}
438
- `);continue}for(let c of i)if(!p.missing.includes(c))a.add(c);s.push({provider:l.id,fetched:p.fetched,changed:[...p.changed],missing:[...p.missing],cachePath:"cachePath"in p&&typeof p.cachePath==="string"?p.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(s,null,2)}
439
- `);else for(let l of s){if(process.stdout.write(`${l.fetched} of ${i.length} pinned tools fetched from ${l.provider}
451
+ `);continue}for(let c of i)if(!g.missing.includes(c))a.add(c);r.push({provider:l.id,fetched:g.fetched,changed:[...g.changed],missing:[...g.missing],cachePath:"cachePath"in g&&typeof g.cachePath==="string"?g.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(r,null,2)}
452
+ `);else for(let l of r){if(process.stdout.write(`${l.fetched} of ${i.length} pinned tools fetched from ${l.provider}
440
453
  `),l.changed.length>0)process.stdout.write(` changed: ${l.changed.join(", ")}
441
454
  `);if(l.cachePath!=="")process.stdout.write(` cache: ${l.cachePath}
442
455
  `)}let d=i.filter((l)=>!a.has(l));for(let l of d)process.stdout.write(` missing: ${l} — no configured provider has a tool with that slug
443
- `);return d.length>0?E:o}async function gl(e){let t=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});try{let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=er(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
444
- `:`${bA(i)}
445
- `),o}finally{await t.stop("cli-exit")}}import{dirname as ei,isAbsolute as yl,resolve as En}from"node:path";async function ni(e){try{let t=U(e.manifestPath),r=await bo({refs:t.plugins??[],agentId:t.id??e.manifestPath,paths:{workspace:ei(En(e.manifestPath)),state:ei(En(e.manifestPath)),manifest:En(e.manifestPath)},env:v([e.manifestPath]),bus:new bt({runtimeId:"validate"}),builtIn:Qe,pluginRoot:ge(),base:{toolProviders:ae,modelTransports:be,mediaProviders:Ee,channels:Ie}}),i=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:s}=i,a=Se(s.model.main.id,s.model.main.capabilities),{workspace:d,warnings:l}=EA(i,a.promptStyle),u=Mo(No(i,{channels:r.channels})),p=await Qn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let b of p.providers)await b.stop?.();let c=Bo(s,{env:i.env,transports:new Map([...lA,...Object.entries(r.modelTransports)])});jA(s,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let f=eA(d,s.context.rules);if(f!==void 0&&s.context.rules.onExceed==="fail")throw f;let m=[...l,...r.failed,...p.warnings,...p.registry.warnings,...u,...mo(s),...Qo(s),...f===void 0?[]:[f.toDetail()]],g=s.knowledge===void 0?void 0:Oo({dir:yl(s.knowledge.dir)?s.knowledge.dir:En(i.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:a.promptStyle}),R=["static","volatile","reminder"].map((b)=>{let x=d.files.filter((I)=>I.tier===b).map((I)=>I.name);if(x.length===0)return;return`${b}=${x.join(",")} (${d.tokens[b]}/${s.context.budgets[b]})`}).filter((b)=>b!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:s.id,model:s.model.main.id,window:i.window,capabilities:a,workspace:{files:d.files.map((b)=>({name:b.name,tier:b.tier,editable:b.editable,tokens:b.tokens,budget:b.budget})),tokens:d.tokens},knowledge:g===void 0?[]:g.entries.map((b)=>({name:b.name,keywords:b.keywords,tokens:b.tokens})),warnings:m},null,2)}
446
- `),o;let P=Mt(s),y=P.map((b)=>b.role===b.configuredAs?`${b.role}=${b.modelId}`:`${b.role}=→main`).join(" "),j=P.filter((b)=>b.role===b.configuredAs),D=es({manifestPath:e.manifestPath,rawModelId:t.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((b)=>{let x=Xi(b.origin);return x===void 0?[]:[` env ${b.variable} — ${x}
456
+ `);return d.length>0?E:o}async function Pl(e){let t=await pe.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:fe(),channels:Ie,env:v([e.manifestPath])});try{let s=t.list()[0];if(s===void 0)throw Error("The manifest produced no agent.");let i=Xo(s);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
457
+ `:`${DA(i)}
458
+ `),o}finally{await t.stop("cli-exit")}}import{dirname as oi,isAbsolute as El,resolve as Tn}from"node:path";async function di(e){try{let t=U(e.manifestPath),s=await Do({refs:t.plugins??[],agentId:t.id??e.manifestPath,paths:{workspace:oi(Tn(e.manifestPath)),state:oi(Tn(e.manifestPath)),manifest:Tn(e.manifestPath)},env:v([e.manifestPath]),bus:new bt({runtimeId:"validate"}),builtIn:Qe,pluginRoot:ge(),base:{toolProviders:ae,modelTransports:be,mediaProviders:Ee,channels:Ie}}),i=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:r}=i,a=Se(r.model.main.id,r.model.main.capabilities),{workspace:d,warnings:l}=uA(i,a.promptStyle),u=No(Oo(i,{channels:s.channels})),g=await yn(i,{toolProviders:s.toolProviders,modelTransports:s.modelTransports,mediaProviders:s.mediaProviders,channels:s.channels,scriptRunner:s.scriptRunner,middleware:s.middleware});for(let S of g.providers)await S.stop?.();let c=ho(r,{env:i.env,transports:new Map([...cA,...Object.entries(s.modelTransports)])});YA(r,{env:i.env,providers:new Map(Object.entries(s.mediaProviders))});let f=Xt(d,r.context.rules);if(f!==void 0&&r.context.rules.onExceed==="fail")throw f;let m=[...l,...s.failed,...g.warnings,...g.registry.warnings,...u,...Qo(r),...yo(r),...f===void 0?[]:[f.toDetail()]],y=r.knowledge===void 0?void 0:bo({dir:El(r.knowledge.dir)?r.knowledge.dir:Tn(i.dir,r.knowledge.dir),maxActive:r.knowledge.maxActive,budget:r.knowledge.budget,style:a.promptStyle}),R=["static","volatile","reminder"].map((S)=>{let P=d.files.filter((I)=>I.tier===S).map((I)=>I.name);if(P.length===0)return;return`${S}=${P.join(",")} (${d.tokens[S]}/${r.context.budgets[S]})`}).filter((S)=>S!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:r.id,model:r.model.main.id,window:i.window,capabilities:a,workspace:{files:d.files.map((S)=>({name:S.name,tier:S.tier,editable:S.editable,tokens:S.tokens,budget:S.budget})),tokens:d.tokens},knowledge:y===void 0?[]:y.entries.map((S)=>({name:S.name,keywords:S.keywords,tokens:S.tokens})),warnings:m},null,2)}
459
+ `),o;let T=Nt(r),b=T.map((S)=>S.role===S.configuredAs?`${S.role}=${S.modelId}`:`${S.role}=→main`).join(" "),N=T.filter((S)=>S.role===S.configuredAs),M=$i({manifestPath:e.manifestPath,rawModelId:t.modelId,apiKeyEnv:r.model.main.apiKeyEnv}).flatMap((S)=>{let P=Zi(S.origin);return P===void 0?[]:[` env ${S.variable} — ${P}
447
460
  `]}).join("");return process.stdout.write(`ok ${i.path}
448
- id ${s.id}${s.name===void 0?"":` (${s.name})`}
449
- models ${y}
450
- `+D+` window ${i.window} ${cA(P[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${a.maxOutput})
451
- `+(j.length<2?"":`${j.slice(1).map((b)=>` ${b.role.padEnd(12)} ${b.modelId} · window ${b.window.contextWindow} ${cA(b.window)}
461
+ id ${r.id}${r.name===void 0?"":` (${r.name})`}
462
+ models ${b}
463
+ `+M+` window ${i.window} ${gA(T[0]?.window)} (reserveOutput ${r.context.reserveOutput}, maxOutput ${a.maxOutput})
464
+ `+(N.length<2?"":`${N.slice(1).map((S)=>` ${S.role.padEnd(12)} ${S.modelId} · window ${S.window.contextWindow} ${gA(S.window)}
452
465
  `).join("")}`)+` capabilities thinking=${c.main.capabilities.thinking} promptCache=${c.main.capabilities.promptCache} nativeTools=${c.main.capabilities.nativeTools} strictSchema=${c.main.capabilities.strictSchema}
453
- `+wl(c.main.capabilities.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
466
+ `+Rl(c.main.capabilities.promptCache,r.model.main.id)+` dialect ${r.tools.dialect}
454
467
  workspace ${R===""?"(none)":R}
455
- `+(g===void 0?"":` knowledge ${g.entries.length} entries, maxActive=${g.maxActive}, budget=${g.budget}
456
- `)+` memory ${s.memory===void 0?"none — nothing is retrieved across sessions":`${s.memory.retriever} at ${s.memory.dir}, maxActive=${s.memory.maxActive}, threshold=${s.memory.threshold}, budget=${s.memory.budget}, history=${s.memory.includeHistory}`}
457
- schedules ${s.schedules.length===0?"none":s.schedules.map((b)=>`${b.id} (${b.kind} ${b.expr}${b.timezone===void 0?"":` ${b.timezone}`}${b.role===void 0?"":` role=${b.role}`}${b.enabled?"":", disabled"})`).join(" ")}
458
- team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((b)=>`${b.id} (${b.manifest})`).join(" ")} — run one at a time`}
459
- limits maxSteps=${s.limits.maxSteps} turnTimeoutMs=${s.limits.turnTimeoutMs}
460
- `+m.map((b)=>` warning ${b.message}
468
+ `+(y===void 0?"":` knowledge ${y.entries.length} entries, maxActive=${y.maxActive}, budget=${y.budget}
469
+ `)+` memory ${r.memory===void 0?"none — nothing is retrieved across sessions":`${r.memory.retriever} at ${r.memory.dir}, maxActive=${r.memory.maxActive}, threshold=${r.memory.threshold}, budget=${r.memory.budget}, history=${r.memory.includeHistory}`}
470
+ schedules ${r.schedules.length===0?"none":r.schedules.map((S)=>`${S.id} (${S.kind} ${S.expr}${S.timezone===void 0?"":` ${S.timezone}`}${S.role===void 0?"":` role=${S.role}`}${S.enabled?"":", disabled"})`).join(" ")}
471
+ team ${r.team===void 0?"none — no delegation; `handoff` is not registered":`${r.team.members.map((S)=>`${S.id} (${S.manifest})`).join(" ")} — run one at a time`}
472
+ limits maxSteps=${r.limits.maxSteps} turnTimeoutMs=${r.limits.turnTimeoutMs}
473
+ `+m.map((S)=>` warning ${S.message}
461
474
  `).join("")),o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
462
- `),E;throw t}}function wl(e,t){if(e!=="none")return"";return/(^|\/)claude-/i.test(t)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
475
+ `),E;throw t}}function Rl(e,t){if(e!=="none")return"";return/(^|\/)claude-/i.test(t)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
463
476
  `+` caching at all, so no request field reaches it. Caching lives on the native
464
477
  Messages API, which this runtime does not speak.
465
478
  `:` promptCache none — this runtime sends no cache directives. Many endpoints cache
466
- `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function ti(e){try{let t=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:r}=t,i=Se(r.model.main.id,r.model.main.capabilities),{workspace:s,warnings:a}=EA(t,i.promptStyle),d=[...a,...yi(s.files.map((p)=>({name:p.name,authored:p.authored,tier:p.tier,field:p.field})))],l=eA(s,r.context.rules);if(l!==void 0)d.push(l.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:d.length===0,path:t.path,promptStyle:i.promptStyle,files:s.files.map((p)=>({name:p.name,tier:p.tier,editable:p.editable,tokens:p.tokens,budget:p.budget})),tokens:s.tokens,findings:d},null,2)}
479
+ `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function li(e){try{let t=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:s}=t,i=Se(s.model.main.id,s.model.main.capabilities),{workspace:r,warnings:a}=uA(t,i.promptStyle),d=[...a,...hi(r.files.map((g)=>({name:g.name,authored:g.authored,tier:g.tier,field:g.field})))],l=Xt(r,s.context.rules);if(l!==void 0)d.push(l.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:d.length===0,path:t.path,promptStyle:i.promptStyle,files:r.files.map((g)=>({name:g.name,tier:g.tier,editable:g.editable,tokens:g.tokens,budget:g.budget})),tokens:r.tokens,findings:d},null,2)}
467
480
  `),e.strict===!0&&d.length>0?E:o;let u=i.promptStyle;process.stdout.write(`${t.path}
468
481
  rendering delimiters=${u.delimiters} intensity=${u.intensity} examplesIn=${u.examplesIn}
469
- total ${s.tokens.total} tokens (static ${s.tokens.static}, volatile ${s.tokens.volatile}, reminder ${s.tokens.reminder})
470
- `);for(let p of s.files)process.stdout.write(` ${p.name.padEnd(14)} ${p.tier.padEnd(9)} ${String(p.tokens).padStart(5)}/${p.budget} tokens, editable=${p.editable}
482
+ total ${r.tokens.total} tokens (static ${r.tokens.static}, volatile ${r.tokens.volatile}, reminder ${r.tokens.reminder})
483
+ `);for(let g of r.files)process.stdout.write(` ${g.name.padEnd(14)} ${g.tier.padEnd(9)} ${String(g.tokens).padStart(5)}/${g.budget} tokens, editable=${g.editable}
471
484
  `);if(d.length===0)return process.stdout.write(`
472
485
  no findings
473
- `),o;for(let p of d)process.stdout.write(`
474
- ${p.code}: ${p.message}
475
- `),process.stdout.write(` hint: ${p.hint}
486
+ `),o;for(let g of d)process.stdout.write(`
487
+ ${g.code}: ${g.message}
488
+ `),process.stdout.write(` hint: ${g.hint}
476
489
  `);return process.stdout.write(`
477
490
  ${d.length} finding(s)
478
491
  `),e.strict===!0?E:o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
479
- `),E;throw t}}function bl(e){let t=ws(e);if(t!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${t} is not installed.
492
+ `),E;throw t}}function Tl(e){let t=kr(e);if(t!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${t} is not installed.
480
493
  hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${A.slug}), or pass --plain where the command has it.
481
494
  `),E;if(h(e))process.stderr.write(`${e.format()}
482
495
  `);else if(e instanceof Error){if(process.stderr.write(`${e.message}
483
- `),$t().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
496
+ `),Zt().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
484
497
  `)}else process.stderr.write(`${String(e)}
485
- `);return E}async function $l(e){let t=ss(e);switch(t.kind){case"version":return process.stdout.write(`${q}
486
- `),o;case"help":return process.stdout.write(Dn(t.command)),o;case"usage":return process.stdout.write(Dn()),E;case"command":break}let{command:r,positionals:i,flags:s}=t.parsed,a=i[0],d=()=>Ge(a),l=r.flags.some((c)=>c.name==="store")?s.str("store"):void 0,u=await nr({needsServer:r.needsServer,disabled:s.bool("no-bootstrap"),install:()=>or(),...l===void 0?{}:{store:l}}),p=OA(u);if(p!==void 0)process.stderr.write(p);switch(r.name){case"init":{let c=s.str("dir"),f=s.str("user"),m=s.str("name"),g=s.str("purpose"),R=s.str("preset"),P=s.str("model"),y=s.str("base-url"),j=s.str("region"),D=s.str("api-key-env"),b=s.str("system"),x=s.str("web"),I=s.str("web-backend"),_=s.str("composio"),F=s.str("telegram"),V=s.str("telegram-allow"),N=s.str("whatsapp"),Z=s.str("whatsapp-number"),K=s.str("server"),Le=s.str("schedules"),$e=s.str("skills"),te=s.str("daemon");return await Wt({...c===void 0?{}:{dir:c},...f===void 0?{}:{user:f},...m===void 0?{}:{name:m},...g===void 0?{}:{purpose:g},...R===void 0?{}:{preset:R},...P===void 0?{}:{model:P},...y===void 0?{}:{baseUrl:y},...j===void 0?{}:{region:j},...D===void 0?{}:{apiKeyEnv:D},...b===void 0?{}:{system:b},...x===void 0?{}:{web:x},...I===void 0?{}:{webBackend:I},..._===void 0?{}:{composio:_},...F===void 0?{}:{telegram:F},...Le===void 0?{}:{schedules:Le},...V===void 0?{}:{telegramAllow:V},...N===void 0?{}:{whatsapp:N},...Z===void 0?{}:{whatsappNumber:Z},...K===void 0?{}:{server:K},...$e===void 0?{}:{skills:$e},...te===void 0?{}:{daemon:te},yes:s.bool("yes"),plain:s.bool("plain"),measureWindow:s.bool("measure-window"),installServer:or})}case"run":{let c=s.str("session"),f=s.str("input"),m=s.str("store");return await rt({...i[0]===void 0?{}:{manifestPath:d()},...c===void 0?{}:{sessionKey:c},continueSession:s.bool("continue"),...f===void 0?{}:{once:f},...m===void 0?{}:{store:m},ephemeral:s.bool("ephemeral"),quiet:s.bool("quiet"),showReasoning:s.bool("show-reasoning"),noReasoning:s.bool("no-reasoning"),...s.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:s.bool("plain")})}case"schedules":{let c=s.str("store"),f=s.str("id"),m=s.str("enable"),g=s.str("disable");return await go({manifestPath:d(),...c===void 0?{}:{store:c},...f===void 0?{}:{id:f},...m===void 0?{}:{enable:m},...g===void 0?{}:{disable:g},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let c=s.str("session"),f=s.str("store"),m=s.num("limit");return await Ho({manifestPath:d(),...c===void 0?{}:{sessionKey:c},...f===void 0?{}:{store:f},...m===void 0?{}:{limit:m},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"owner":{let c=s.str("store");return await Ws({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{store:c},json:s.bool("json")})}case"memory":{let c=s.num("limit"),f=s.str("store");return await Ps({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...c===void 0?{}:{limit:c},...f===void 0?{}:{store:f},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:c,readAction:f}=await import("./config-3mz4zwsf.js"),m=f(a,i[1]);return await c({action:m.action,...m.ref===void 0?{}:{ref:m.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...s.str("channel")===void 0?{}:{channel:s.str("channel")},remove:s.bool("remove"),yes:s.bool("yes"),...s.str("store")===void 0?{}:{store:s.str("store")}})}case"validate":return await ni({manifestPath:d(),json:s.bool("json")});case"workspace":return ti({manifestPath:d(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let c=s.str("out");return Wo({action:a,file:i[1],...c===void 0?{}:{out:c}})}case"skills":{if(i.length===0)return await Es({plain:s.bool("plain"),json:s.bool("json")});let c=i[2];return Yt({action:a,manifestPath:Ge(i[1]??""),...c===void 0?{}:{name:c},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let c=s.str("path"),f=s.str("ref");return await qo({action:a,rest:i.slice(1),...c===void 0?{}:{path:c},...f===void 0?{}:{ref:f},json:s.bool("json")})}case"channels":{let c=gs("channels",a),f=c.ref??i[1]??"",{channelsCommand:m}=await import("./channels-a9zx9yba.js");return await m({...c.action===void 0?{}:{action:c.action},manifestPath:Ge(f),...i[2]===void 0?{}:{channelId:i[2]},json:s.bool("json"),installServer:or})}case"plugins":{let c=s.str("ref"),f=s.str("name");return await mr({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...c===void 0?{}:{ref:c},...f===void 0?{}:{name:f},json:s.bool("json")})}case"agents":{let c=s.str("store");return await kt({manifestPaths:i.map((f)=>Ge(f)),...c===void 0?{}:{store:c},json:s.bool("json")})}case"restart":{let c=s.str("store");return await Mr({...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{store:c},json:s.bool("json")})}case"status":{let c=s.str("store");return await Jo({...c===void 0?{}:{store:c},json:s.bool("json")})}case"logs":{let c=s.num("lines"),f=s.str("store");return await Ut({action:"logs",...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{lines:c},follow:s.bool("follow"),truncate:s.bool("truncate"),...f===void 0?{}:{store:f},json:s.bool("json")})}case"serve":{let c=s.num("port"),f=s.str("host"),m=s.str("store");return await Lo({manifestPaths:i.map((g)=>Ge(g)),...c===void 0?{}:{port:c},...f===void 0?{}:{host:f},...m===void 0?{}:{store:m},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await ms({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await Yo({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:TA});case"remove":return await _r({...a===void 0?{}:{ref:a},dryRun:s.bool("dry-run"),filesOnly:s.bool("files-only"),prune:s.bool("prune"),all:s.bool("all"),yes:s.bool("yes"),json:s.bool("json"),...s.str("store")===void 0?{}:{store:s.str("store")},confirm:As});case"stop":{let c=s.str("reason");return await $n({...a===void 0?{}:{manifestPath:d()},dryRun:s.bool("dry-run"),...c===void 0?{}:{reason:c},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await Vo({manifestPath:d(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:c}=await import("./web-7mdrcb8a.js");return await c({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:c}=await import("./credential-ja7zmd4c.js");return await c({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...s.str("label")===void 0?{}:{label:s.str("label")},...s.str("agents")===void 0?{}:{agents:s.str("agents")},...s.str("sessions")===void 0?{}:{sessions:s.str("sessions")},...s.str("can")===void 0?{}:{can:s.str("can")},...s.str("expires")===void 0?{}:{expires:s.str("expires")},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"daemon":{let c=s.num("lines");return await Ut({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{lines:c},follow:s.bool("follow"),truncate:s.bool("truncate"),dryRun:s.bool("dry-run"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"model":{let c=s.num("price");return await Gs({manifestPath:Ge(i[1]),window:s.bool("window"),...c===void 0?{}:{price:c},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await Zo({manifestPath:d(),warm:s.bool("warm"),json:s.bool("json")});default:throw new n({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}vs();Bs();bs();await $l(process.argv.slice(2)).catch(bl).then((e)=>Ir(e));
498
+ `);return E}async function xl(e){let t=rs(e);switch(t.kind){case"version":return process.stdout.write(`${q}
499
+ `),o;case"help":return process.stdout.write(Bn(t.command)),o;case"usage":return process.stdout.write(Bn()),E;case"command":break}let{command:s,positionals:i,flags:r}=t.parsed,a=i[0],d=()=>Ge(a),l=s.flags.some((c)=>c.name==="store")?r.str("store"):void 0,u=await Ar({needsServer:s.needsServer,disabled:r.bool("no-bootstrap"),install:()=>nr(),...l===void 0?{}:{store:l}}),g=bA(u);if(g!==void 0)process.stderr.write(g);switch(s.name){case"init":{let c=r.str("dir"),f=r.str("user"),m=r.str("name"),y=r.str("purpose"),R=r.str("preset"),T=r.str("model"),b=r.str("base-url"),N=r.str("region"),M=r.str("api-key-env"),S=r.str("system"),P=r.str("web"),I=r.str("web-backend"),O=r.str("composio"),j=r.str("telegram"),V=r.str("telegram-allow"),C=r.str("whatsapp"),ne=r.str("whatsapp-number"),we=r.str("server"),F=r.str("schedules"),Be=r.str("skills"),ke=r.str("daemon");return await Yt({...c===void 0?{}:{dir:c},...f===void 0?{}:{user:f},...m===void 0?{}:{name:m},...y===void 0?{}:{purpose:y},...R===void 0?{}:{preset:R},...T===void 0?{}:{model:T},...b===void 0?{}:{baseUrl:b},...N===void 0?{}:{region:N},...M===void 0?{}:{apiKeyEnv:M},...S===void 0?{}:{system:S},...P===void 0?{}:{web:P},...I===void 0?{}:{webBackend:I},...O===void 0?{}:{composio:O},...j===void 0?{}:{telegram:j},...F===void 0?{}:{schedules:F},...V===void 0?{}:{telegramAllow:V},...C===void 0?{}:{whatsapp:C},...ne===void 0?{}:{whatsappNumber:ne},...we===void 0?{}:{server:we},...Be===void 0?{}:{skills:Be},...ke===void 0?{}:{daemon:ke},yes:r.bool("yes"),plain:r.bool("plain"),measureWindow:r.bool("measure-window"),installServer:nr})}case"run":{let c=r.str("session"),f=r.str("input"),m=r.str("store");return await it({...i[0]===void 0?{}:{manifestPath:d()},...c===void 0?{}:{sessionKey:c},continueSession:r.bool("continue"),...f===void 0?{}:{once:f},...m===void 0?{}:{store:m},ephemeral:r.bool("ephemeral"),quiet:r.bool("quiet"),showReasoning:r.bool("show-reasoning"),noReasoning:r.bool("no-reasoning"),...r.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:r.bool("plain")})}case"schedules":{let c=r.str("store"),f=r.str("id"),m=r.str("enable"),y=r.str("disable");return await vo({manifestPath:d(),...c===void 0?{}:{store:c},...f===void 0?{}:{id:f},...m===void 0?{}:{enable:m},...y===void 0?{}:{disable:y},recipients:r.bool("recipients"),json:r.bool("json")})}case"sessions":{let c=r.str("session"),f=r.str("store"),m=r.num("limit");return await Jo({manifestPath:d(),...c===void 0?{}:{sessionKey:c},...f===void 0?{}:{store:f},...m===void 0?{}:{limit:m},json:r.bool("json"),clear:r.bool("clear"),turns:r.bool("turns")})}case"owner":{let c=r.str("store");return await Qr({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{store:c},json:r.bool("json")})}case"memory":{let c=r.num("limit"),f=r.str("store");return await Nr({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...c===void 0?{}:{limit:c},...f===void 0?{}:{store:f},all:r.bool("all"),json:r.bool("json")})}case"config":{let{configCommand:c,readAction:f}=await import("./config-sx40rg8m.js"),m=f(a,i[1]);return await c({action:m.action,...m.ref===void 0?{}:{ref:m.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...r.str("channel")===void 0?{}:{channel:r.str("channel")},remove:r.bool("remove"),yes:r.bool("yes"),...r.str("store")===void 0?{}:{store:r.str("store")}})}case"validate":return await di({manifestPath:d(),json:r.bool("json")});case"workspace":return li({manifestPath:d(),json:r.bool("json"),strict:r.bool("strict")});case"soul":{let c=r.str("out");return zo({action:a,file:i[1],...c===void 0?{}:{out:c}})}case"skills":{if(i.length===0)return await ds({plain:r.bool("plain"),json:r.bool("json")});let c=i[2];return Kt({action:a,manifestPath:Ge(i[1]??""),...c===void 0?{}:{name:c},json:r.bool("json"),strict:r.bool("strict")})}case"sources":{let c=r.str("path"),f=r.str("ref");return await Yo({action:a,rest:i.slice(1),...c===void 0?{}:{path:c},...f===void 0?{}:{ref:f},json:r.bool("json")})}case"channels":{let c=ss("channels",a),f=c.ref??i[1]??"",{channelsCommand:m}=await import("./channels-nf6d8fvx.js");return await m({...c.action===void 0?{}:{action:c.action},manifestPath:Ge(f),...i[2]===void 0?{}:{channelId:i[2]},json:r.bool("json"),installServer:nr})}case"plugins":{let c=r.str("ref"),f=r.str("name");return await $s({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...c===void 0?{}:{ref:c},...f===void 0?{}:{name:f},json:r.bool("json")})}case"agents":{let c=r.str("store");return await Pt({manifestPaths:i.map((f)=>Ge(f)),...c===void 0?{}:{store:c},json:r.bool("json")})}case"restart":{let c=r.str("store");return await Ds({...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{store:c},json:r.bool("json")})}case"status":{let c=r.str("store");return await ei({...c===void 0?{}:{store:c},json:r.bool("json")})}case"logs":{let c=r.num("lines"),f=r.str("store");return await Ft({action:"logs",...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{lines:c},follow:r.bool("follow"),truncate:r.bool("truncate"),...f===void 0?{}:{store:f},json:r.bool("json")})}case"serve":{let c=r.num("port"),f=r.str("host"),m=r.str("store");return await Vo({manifestPaths:i.map((y)=>Ge(y)),...c===void 0?{}:{port:c},...f===void 0?{}:{host:f},...m===void 0?{}:{store:m},claim:r.bool("claim"),json:r.bool("json")})}case"keys":return await yr({noEnhancedKeys:r.bool("no-enhanced-keys")});case"terminal-setup":return await ti({dryRun:r.bool("dry-run"),yes:r.bool("yes"),json:r.bool("json"),confirm:MA});case"remove":return await js({...a===void 0?{}:{ref:a},dryRun:r.bool("dry-run"),filesOnly:r.bool("files-only"),prune:r.bool("prune"),all:r.bool("all"),yes:r.bool("yes"),json:r.bool("json"),...r.str("store")===void 0?{}:{store:r.str("store")},confirm:es});case"stop":{let c=r.str("reason");return await vn({...a===void 0?{}:{manifestPath:d()},dryRun:r.bool("dry-run"),...c===void 0?{}:{reason:c},...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"start":return await Zo({manifestPath:d(),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")});case"web":{let{webCommand:c}=await import("./web-zvf80ns1.js");return await c({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:r.bool("no-open"),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"credential":{let{credentialCommand:c}=await import("./credential-vdbkfk65.js");return await c({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...r.str("label")===void 0?{}:{label:r.str("label")},...r.str("agents")===void 0?{}:{agents:r.str("agents")},...r.str("sessions")===void 0?{}:{sessions:r.str("sessions")},...r.str("can")===void 0?{}:{can:r.str("can")},...r.str("expires")===void 0?{}:{expires:r.str("expires")},...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"daemon":{let c=r.num("lines");return await Ft({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{lines:c},follow:r.bool("follow"),truncate:r.bool("truncate"),dryRun:r.bool("dry-run"),...r.str("store")===void 0?{}:{store:r.str("store")},json:r.bool("json")})}case"model":{let c=r.num("price");return await zr({manifestPath:Ge(i[1]),window:r.bool("window"),...c===void 0?{}:{price:c},write:r.bool("write"),yes:r.bool("yes"),json:r.bool("json")})}case"tools":return await ri({manifestPath:d(),warm:r.bool("warm"),json:r.bool("json")});default:throw new n({code:"cli_command_unwired",message:`Command "${s.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}Tr();Cs();Pr();await xl(process.argv.slice(2)).catch(Tl).then((e)=>lr(e));
487
500
 
488
- //# debugId=02CBB3535531C9CA64756E2164756E21
501
+ //# debugId=AA0149936B525AEA64756E2164756E21
489
502
  //# sourceMappingURL=index.js.map