dispach 0.2.0 → 0.2.1

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 (167) hide show
  1. package/README.md +58 -18
  2. package/dist/APEv2Parser-9wqew3zv.js +5 -0
  3. package/dist/{APEv2Parser-jdp5yp24.js.map → APEv2Parser-9wqew3zv.js.map} +1 -1
  4. package/dist/{AiffParser-n65syezh.js → AiffParser-tbx3xkmk.js} +3 -3
  5. package/dist/{AiffParser-n65syezh.js.map → AiffParser-tbx3xkmk.js.map} +1 -1
  6. package/dist/App-hjn867nc.js +11 -0
  7. package/dist/{App-pmqmzsb3.js.map → App-hjn867nc.js.map} +1 -1
  8. package/dist/{AsfParser-da1fqvxz.js → AsfParser-d784ak3y.js} +3 -3
  9. package/dist/{AsfParser-da1fqvxz.js.map → AsfParser-d784ak3y.js.map} +1 -1
  10. package/dist/{ConfigEditor-4nqbeejh.js → ConfigEditor-g7eb2wsm.js} +3 -3
  11. package/dist/{ConfigEditor-4nqbeejh.js.map → ConfigEditor-g7eb2wsm.js.map} +1 -1
  12. package/dist/{DsdiffParser-gk95sj7t.js → DsdiffParser-vxnfx80c.js} +2 -2
  13. package/dist/{DsfParser-b0enevjw.js → DsfParser-0xsh0zzk.js} +3 -3
  14. package/dist/{DsfParser-b0enevjw.js.map → DsfParser-0xsh0zzk.js.map} +1 -1
  15. package/dist/FlacParser-bf8y3e0w.js +5 -0
  16. package/dist/{KeyProbe-rspsxpsr.js → KeyProbe-w8c37s9q.js} +3 -3
  17. package/dist/{KeyProbe-rspsxpsr.js.map → KeyProbe-w8c37s9q.js.map} +1 -1
  18. package/dist/{MP4Parser-ph7rv2fn.js → MP4Parser-tq7r7wd4.js} +3 -3
  19. package/dist/{MP4Parser-ph7rv2fn.js.map → MP4Parser-tq7r7wd4.js.map} +1 -1
  20. package/dist/{MatroskaParser-fjk1mpct.js → MatroskaParser-a79gsmzb.js} +3 -3
  21. package/dist/{MatroskaParser-fjk1mpct.js.map → MatroskaParser-a79gsmzb.js.map} +1 -1
  22. package/dist/{MpegParser-vp7cj8ts.js → MpegParser-zs61b3wq.js} +3 -3
  23. package/dist/{MpegParser-vp7cj8ts.js.map → MpegParser-zs61b3wq.js.map} +1 -1
  24. package/dist/{MusepackParser-v22gft1f.js → MusepackParser-bp8dm6nz.js} +3 -3
  25. package/dist/{MusepackParser-v22gft1f.js.map → MusepackParser-bp8dm6nz.js.map} +1 -1
  26. package/dist/{OggParser-as1m8xsa.js → OggParser-7pxr1sn9.js} +3 -3
  27. package/dist/{OggParser-as1m8xsa.js.map → OggParser-7pxr1sn9.js.map} +1 -1
  28. package/dist/{Picker-jkmd5xnx.js → Picker-b09hr4tk.js} +3 -3
  29. package/dist/{Picker-jkmd5xnx.js.map → Picker-b09hr4tk.js.map} +1 -1
  30. package/dist/{SessionPicker-3712ke3k.js → SessionPicker-wtfxwdxg.js} +3 -3
  31. package/dist/{SessionPicker-3712ke3k.js.map → SessionPicker-wtfxwdxg.js.map} +1 -1
  32. package/dist/{SkillBrowser-qhsyszt4.js → SkillBrowser-p9ht63c7.js} +3 -3
  33. package/dist/{SkillBrowser-qhsyszt4.js.map → SkillBrowser-p9ht63c7.js.map} +1 -1
  34. package/dist/{WavPackParser-b4qqavzg.js → WavPackParser-gpf3r92t.js} +3 -3
  35. package/dist/{WavPackParser-b4qqavzg.js.map → WavPackParser-gpf3r92t.js.map} +1 -1
  36. package/dist/{WaveParser-fqs1h38f.js → WaveParser-3kcak550.js} +3 -3
  37. package/dist/{WaveParser-fqs1h38f.js.map → WaveParser-3kcak550.js.map} +1 -1
  38. package/dist/WizardApp-494018sk.js +5 -0
  39. package/dist/{WizardApp-qrq36nv8.js.map → WizardApp-494018sk.js.map} +1 -1
  40. package/dist/{channels-gf31stv7.js → channels-yhdvxxrb.js} +14 -14
  41. package/dist/{channels-gf31stv7.js.map → channels-yhdvxxrb.js.map} +1 -1
  42. package/dist/config-g0ybmm4t.js +24 -0
  43. package/dist/{config-z2cd0c5f.js.map → config-g0ybmm4t.js.map} +1 -1
  44. package/dist/credential-pkme1sfe.js +19 -0
  45. package/dist/{credential-h0wmsjsw.js.map → credential-pkme1sfe.js.map} +1 -1
  46. package/dist/{index-dwxmy0kx.js → index-0mz7wpbw.js} +6 -6
  47. package/dist/{index-dwxmy0kx.js.map → index-0mz7wpbw.js.map} +1 -1
  48. package/dist/{index-fcqy46mh.js → index-0pddq849.js} +25 -25
  49. package/dist/{index-fcqy46mh.js.map → index-0pddq849.js.map} +1 -1
  50. package/dist/{index-2yj11ykt.js → index-1f1erzfx.js} +4 -4
  51. package/dist/{index-2yj11ykt.js.map → index-1f1erzfx.js.map} +1 -1
  52. package/dist/{index-1h9pqnec.js → index-26ejkp8q.js} +189 -189
  53. package/dist/{index-1h9pqnec.js.map → index-26ejkp8q.js.map} +7 -7
  54. package/dist/{index-ccpq4k6r.js → index-307qmvb0.js} +25 -25
  55. package/dist/{index-ccpq4k6r.js.map → index-307qmvb0.js.map} +1 -1
  56. package/dist/index-3b3h8kyh.js +5 -0
  57. package/dist/{index-3mvenfbg.js.map → index-3b3h8kyh.js.map} +1 -1
  58. package/dist/{index-0p9p6fvc.js → index-3fgq1acj.js} +10 -10
  59. package/dist/{index-0p9p6fvc.js.map → index-3fgq1acj.js.map} +3 -3
  60. package/dist/{index-dh2g58s1.js → index-4emtktc0.js} +3 -3
  61. package/dist/{index-dh2g58s1.js.map → index-4emtktc0.js.map} +1 -1
  62. package/dist/{index-026q0y3a.js → index-4t3p7vm9.js} +4 -4
  63. package/dist/{index-026q0y3a.js.map → index-4t3p7vm9.js.map} +1 -1
  64. package/dist/{index-t5d8ey5t.js → index-5m9wydxb.js} +4 -4
  65. package/dist/{index-t5d8ey5t.js.map → index-5m9wydxb.js.map} +1 -1
  66. package/dist/{index-g1d06ct5.js → index-633eqxry.js} +7 -7
  67. package/dist/{index-g1d06ct5.js.map → index-633eqxry.js.map} +1 -1
  68. package/dist/index-6r9h7ftn.js +308 -0
  69. package/dist/index-6r9h7ftn.js.map +21 -0
  70. package/dist/{index-kktaw552.js → index-7gsbzvnc.js} +2 -2
  71. package/dist/{index-z88f35vs.js → index-94k4mh6s.js} +13 -13
  72. package/dist/{index-z88f35vs.js.map → index-94k4mh6s.js.map} +3 -3
  73. package/dist/index-9dmgk6d3.js +5 -0
  74. package/dist/{index-tny7c703.js.map → index-9dmgk6d3.js.map} +1 -1
  75. package/dist/index-9qv87rq7.js +9 -0
  76. package/dist/{index-s4a28ctb.js.map → index-9qv87rq7.js.map} +1 -1
  77. package/dist/{index-k2q76dhw.js → index-a6mtqkth.js} +6 -6
  78. package/dist/{index-k2q76dhw.js.map → index-a6mtqkth.js.map} +1 -1
  79. package/dist/{index-0m0x1454.js → index-ac2wzspd.js} +4 -4
  80. package/dist/{index-0m0x1454.js.map → index-ac2wzspd.js.map} +1 -1
  81. package/dist/{index-wxmqyv4c.js → index-ad5c9t83.js} +4 -4
  82. package/dist/{index-wxmqyv4c.js.map → index-ad5c9t83.js.map} +1 -1
  83. package/dist/{index-b7qc21s7.js → index-akv6e7ge.js} +6 -6
  84. package/dist/{index-b7qc21s7.js.map → index-akv6e7ge.js.map} +1 -1
  85. package/dist/{index-v271gbaz.js → index-ec101x93.js} +4 -4
  86. package/dist/{index-v271gbaz.js.map → index-ec101x93.js.map} +1 -1
  87. package/dist/{index-rhv6gqpt.js → index-f056wkb4.js} +4 -4
  88. package/dist/{index-rhv6gqpt.js.map → index-f056wkb4.js.map} +1 -1
  89. package/dist/{index-c2qjdz4q.js → index-gqaa06yh.js} +8 -8
  90. package/dist/{index-c2qjdz4q.js.map → index-gqaa06yh.js.map} +1 -1
  91. package/dist/{index-rfa0ztab.js → index-j20k6k0m.js} +4 -4
  92. package/dist/{index-rfa0ztab.js.map → index-j20k6k0m.js.map} +1 -1
  93. package/dist/{index-2pzgta33.js → index-jh2az41t.js} +4 -4
  94. package/dist/{index-2pzgta33.js.map → index-jh2az41t.js.map} +1 -1
  95. package/dist/{index-gace5ac7.js → index-mn34kj95.js} +4 -4
  96. package/dist/{index-gace5ac7.js.map → index-mn34kj95.js.map} +1 -1
  97. package/dist/{index-rvq7t636.js → index-myg5enf5.js} +2 -2
  98. package/dist/{index-s78sq9g1.js → index-pdsey1ab.js} +45 -45
  99. package/dist/{index-s78sq9g1.js.map → index-pdsey1ab.js.map} +1 -1
  100. package/dist/{index-jmnjcw61.js → index-psk6q25h.js} +4 -4
  101. package/dist/{index-jmnjcw61.js.map → index-psk6q25h.js.map} +1 -1
  102. package/dist/{index-3s2q0m64.js → index-q8b1fc3k.js} +4 -4
  103. package/dist/{index-3s2q0m64.js.map → index-q8b1fc3k.js.map} +1 -1
  104. package/dist/{index-g8n8rhtr.js → index-qh82wtpa.js} +3 -3
  105. package/dist/{index-g8n8rhtr.js.map → index-qh82wtpa.js.map} +1 -1
  106. package/dist/{index-gqbny9gy.js → index-s2tzq27a.js} +6 -6
  107. package/dist/{index-gqbny9gy.js.map → index-s2tzq27a.js.map} +1 -1
  108. package/dist/{index-1wxw30j1.js → index-s57ztjhq.js} +35 -35
  109. package/dist/index-s57ztjhq.js.map +13 -0
  110. package/dist/{index-jv7egrh2.js → index-skkddg44.js} +4 -4
  111. package/dist/{index-jv7egrh2.js.map → index-skkddg44.js.map} +1 -1
  112. package/dist/{index-9m6b14b4.js → index-thmq816c.js} +4 -4
  113. package/dist/{index-9m6b14b4.js.map → index-thmq816c.js.map} +1 -1
  114. package/dist/{index-es4bgkbh.js → index-trx9xb59.js} +6 -6
  115. package/dist/{index-es4bgkbh.js.map → index-trx9xb59.js.map} +1 -1
  116. package/dist/{index-60jxyzbe.js → index-twcgf73h.js} +4 -4
  117. package/dist/{index-60jxyzbe.js.map → index-twcgf73h.js.map} +1 -1
  118. package/dist/index-vw2hf4d8.js +6 -0
  119. package/dist/{index-v6taf4vn.js.map → index-vw2hf4d8.js.map} +1 -1
  120. package/dist/{index-m5rmhcez.js → index-w97gprre.js} +4 -4
  121. package/dist/{index-m5rmhcez.js.map → index-w97gprre.js.map} +1 -1
  122. package/dist/index-wk6andxq.js +5 -0
  123. package/dist/{index-ak304afj.js.map → index-wk6andxq.js.map} +1 -1
  124. package/dist/index-x9z2xnct.js +11 -0
  125. package/dist/{index-5nprb9px.js.map → index-x9z2xnct.js.map} +1 -1
  126. package/dist/index-xa9crtzq.js +6 -0
  127. package/dist/{index-qe3ybzh6.js.map → index-xa9crtzq.js.map} +1 -1
  128. package/dist/{index-0v2gw4mk.js → index-y34s71qe.js} +3 -3
  129. package/dist/{index-0v2gw4mk.js.map → index-y34s71qe.js.map} +1 -1
  130. package/dist/{index-y6r1k2yd.js → index-ye2yb3xf.js} +7 -7
  131. package/dist/{index-y6r1k2yd.js.map → index-ye2yb3xf.js.map} +1 -1
  132. package/dist/{index-y605a1rj.js → index-z0dgxd7d.js} +10 -10
  133. package/dist/{index-y605a1rj.js.map → index-z0dgxd7d.js.map} +2 -2
  134. package/dist/{index-m01mb74d.js → index-zg89tq04.js} +4 -4
  135. package/dist/{index-m01mb74d.js.map → index-zg89tq04.js.map} +1 -1
  136. package/dist/{index-dgrwpzz9.js → index-zjphh8ch.js} +4 -4
  137. package/dist/{index-dgrwpzz9.js.map → index-zjphh8ch.js.map} +1 -1
  138. package/dist/index.js +172 -172
  139. package/dist/index.js.map +4 -4
  140. package/dist/transcript.d.ts.map +1 -1
  141. package/dist/web-f6869dy2.js +14 -0
  142. package/dist/{web-stkkwyka.js.map → web-f6869dy2.js.map} +1 -1
  143. package/dist/wrapper-52c0vacs.js +5 -0
  144. package/dist/{wrapper-bwxbqa53.js.map → wrapper-52c0vacs.js.map} +1 -1
  145. package/package.json +2 -2
  146. package/dist/APEv2Parser-jdp5yp24.js +0 -5
  147. package/dist/App-pmqmzsb3.js +0 -11
  148. package/dist/FlacParser-6jwner07.js +0 -5
  149. package/dist/WizardApp-qrq36nv8.js +0 -5
  150. package/dist/config-z2cd0c5f.js +0 -24
  151. package/dist/credential-h0wmsjsw.js +0 -19
  152. package/dist/index-1wxw30j1.js.map +0 -13
  153. package/dist/index-358nsn9t.js +0 -65
  154. package/dist/index-358nsn9t.js.map +0 -21
  155. package/dist/index-3mvenfbg.js +0 -5
  156. package/dist/index-5nprb9px.js +0 -11
  157. package/dist/index-ak304afj.js +0 -5
  158. package/dist/index-qe3ybzh6.js +0 -6
  159. package/dist/index-s4a28ctb.js +0 -9
  160. package/dist/index-tny7c703.js +0 -5
  161. package/dist/index-v6taf4vn.js +0 -6
  162. package/dist/web-stkkwyka.js +0 -14
  163. package/dist/wrapper-bwxbqa53.js +0 -5
  164. /package/dist/{DsdiffParser-gk95sj7t.js.map → DsdiffParser-vxnfx80c.js.map} +0 -0
  165. /package/dist/{FlacParser-6jwner07.js.map → FlacParser-bf8y3e0w.js.map} +0 -0
  166. /package/dist/{index-kktaw552.js.map → index-7gsbzvnc.js.map} +0 -0
  167. /package/dist/{index-rvq7t636.js.map → index-myg5enf5.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,39 +1,39 @@
1
1
  #!/usr/bin/env node
2
- import{A,j,f,t,DA,Ut,zA,xt,st,ye,Co,ti,ni,at,fo,NA,po,MA,Ht,BA,Bo,ho,We,G,q,ii,wr,Kt,J,mo,So,lt,Yt,wo,It,z,fe,ci,ue,pn,Do,bo,li,Ii,di,_,Fs}from"./index-1h9pqnec.js";import{cr,Ge,lr,Ir,JA,dr,ur,Er}from"./index-1wxw30j1.js";import{oe,Se,Ie,de,ce,he,Kr}from"./index-358nsn9t.js";import{Zs}from"./index-rfa0ztab.js";import{hn}from"./index-9m6b14b4.js";import{Mt,Tt,$n,ve,os,rs,rr,Hr,ir,uA,sr,Rt,HA,ar,KA,_t,is,ss}from"./index-s78sq9g1.js";import{$o,nn,FA,Gr,er,wt,Ar,Hn,Dt,Kn,on,Yn,jn,qi,Jn,qn,Vn}from"./index-ccpq4k6r.js";import{Lt,vt,lo,In,Io,Pt,yr,dn,iA,it,VA,Gt,Qr}from"./index-y605a1rj.js";import{xr,Wi,rn,zi,Zi,Xi,et}from"./index-z88f35vs.js";import{sn,nA,an,As}from"./index-026q0y3a.js";import{Fn,Un,An,Zo,St,Gi,xn,xi,Hi}from"./index-0p9p6fvc.js";import"./index-2pzgta33.js";import{zo}from"./index-81vj1bxe.js";import{GA,tn,ji,Ji}from"./index-0m0x1454.js";import{bt,Vi}from"./index-v271gbaz.js";import{Ye}from"./index-5nprb9px.js";import{$i}from"./index-60jxyzbe.js";import{ts,nr,or,je,Je,UA,ns,xA,me,Nt,dA,Xn}from"./index-qe3ybzh6.js";import{Pe,oA}from"./index-wxmqyv4c.js";import{to,SA,gs,U,ls,qe,EA,gr,Is}from"./index-b7qc21s7.js";import{u,k,Q,y,At,ln,tt,nt}from"./index-k2q76dhw.js";import{WA,we,ie,mr,F,se,Sr,un,En,$r,ks,Ft,Ls,Ae,Fe}from"./index-dwxmy0kx.js";import{ke}from"./index-g8n8rhtr.js";import{Js,Vs}from"./index-v7mz396x.js";import{Ro,ra,RA,be,Lo,Uo,o,d,yn}from"./index-v6taf4vn.js";async function bn(e){let s=await xA(e),r=[];for(let i of Ae()){let n=i.id??i.ref,a=await or(n,e)??{enabled:!0},l=s.find((p)=>p.agentId===n),c=l===void 0?Number.NaN:Date.now()-Date.parse(l.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...l===void 0?{}:{pid:l.pid,serving:`serving · ${l.mode} · pid ${l.pid}${Number.isFinite(c)?` · up ${ln(c)}`:""}`}})}return r}function vn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((s)=>({label:s.ref,value:s.problem!==void 0?"broken":s.enabled?"on":"off",note:s.problem??s.serving??(s.enabled?`not hosted${s.modelId===void 0?"":` · ${s.modelId}`}`:`switched off${s.reason===void 0?"":` — ${s.reason}`}`)}))}async function $t(e){if(e.manifestPaths.length===0){let a=await bn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
- `);else process.stdout.write(`${u(vn(a))}
4
- `);return o}let s=await ue.create({agents:[...e.manifestPaths],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_(e.manifestPaths),store:e.store??F(),lease:!1});U(()=>s.stop("cli-exit"));let r=s.list().map((a)=>a.describe()),i=new Map;for(let a of await s.store.leases.all()){if(a.runtimeId===s.runtimeId||!z(a.pid))continue;let l=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(l)?` · up ${ln(l)}`:""}`)}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 n=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(`${u(n)}
6
- `),o}import{basename as _n,dirname as mi,join as re,resolve as fi}from"node:path";import{rmSync as Go}from"node:fs";import{isAbsolute as kt,join as qo,resolve as Et}from"node:path";var Vo=3;async function Ot(e){if(e.answers.skills!=="find")return;let s=e.answers.skillsSearch?.trim()??"";if(s===""){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=ve(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(`
2
+ import{t,j,f,A,Dt,UA,zt,xA,sA,ye,Co,Ai,ni,aA,fo,Nt,po,Mt,HA,ht,ho,Bo,We,G,q,ii,wr,KA,J,mo,So,lA,YA,wo,IA,z,fe,ci,de,pn,Do,bo,li,Ii,ui,_,Fs}from"./index-26ejkp8q.js";import{cr,Ge,lr,Ir,Jt,ur,dr,Er}from"./index-s57ztjhq.js";import{oe,Se,Ie,ue,ce,Be,Kr}from"./index-6r9h7ftn.js";import{Zs}from"./index-j20k6k0m.js";import{Bn}from"./index-thmq816c.js";import{MA,TA,$n,ve,os,rs,rr,Hr,ir,dt,sr,RA,Ht,ar,Kt,_A,is,ss}from"./index-pdsey1ab.js";import{$o,nn,Ft,Gr,er,wA,tr,Hn,DA,Kn,on,Yn,jn,qi,Jn,qn,Vn}from"./index-307qmvb0.js";import{LA,vA,lo,In,Io,PA,yr,un,it,iA,Vt,GA,Qr}from"./index-z0dgxd7d.js";import{xr,Wi,rn,zi,Zi,Xi,eA}from"./index-94k4mh6s.js";import{sn,nt,an,ts}from"./index-4t3p7vm9.js";import{Fn,Un,tn,Zo,SA,Gi,xn,xi,Hi}from"./index-3fgq1acj.js";import"./index-jh2az41t.js";import{zo}from"./index-81vj1bxe.js";import{Gt,An,ji,Ji}from"./index-ac2wzspd.js";import{bA,Vi}from"./index-ec101x93.js";import{Ye}from"./index-x9z2xnct.js";import{$i}from"./index-twcgf73h.js";import{As,nr,or,je,Je,Ut,ns,xt,me,NA,ut,Xn}from"./index-xa9crtzq.js";import{Pe,ot}from"./index-ad5c9t83.js";import{Ao,St,gs,U,ls,qe,Et,gr,Is}from"./index-akv6e7ge.js";import{d,k,Q,y,tA,ln,AA,nA}from"./index-a6mtqkth.js";import{Wt,we,ie,mr,F,se,Sr,dn,En,$r,ks,FA,Ls,te,Fe}from"./index-0mz7wpbw.js";import{ke}from"./index-qh82wtpa.js";import{Js,Vs}from"./index-v7mz396x.js";import{Ro,ra,Rt,be,Lo,Uo,o,u,yn}from"./index-vw2hf4d8.js";async function wn(e){let s=await xt(e),r=[];for(let i of te()){let n=i.id??i.ref,a=await or(n,e)??{enabled:!0},l=s.find((p)=>p.agentId===n),c=l===void 0?Number.NaN:Date.now()-Date.parse(l.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...l===void 0?{}:{pid:l.pid,serving:`serving · ${l.mode} · pid ${l.pid}${Number.isFinite(c)?` · up ${ln(c)}`:""}`}})}return r}function bn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((s)=>({label:s.ref,value:s.problem!==void 0?"broken":s.enabled?"on":"off",note:s.problem??s.serving??(s.enabled?`not hosted${s.modelId===void 0?"":` · ${s.modelId}`}`:`switched off${s.reason===void 0?"":` — ${s.reason}`}`)}))}async function yt(e){if(e.manifestPaths.length===0){let a=await wn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
+ `);else process.stdout.write(`${d(bn(a))}
4
+ `);return o}let s=await de.create({agents:[...e.manifestPaths],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_(e.manifestPaths),store:e.store??F(),lease:!1});U(()=>s.stop("cli-exit"));let r=s.list().map((a)=>a.describe()),i=new Map;for(let a of await s.store.leases.all()){if(a.runtimeId===s.runtimeId||!z(a.pid))continue;let l=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(l)?` · up ${ln(l)}`:""}`)}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 n=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(`${d(n)}
6
+ `),o}import{basename as On,dirname as ei,join as ae,resolve as ti}from"node:path";import{rmSync as jo}from"node:fs";import{isAbsolute as wt,join as Fo,resolve as bt}from"node:path";var Ko=3;async function $t(e){if(e.answers.skills!=="find")return;let s=e.answers.skillsSearch?.trim()??"";if(s===""){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=ve(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
7
  searching ${r.length} skill source(s) for ${JSON.stringify(s)}
8
- `);let i=[],n=[];for(let m of r){if(!uA(m.name,e.env))try{await Rt(m,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(h){n.push(`${m.name} — ${f(h)?h.message:String(h)}`);continue}i.push(...HA(m,e.env))}for(let m of n)process.stdout.write(y(`could not fetch ${m}
8
+ `);let i=[],n=[];for(let m of r){if(!dt(m.name,e.env))try{await RA(m,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(h){n.push(`${m.name} — ${f(h)?h.message:String(h)}`);continue}i.push(...Ht(m,e.env))}for(let m of n)process.stdout.write(y(`could not fetch ${m}
9
9
  `));if(i.length===0){process.stdout.write(`${y("no source could be read, so no skill was installed — the directory is there and empty")}
10
10
  ${y("`sources update` reports why; `sources search <words>` when it works",4)}
11
- `);return}let a=Jo(s,i);if(a.length===0){process.stdout.write(`${y(`nothing in ${i.length} skills matches those words, so none was installed`)}
11
+ `);return}let a=Mo(s,i);if(a.length===0){process.stdout.write(`${y(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
12
  ${y("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
13
13
  `);return}let l=a[0],c=`${l.source}/${l.skill}`;if(process.stdout.write(`${y(`best of ${i.length}: ${c}`)}
14
- `),a.length>1)process.stdout.write(`${y(`also matched: ${a.slice(1,1+Vo).map((m)=>`${m.source}/${m.skill}`).join(", ")}`,4)}
14
+ `),a.length>1)process.stdout.write(`${y(`also matched: ${a.slice(1,1+Ko).map((m)=>`${m.source}/${m.skill}`).join(", ")}`,4)}
15
15
  `);if(process.stdout.write(`
16
- `),KA({action:"install",manifestPath:e.manifestPath,name:c,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let w=Xo(e.manifestPath,e.envOverlay);if(w!==void 0)Yo(e.manifestPath,l.skill,e.envOverlay),process.stdout.write(`
16
+ `),Kt({action:"install",manifestPath:e.manifestPath,name:c,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let w=Ho(e.manifestPath,e.envOverlay);if(w!==void 0)Wo(e.manifestPath,l.skill,e.envOverlay),process.stdout.write(`
17
17
  ${Q(`${c} was removed again: it does not load on this machine`)}
18
18
  ${y(w,4)}
19
19
  ${y("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
- `)}function Jo(e,s){let r=new Map,i=s.filter((n)=>n.problem===void 0).map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return Yt(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}function Xo(e,s){try{let r=q(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=r.manifest.skills;if(i===void 0)return;let n=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities);lt({dir:kt(i.dir)?i.dir:Et(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:n.promptStyle,agentDir:r.dir,runner:de()});return}catch(r){return f(r)?r.message:String(r)}}function Yo(e,s,r){try{let i=q(e,{...r===void 0?{}:{env:{...process.env,...r}}}),n=i.manifest.skills;if(n===void 0)return;let a=kt(n.dir)?n.dir:Et(i.dir,n.dir);Go(qo(a,s),{recursive:!0,force:!0}),ar(a,s)}catch{}}var kn=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function Ct(e,s,r={}){let i=r.fetch??fetch,n=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},l=async(b)=>{try{let P=await i(b,{headers:a,signal:AbortSignal.timeout(3000)});if(!P.ok)return;let R=await P.json();return R!==null&&typeof R==="object"?R:void 0}catch{return}},w=((await l(`${n}/models/${s}/endpoints`))?.data?.endpoints??[]).map((b)=>kn(b.context_length)).filter((b)=>b!==void 0);if(w.length>0)return{tokens:Math.min(...w),source:`the smallest of ${w.length} published endpoint${w.length===1?"":"s"} at ${n}`};let h=((await l(`${n}/models`))?.data??[]).find((b)=>b.id===s),g=kn(h?.context_length)??kn(h?.max_model_len);return g===void 0?void 0:{tokens:g,source:`${n}/models`}}import{existsSync as Qo,mkdirSync as ei,writeFileSync as si}from"node:fs";import{dirname as ri,join as Sn,resolve as Rn,sep as oi}from"node:path";var De={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",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 Pn(e,s,r){let i=[];for(;;){let n=it(e,r);if(n===void 0)break;if(n.optional===!0){e[n.step]="";continue}if(n.fallback===""){i.push(n.step),e[n.step]="(missing)";continue}let a=VA(n.step,n.fallback);if(a.ok)e[n.step]=a.value}if(i.length>0){let n=i.map((a)=>De[a]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${s}), and ${i.join(", ")} ${i.length===1?"has":"have"} no default.`,hint:`Pass ${n} — 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 Tn(e,s){let r=e,i=Lt(r.preset),n=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??vt(r.dirChoice,r.name,s);if(l===void 0)throw new t({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,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(l,s.agentDirBase)?ks(s.agentDirBase,jt):jt()}:{},...n===void 0?{}:{apiKeyEnv:n},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function ai(e,s){let r=Rn(e),i=Rn(s);return r===i||r.startsWith(i+oi)}function jt(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((s)=>s.toString(16).padStart(2,"0")).join("")}function Oe(e,s){let r=s.map((i)=>Sn(e,i.relPath)).filter((i)=>Qo(i));if(r.length>0)throw new t({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 s){let n=Sn(e,i.relPath);ei(ri(n),{recursive:!0}),si(n,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function He(e,s){let r=q(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:n,warnings:a}=It(r,i.promptStyle),l=zA(n,r.manifest.context.rules);if(l!==void 0&&r.manifest.context.rules.onExceed==="fail")throw l;return{distilled:a.some((c)=>c.code==="soul_distilled")}}var qt=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."}]]),On=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 Bt(e){let s=VA(e.step,e.fallback);return s.ok?s.value:e.fallback}function ui(e,s){let r=On.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Bt(e),optional:e.optional===!0,secret:dn.has(e.step),...s===void 0?{}:{requires:s},...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 Wt=64;function Vt(e){let s=new Map,r=new Set,i=(a,l)=>{let c={...a},p=[];for(let w=0;w<Wt;w+=1){let m=it(c,e);if(m===void 0)break;let h=Bt(m);if(!qt.has(m.step)&&!s.has(m.step))s.set(m.step,ui(m,l));for(let g of m.options??[]){if(g.value===h)continue;if(On.get(m.step)?.has(g.value)===!0)continue;p.push({seed:{...c,[m.step]:g.value},opened:{step:m.step,value:g.value}})}c[m.step]=h}return p},n=[...i({})];for(let a=0;a<Wt&&n.length>0;a+=1){let l=n.splice(0,n.length);for(let c of l){let p=`${c.opened.step}=${c.opened.value}`;if(r.has(p))continue;r.add(p),n.push(...i(c.seed,c.opened))}}return[...s.values()].sort((a,l)=>yr.indexOf(a.step)-yr.indexOf(l.step))}function Jt(e){let s={};for(let[c,p]of Object.entries(e.answers)){let w=c;if(!(w in De))throw new t({code:"provision_unknown_answer",message:`"${c}" 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:c});let m=qt.get(w);if(m!==void 0)throw new t({code:m.code,message:`"${c}" cannot be set over the API.`,hint:m.hint,field:c});let h=On.get(w)?.get(p.trim().toLowerCase());if(h!==void 0)throw new t({code:h.code,message:`${c} is ${JSON.stringify(p)}, which this runtime cannot do over the API.`,hint:h.hint,field:c});let g=VA(w,p);if(!g.ok)throw new t({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(p)}, which ${g.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:c});s[w]=g.value}Pn(s,"this is the provisioning API",e.defaults);let r=Tn(s,e.defaults),i=iA(r.name),n=vt("sandbox",r.name,e.defaults);if(n===void 0)throw new t({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=Rn(n),l=Qr({...r,dir:a});return Oe(a,l),{agentId:i,dir:a,manifestPath:Sn(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function pi(e){if(e.web!=="search")return;return lo(e.webBackend??"tavily")?.apiKeyEnv}async function Xt(e){let s=await zt(e);if(s.kind==="aborted")return process.stdout.write(`nothing written
21
- `),o;return s.kind==="failed"?s.code:o}async function Cn(e){return zt(e)}async function zt(e){let s=gi(e),r=oA({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,n={agentDirBase:ie()};if(i){let v=await yi(s,n);if(v===void 0)return{kind:"aborted"};Object.assign(s,v)}else Pn(s,e.yes===!0?"--yes was passed":r.because,n);let a=Tn(s,n),l=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),c=i||e.measureWindow===!0?await Ct(a.baseUrl,a.model,{...l===void 0||l===""?{}:{apiKey:l}}):void 0,p=a,w=fi(process.cwd(),p.dir),m=Ls(w);if(m!==void 0)process.stderr.write(`${m}
22
- `);let h=re(w,"agent.yaml"),g=Qr(p,c);Oe(w,g);let b=p.apiKeyEnv,R=b!==void 0&&p.apiKey===void 0&&(process.env[b]===void 0||process.env[b]==="")&&b!==void 0?{[b]:"(pending)"}:void 0,S=!1;try{S=He(re(w,"agent.yaml"),R).distilled}catch(v){if(f(v))return process.stderr.write(`init wrote ${g.length} files to ${w}, but the result does not load:
20
+ `)}function Mo(e,s){let r=new Map,i=s.filter((n)=>n.problem===void 0).map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return YA(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}function Ho(e,s){try{let r=q(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=r.manifest.skills;if(i===void 0)return;let n=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities);lA({dir:wt(i.dir)?i.dir:bt(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:n.promptStyle,agentDir:r.dir,runner:ue()});return}catch(r){return f(r)?r.message:String(r)}}function Wo(e,s,r){try{let i=q(e,{...r===void 0?{}:{env:{...process.env,...r}}}),n=i.manifest.skills;if(n===void 0)return;let a=wt(n.dir)?n.dir:bt(i.dir,n.dir);jo(Fo(a,s),{recursive:!0,force:!0}),ar(a,s)}catch{}}var vn=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function vt(e,s,r={}){let i=r.fetch??fetch,n=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},l=async(b)=>{try{let P=await i(b,{headers:a,signal:AbortSignal.timeout(3000)});if(!P.ok)return;let R=await P.json();return R!==null&&typeof R==="object"?R:void 0}catch{return}},w=((await l(`${n}/models/${s}/endpoints`))?.data?.endpoints??[]).map((b)=>vn(b.context_length)).filter((b)=>b!==void 0);if(w.length>0)return{tokens:Math.min(...w),source:`the smallest of ${w.length} published endpoint${w.length===1?"":"s"} at ${n}`};let h=((await l(`${n}/models`))?.data??[]).find((b)=>b.id===s),g=vn(h?.context_length)??vn(h?.max_model_len);return g===void 0?void 0:{tokens:g,source:`${n}/models`}}import{existsSync as Go,mkdirSync as qo,writeFileSync as Vo}from"node:fs";import{dirname as Jo,join as kn,resolve as Sn,sep as Xo}from"node:path";var Me={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",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 Rn(e,s,r){let i=[];for(;;){let n=iA(e,r);if(n===void 0)break;if(n.optional===!0){e[n.step]="";continue}if(n.fallback===""){i.push(n.step),e[n.step]="(missing)";continue}let a=Vt(n.step,n.fallback);if(a.ok)e[n.step]=a.value}if(i.length>0){let n=i.map((a)=>Me[a]).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${s}), and ${i.join(", ")} ${i.length===1?"has":"have"} no default.`,hint:`Pass ${n} — 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 Pn(e,s){let r=e,i=LA(r.preset),n=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??vA(r.dirChoice,r.name,s);if(l===void 0)throw new A({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,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:Yo(l,s.agentDirBase)?ks(s.agentDirBase,kt):kt()}:{},...n===void 0?{}:{apiKeyEnv:n},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function Yo(e,s){let r=Sn(e),i=Sn(s);return r===i||r.startsWith(i+Xo)}function kt(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((s)=>s.toString(16).padStart(2,"0")).join("")}function Ae(e,s){let r=s.map((i)=>kn(e,i.relPath)).filter((i)=>Go(i));if(r.length>0)throw new A({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 s){let n=kn(e,i.relPath);qo(Jo(n),{recursive:!0}),Vo(n,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function De(e,s){let r=q(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:n,warnings:a}=IA(r,i.promptStyle),l=zt(n,r.manifest.context.rules);if(l!==void 0&&r.manifest.context.rules.onExceed==="fail")throw l;return{distilled:a.some((c)=>c.code==="soul_distilled")}}var Tt=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."}]]),Tn=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 It(e){let s=Vt(e.step,e.fallback);return s.ok?s.value:e.fallback}function Qo(e,s){let r=Tn.get(e.step);return{step:e.step,prompt:e.prompt,fallback:It(e),optional:e.optional===!0,secret:un.has(e.step),...s===void 0?{}:{requires:s},...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 Pt=64;function At(e){let s=new Map,r=new Set,i=(a,l)=>{let c={...a},p=[];for(let w=0;w<Pt;w+=1){let m=iA(c,e);if(m===void 0)break;let h=It(m);if(!Tt.has(m.step)&&!s.has(m.step))s.set(m.step,Qo(m,l));for(let g of m.options??[]){if(g.value===h)continue;if(Tn.get(m.step)?.has(g.value)===!0)continue;p.push({seed:{...c,[m.step]:g.value},opened:{step:m.step,value:g.value}})}c[m.step]=h}return p},n=[...i({})];for(let a=0;a<Pt&&n.length>0;a+=1){let l=n.splice(0,n.length);for(let c of l){let p=`${c.opened.step}=${c.opened.value}`;if(r.has(p))continue;r.add(p),n.push(...i(c.seed,c.opened))}}return[...s.values()].sort((a,l)=>yr.indexOf(a.step)-yr.indexOf(l.step))}function Ot(e){let s={};for(let[c,p]of Object.entries(e.answers)){let w=c;if(!(w in Me))throw new A({code:"provision_unknown_answer",message:`"${c}" 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:c});let m=Tt.get(w);if(m!==void 0)throw new A({code:m.code,message:`"${c}" cannot be set over the API.`,hint:m.hint,field:c});let h=Tn.get(w)?.get(p.trim().toLowerCase());if(h!==void 0)throw new A({code:h.code,message:`${c} is ${JSON.stringify(p)}, which this runtime cannot do over the API.`,hint:h.hint,field:c});let g=Vt(w,p);if(!g.ok)throw new A({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(p)}, which ${g.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:c});s[w]=g.value}Rn(s,"this is the provisioning API",e.defaults);let r=Pn(s,e.defaults),i=it(r.name),n=vA("sandbox",r.name,e.defaults);if(n===void 0)throw new A({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=Sn(n),l=Qr({...r,dir:a});return Ae(a,l),{agentId:i,dir:a,manifestPath:kn(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function si(e){if(e.web!=="search")return;return lo(e.webBackend??"tavily")?.apiKeyEnv}async function _t(e){let s=await Ct(e);if(s.kind==="aborted")return process.stdout.write(`nothing written
21
+ `),o;return s.kind==="failed"?s.code:o}async function _n(e){return Ct(e)}async function Ct(e){let s=oi(e),r=ot({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,n={agentDirBase:ie()};if(i){let v=await ai(s,n);if(v===void 0)return{kind:"aborted"};Object.assign(s,v)}else Rn(s,e.yes===!0?"--yes was passed":r.because,n);let a=Pn(s,n),l=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),c=i||e.measureWindow===!0?await vt(a.baseUrl,a.model,{...l===void 0||l===""?{}:{apiKey:l}}):void 0,p=a,w=ti(process.cwd(),p.dir),m=Ls(w);if(m!==void 0)process.stderr.write(`${m}
22
+ `);let h=ae(w,"agent.yaml"),g=Qr(p,c);Ae(w,g);let b=p.apiKeyEnv,R=b!==void 0&&p.apiKey===void 0&&(process.env[b]===void 0||process.env[b]==="")&&b!==void 0?{[b]:"(pending)"}:void 0,S=!1;try{S=De(ae(w,"agent.yaml"),R).distilled}catch(v){if(f(v))return process.stderr.write(`init wrote ${g.length} files to ${w}, but the result does not load:
23
23
  ${v.format()}
24
- `),{kind:"failed",code:d};throw v}if(process.stdout.write(`wrote ${g.length} files to ${w} — validated ok
25
- `),p.skills==="find"){let v=(p.skillsPick??"").split(",").map((x)=>x.trim()).filter((x)=>x!=="");if(v.length>0)is(v,h,{...R===void 0?{}:{envOverlay:R}});else if(!i)await Ot({answers:p,manifestPath:h,...R===void 0?{}:{envOverlay:R}})}let L;if(p.daemon==="service"){process.stdout.write(`
26
- `);let{outcome:v,host:x}=await Hn({...e.installServer===void 0?{}:{install:e.installServer}}),I=wt(v);if(I!==void 0)process.stderr.write(I);if(x?.baseUrl!==void 0){let N=await Dt(x,h);if(N.ok)L=x.baseUrl;else process.stderr.write(`pid ${x.pid} did not adopt ${iA(p.name)}${N.detail===void 0?"":`: ${N.detail}`}
24
+ `),{kind:"failed",code:u};throw v}if(process.stdout.write(`wrote ${g.length} files to ${w} — validated ok
25
+ `),p.skills==="find"){let v=(p.skillsPick??"").split(",").map((x)=>x.trim()).filter((x)=>x!=="");if(v.length>0)is(v,h,{...R===void 0?{}:{envOverlay:R}});else if(!i)await $t({answers:p,manifestPath:h,...R===void 0?{}:{envOverlay:R}})}let L;if(p.daemon==="service"){process.stdout.write(`
26
+ `);let{outcome:v,host:x}=await Hn({...e.installServer===void 0?{}:{install:e.installServer}}),I=wA(v);if(I!==void 0)process.stderr.write(I);if(x?.baseUrl!==void 0){let N=await DA(x,h);if(N.ok)L=x.baseUrl;else process.stderr.write(`pid ${x.pid} did not adopt ${it(p.name)}${N.detail===void 0?"":`: ${N.detail}`}
27
27
  `)}}let D;if(p.whatsapp==="connected"&&(p.whatsappNumber??"")!==""&&i)D=L!==void 0?await Yn({manifestPath:h,channelId:"wa"}):await jn({manifestPath:h,dir:w,number:p.whatsappNumber??"",channelId:"wa"});if(p.whatsapp==="connected"&&D!=="paired")process.stdout.write(`
28
- ${qi(iA(p.name))}`);return process.stdout.write(wi(p,w,S,L)),{kind:"ok",manifestPath:re(w,"agent.yaml")}}function hi(e){if(e===void 0)return[];if(Pt.some((s)=>s.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function gi(e){let s={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["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],...hi(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,n]of r){if(n===void 0)continue;let a=VA(i,n);if(!a.ok)throw new t({code:"cli_init_flag_invalid",message:`${De[i]} is ${JSON.stringify(n)}, 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."});s[i]=a.value}return s}async function yi(e,s){let[{render:r},{createElement:i},{WizardApp:n}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-qrq36nv8.js")]),a;to();let l=r(i(n,{title:`${A.name} ${J}`,given:e,defaults:s,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Pe()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function wi(e,s,r,i){let n=i!==void 0,l=mi(s)===ie()?_n(s):re(s,"agent.yaml"),c=re(s,"agent.yaml"),p=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)p.push(`Add your key: edit ${re(s,".env")} and set ${e.apiKeyEnv}=`);let w=pi(e);if(w!==void 0&&e.webKey===void 0)p.push(`Add your search key: edit ${re(s,".env")} and set ${w}= — web_fetch works without it, web_search does not`);if(Gt(e)&&e.composioKey===void 0)p.push(`Add your Composio key: edit ${re(s,".env")} and set ${In}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)p.push(`Add your bot token: message @BotFather with /newbot, then edit ${re(s,".env")} and set ${Io}=`);let m=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],h=m.length>0||e.server==="local",g=[...m,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(n)p.push(`open ${et(i,_n(s))} — the web UI. The service is serving `+`${_n(s)} now; ${g} ${m.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),p.push(`${A.slug} run ${l} — talks to it here, attached to that same service.`);else p.push(`${A.slug} run ${l}`);if(h&&!n){if(p.push(`${A.slug} serve ${l} — starts ${g}; \`run\` starts neither`),e.daemon==="service")p.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)p.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(Gt(e))p.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.");p.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 ${l} <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 440+ from two catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${l} <name>\` writes one.`),p.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${c}\` shows exactly what still reads as a template.`);let b=n?`
29
- it is running in the background now — \`${A.slug} status\` at any time,
30
- \`${A.slug} restart ${l}\` after editing it, and \`${A.slug} stop\` turns everything off.
28
+ ${qi(it(p.name))}`);return process.stdout.write(di(p,w,S,L)),{kind:"ok",manifestPath:ae(w,"agent.yaml")}}function ri(e){if(e===void 0)return[];if(PA.some((s)=>s.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function oi(e){let s={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["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],...ri(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,n]of r){if(n===void 0)continue;let a=Vt(i,n);if(!a.ok)throw new A({code:"cli_init_flag_invalid",message:`${Me[i]} is ${JSON.stringify(n)}, 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."});s[i]=a.value}return s}async function ai(e,s){let[{render:r},{createElement:i},{WizardApp:n}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-494018sk.js")]),a;Ao();let l=r(i(n,{title:`${t.name} ${J}`,given:e,defaults:s,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Pe()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function di(e,s,r,i){let n=i!==void 0,l=ei(s)===ie()?On(s):ae(s,"agent.yaml"),c=ae(s,"agent.yaml"),p=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)p.push(`Add your key: edit ${ae(s,".env")} and set ${e.apiKeyEnv}=`);let w=si(e);if(w!==void 0&&e.webKey===void 0)p.push(`Add your search key: edit ${ae(s,".env")} and set ${w}= — web_fetch works without it, web_search does not`);if(GA(e)&&e.composioKey===void 0)p.push(`Add your Composio key: edit ${ae(s,".env")} and set ${In}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)p.push(`Add your bot token: message @BotFather with /newbot, then edit ${ae(s,".env")} and set ${Io}=`);let m=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],h=m.length>0||e.server==="local",g=[...m,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(n)p.push(`open ${eA(i,On(s))} — the web UI. The service is serving `+`${On(s)} now; ${g} ${m.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),p.push(`${t.slug} run ${l} — talks to it here, attached to that same service.`);else p.push(`${t.slug} run ${l}`);if(h&&!n){if(p.push(`${t.slug} serve ${l} — starts ${g}; \`run\` starts neither`),e.daemon==="service")p.push(`${t.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)p.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(GA(e))p.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.");p.push(e.skills==="find"?`Add more skills: \`${t.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${t.slug} skills install ${l} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${t.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${t.slug} sources search <what it should do>\` finds one, \`${t.slug} skills new ${l} <name>\` writes one.`),p.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${t.slug} workspace ${c}\` shows exactly what still reads as a template.`);let b=n?`
29
+ it is running in the background now — \`${t.slug} status\` at any time,
30
+ \`${t.slug} restart ${l}\` after editing it, and \`${t.slug} stop\` turns everything off.
31
31
  `:"";return`${r?`
32
32
  this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
33
33
  frontier-class model, and activates automatically if you upgrade.
34
34
  `:""}${b}
35
35
  `+p.map((R,S)=>` ${S+1}. ${R}
36
- `).join("")}var Be=16;function Ve(e=process.stdin){let s=[],r=[],i=(n)=>{let a=typeof n==="string"?n:n.toString("utf8");if(r.push(a),r.length>Be)r.splice(0,r.length-Be);if(s.push(...Js(a)),s.length>Be)s.splice(0,s.length-Be)};return e.on("data",i),{correct:(n,a)=>Vs(n,a,s),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Qt=[{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 Xe(e){let s=e.TERM_PROGRAM??"";if(s==="vscode")return"vscode";if(s==="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(s==="WarpTerminal")return"warp";if(s==="iTerm.app")return"iterm2";if(s==="Apple_Terminal")return"apple";return"unknown"}function ze(e){return Qt.find((s)=>s.id===e)}function Zt(){return Qt}function es(e,s){return s.marker!==void 0&&e.includes(s.marker)}function as(e,s){let r=s.line;if(r===void 0)return;if(s.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
36
+ `).join("")}var He=16;function Ve(e=process.stdin){let s=[],r=[],i=(n)=>{let a=typeof n==="string"?n:n.toString("utf8");if(r.push(a),r.length>He)r.splice(0,r.length-He);if(s.push(...Js(a)),s.length>He)s.splice(0,s.length-He)};return e.on("data",i),{correct:(n,a)=>Vs(n,a,s),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 — \`${t.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 Xe(e){let s=e.TERM_PROGRAM??"";if(s==="vscode")return"vscode";if(s==="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(s==="WarpTerminal")return"warp";if(s==="iTerm.app")return"iterm2";if(s==="Apple_Terminal")return"apple";return"unknown"}function ze(e){return jt.find((s)=>s.id===e)}function Lt(){return jt}function qt(e,s){return s.marker!==void 0&&e.includes(s.marker)}function Bt(e,s){let r=s.line;if(r===void 0)return;if(s.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
37
37
  `:`${c}
38
38
  ${r}
39
39
  `}let i=e.trim();if(i===""||i==="[]")return`[
@@ -41,66 +41,66 @@ ${r}
41
41
  ]
42
42
  `;let n=i.indexOf("[");if(n===-1)return;let l=i.slice(n+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,n+1)}
43
43
  ${r}${l}
44
- ${i.slice(n+1)}`}async function ds(e={}){let s=oA({plain:!1,json:!1,oneShot:!1});if(s.mode!=="rich")throw new t({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${s.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=Pe(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,n=Xe(process.env),a=ze(n)?.name??n,[{render:l},{createElement:c},{KeyProbe:p}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-rspsxpsr.js")]),w=()=>{},m=new Promise((b)=>{w=b}),h=Ve();U(()=>{h.close()}),SA(),process.stdout.write(RA);let g=l(c(p,{columns:ke(process.stdout.columns,be),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:w}),{exitOnCtrlC:!1,...r});return U(()=>g.unmount()),await m,g.unmount(),h.close(),qe(),await EA(),o}var bi=24,Nn=22;function Ln(e){let s=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${s===""?"":` ${s}`}`}function cs(e){let s=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?s:`-${e.short}, ${s}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(bi-1)} ${e.help}${i}`}var us=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
45
- delivery reads the channel back out of the key.`;function vi(e){let s=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((n)=>n.value.length))+2;s.push("",`${r.name}:`);for(let n of r.choices)s.push(` ${n.value.padEnd(i)}${n.help}`)}return s}function Mn(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Ln(e)} [flags]`,...vi(e),"","flags:",...an(e).map(cs)];if(e.flags.some((i)=>i.name==="session"))r.push("",us);return`${r.join(`
44
+ ${i.slice(n+1)}`}async function Xt(e={}){let s=ot({plain:!1,json:!1,oneShot:!1});if(s.mode!=="rich")throw new A({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${s.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=Pe(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,n=Xe(process.env),a=ze(n)?.name??n,[{render:l},{createElement:c},{KeyProbe:p}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-w8c37s9q.js")]),w=()=>{},m=new Promise((b)=>{w=b}),h=Ve();U(()=>{h.close()}),St(),process.stdout.write(Rt);let g=l(c(p,{columns:ke(process.stdout.columns,be),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:w}),{exitOnCtrlC:!1,...r});return U(()=>g.unmount()),await m,g.unmount(),h.close(),qe(),await Et(),o}var mi=24,Cn=22;function Nn(e){let s=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${t.slug} ${e.name}${s===""?"":` ${s}`}`}function Yt(e){let s=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?s:`-${e.short}, ${s}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(mi-1)} ${e.help}${i}`}var Qt=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
45
+ delivery reads the channel back out of the key.`;function fi(e){let s=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((n)=>n.value.length))+2;s.push("",`${r.name}:`);for(let n of r.choices)s.push(` ${n.value.padEnd(i)}${n.help}`)}return s}function Ln(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Nn(e)} [flags]`,...fi(e),"","flags:",...an(e).map(Yt)];if(e.flags.some((i)=>i.name==="session"))r.push("",Qt);return`${r.join(`
46
46
  `)}
47
- `}let s=Math.max(...nA.map((r)=>Ln(r).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...nA.map((r)=>` ${Ln(r).padEnd(s)}${r.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...sn.map(cs),"",us,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(Nn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Nn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Nn)}print stack traces on failure`].join(`
47
+ `}let s=Math.max(...nt.map((r)=>Nn(r).length))+2;return`${[`${t.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...nt.map((r)=>` ${Nn(r).padEnd(s)}${r.summary}`),` ${t.slug} --version`,` ${t.slug} --help`,"",`Per-command flags: ${t.slug} <command> --help`,"","global flags:",...sn.map(Yt),"",Qt,"","environment:",` ${`${t.envPrefix}BRAND`.padEnd(Cn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Cn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Cn)}print stack traces on failure`].join(`
48
48
  `)}
49
- `}function ms(e){if(!(e instanceof Error))return;let s=e.code;if(s!=="ERR_MODULE_NOT_FOUND"&&s!=="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 ki,statSync as Si}from"node:fs";var Ei=65536;function fs(e=process.env,s=(r)=>process.stderr.write(`${r}
50
- `)){let r=[];for(let[i,n]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||n===void 0||n==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(Si(n).size>Ei)continue;e[a]=ki(n,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(l){s(`${i} names ${n}, which could not be read (${l instanceof Error?l.message:String(l)}); ${a} is not set from it.`)}}return r}var Ri=[{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 Pi(e,s){return Ri.some((r)=>r.name===e&&s.includes(r.contains))}function Ti(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var ps;function hs(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(ps)return;if(Ti(e))return;let s=process.emitWarning;ps=s,process.emitWarning=(r,...i)=>{let n=typeof r==="string"?Ai(i):r.name,a=typeof r==="string"?r:r.message;if(Pi(n,a))return;Reflect.apply(s,process,[r,...i])}}function Ai(e){let s=e[0];return typeof s==="string"?s:"Warning"}var ys=96;async function bs(e){let s=await ue.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_([e.manifestPath])});try{let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let p=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(p,null,2)}
51
- `),o;return process.stdout.write(u([{label:"passages",value:String(p.passages)},{label:"files read",value:String(p.indexed.length)},{label:"conversations",value:p.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(p.sessions.length)},{label:"shared scopes",value:p.scopes.length===0?"none":p.scopes.join(", ")},{label:"dropped",value:p.dropped.length===0?"":p.dropped.join(", ")}])),process.stdout.write(p.indexed.length===0&&p.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":`
49
+ `}function Zt(e){if(!(e instanceof Error))return;let s=e.code;if(s!=="ERR_MODULE_NOT_FOUND"&&s!=="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 pi,statSync as hi}from"node:fs";var gi=65536;function es(e=process.env,s=(r)=>process.stderr.write(`${r}
50
+ `)){let r=[];for(let[i,n]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||n===void 0||n==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(hi(n).size>gi)continue;e[a]=pi(n,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(l){s(`${i} names ${n}, which could not be read (${l instanceof Error?l.message:String(l)}); ${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 wi(e,s){return yi.some((r)=>r.name===e&&s.includes(r.contains))}function bi(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var as;function ds(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(as)return;if(bi(e))return;let s=process.emitWarning;as=s,process.emitWarning=(r,...i)=>{let n=typeof r==="string"?vi(i):r.name,a=typeof r==="string"?r:r.message;if(wi(n,a))return;Reflect.apply(s,process,[r,...i])}}function vi(e){let s=e[0];return typeof s==="string"?s:"Warning"}var cs=96;async function ms(e){let s=await de.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_([e.manifestPath])});try{let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let p=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(p,null,2)}
51
+ `),o;return process.stdout.write(d([{label:"passages",value:String(p.passages)},{label:"files read",value:String(p.indexed.length)},{label:"conversations",value:p.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(p.sessions.length)},{label:"shared scopes",value:p.scopes.length===0?"none":p.scopes.join(", ")},{label:"dropped",value:p.dropped.length===0?"":p.dropped.join(", ")}])),process.stdout.write(p.indexed.length===0&&p.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":`
52
52
  Read: ${[...p.indexed,...p.sessions].join(", ")}
53
53
  `),o}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
54
- `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),d;let n=await r.searchMemory({query:i,limit:e.limit??10}),a=n.hits.filter((p)=>p.score>=n.threshold),l=e.all===!0?n.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:n.corpus,threshold:n.threshold,carried:n.carried??null,hits:l.map((p)=>({source:p.passage.source,at:p.passage.at,score:p.score,lexical:p.lexical,coverage:p.coverage,tokens:p.tokens,wouldInject:p.score>=n.threshold,carried:p.passage.source===n.carried,text:p.passage.text}))},null,2)}
55
- `),o;if(process.stdout.write(u([{label:"corpus",value:`${n.corpus} passage${n.corpus===1?"":"s"}`},{label:"threshold",value:n.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),n.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(l.length===0)return process.stdout.write(`
54
+ `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),u;let n=await r.searchMemory({query:i,limit:e.limit??10}),a=n.hits.filter((p)=>p.score>=n.threshold),l=e.all===!0?n.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:n.corpus,threshold:n.threshold,carried:n.carried??null,hits:l.map((p)=>({source:p.passage.source,at:p.passage.at,score:p.score,lexical:p.lexical,coverage:p.coverage,tokens:p.tokens,wouldInject:p.score>=n.threshold,carried:p.passage.source===n.carried,text:p.passage.text}))},null,2)}
55
+ `),o;if(process.stdout.write(d([{label:"corpus",value:`${n.corpus} passage${n.corpus===1?"":"s"}`},{label:"threshold",value:n.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),n.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(l.length===0)return process.stdout.write(`
56
56
  Nothing ${e.all===!0?"matched":`scored above ${n.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
57
- `),o;let c=Math.max(6,...l.map((p)=>ws(p,n.carried).length));process.stdout.write(`
57
+ `),o;let c=Math.max(6,...l.map((p)=>us(p,n.carried).length));process.stdout.write(`
58
58
  ${ne("SCORE",6)} ${ne("LEXICAL",7)} ${ne("COVER",5)} ${ne("SOURCE",c)} ${ne("LEARNED",10)} PASSAGE
59
- `);for(let p of l){let w=p.score>=n.threshold?" ":"·";process.stdout.write(`${ne(p.score.toFixed(3),6)} ${ne(p.lexical.toFixed(3),7)} ${ne(p.coverage.toFixed(2),5)} ${ne(ws(p,n.carried),c)} ${ne(p.passage.at.slice(0,10),10)} ${w}${Oi(p.passage.text)}
59
+ `);for(let p of l){let w=p.score>=n.threshold?" ":"·";process.stdout.write(`${ne(p.score.toFixed(3),6)} ${ne(p.lexical.toFixed(3),7)} ${ne(p.coverage.toFixed(2),5)} ${ne(us(p,n.carried),c)} ${ne(p.passage.at.slice(0,10),10)} ${w}${ki(p.passage.text)}
60
60
  `)}if(e.all===!0&&a.length<l.length)process.stdout.write(`
61
61
  ${l.length-a.length} shown below the threshold; a turn would not inject those.
62
62
  `);if(n.carried!==void 0&&l.some((p)=>p.passage.source===n.carried))process.stdout.write(`
63
63
  ${n.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
64
- `);return o}finally{await s.stop("cli-exit")}}function Oi(e){let s=e.replace(/\s+/g," ").trim();return s.length<=ys?s:`${s.slice(0,ys-1)}…`}function ne(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function ws(e,s){return e.passage.source===s?`${e.passage.source} *`:e.passage.source}var _i=["context_length","context_window","max_context_length","max_model_len"],Ci=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let s=e.prompt_tokens_details;return Qe(s)?s.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Dn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function $s(e,s){let r=Qe(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let n=s.toLowerCase();for(let a of i){if(!Qe(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===n||l.endsWith(`/${n}`)||n.endsWith(`/${l}`)))continue;for(let p of _i){let w=Dn(a[p]);if(w!==void 0)return{technique:"metadata",tokens:w,bound:"ceiling",detail:`GET /models published ${p}: ${w}`}}return}return}function Wn(e){let s=[/(?: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 s){let n=i.exec(e);if(n?.[1]===void 0)continue;let a=Dn(Number(n[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function vs(e){if(!Qe(e))return;let s=Dn(e.prompt_tokens)??0;for(let[r,i]of Ci){let n=i(e);if(typeof n==="number"&&Number.isFinite(n))return{cached:n,promptTokens:s,field:r}}return{cached:void 0,promptTokens:s,field:void 0}}function Ss(e,s,r){if(e===void 0||s===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(s.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=s.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${s.promptTokens} prompt tokens, via ${s.field}`};return{supported:!1,detail:`${s.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 _e(e){let s=e.filter((i)=>i.bound==="ceiling");return(s.length>0?s:e).reduce((i,n)=>i===void 0||n.tokens>i.tokens?n:i,void 0)}function Es(e,s,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${s.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(`
65
- `)}function Rs(e,s,r){return`measured ${s} against ${e} — ${r}`}function Ps(e,s){let r=Math.max(1,e),i=0,n=0;while(r<s)i+=r,n+=1,r*=2;return i+=s,n+=1,{requests:n,tokens:i}}var Ni=2000000000,xs=1024,Os=8192,_s=2097152;function Cs(e){return"context ".repeat(Math.max(1,e))}async function Ce(e){let s=await e.text();try{return{text:s,json:JSON.parse(s)}}catch{return{text:s,json:void 0}}}function Ns(e,s){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 n=i.message;if(typeof n==="string")return n}if(typeof r.message==="string")return r.message}return s}async function Fi(e,s,r){try{let i=await s(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:n}=await Ce(i),a=$s(n,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 Li(e,s,r){try{let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:Ni})}),{text:n,json:a}=await Ce(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 l=Ns(a,n.slice(0,400)),c=Wn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let p=/max_?tokens/i.test(l);return{window:p?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:p?c: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 Ts(e,s,r){let i=await s(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:n}=await Ce(i),a=typeof n==="object"&&n!==null?n.usage:void 0;return vs(a)}async function Ui(e,s,r){let i=`${Cs(xs)}
66
- Reply with the single character x.`;try{let n=await Ts(e,s,i),a=await Ts(e,s,i);return Ss(n,a,xs)}catch(n){return r.push(`the caching probe failed: ${n instanceof Error?n.message:String(n)}`),{supported:void 0,detail:"the probe did not complete"}}}async function Ki(e,s,r){let i=Os,n=0;while(i<=_s){let a;try{a=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Cs(i)}],max_tokens:1})})}catch(w){r.push(`the search stopped at ${i}: ${w instanceof Error?w.message:String(w)}`);break}if(a.ok){let{json:w}=await Ce(a),m=typeof w==="object"&&w!==null?w.usage:void 0,h=typeof m==="object"&&m!==null?m.prompt_tokens:void 0;n=typeof h==="number"&&Number.isFinite(h)?h:n,i*=2;continue}let{text:l,json:c}=await Ce(a),p=Wn(Ns(c,l.slice(0,400)));if(p!==void 0)return{technique:"search",tokens:p,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${p}`};break}if(n===0)return;return{technique:"search",tokens:n,bound:"floor",detail:`accepted a prompt the endpoint counted at ${n} tokens; nothing above it named a number`}}function Mi(e,s){let r=_e(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,n=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[k(` ${e.role} · ${e.modelId}`),u([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:n},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...s===void 0?[]:[{label:"price",value:`$${s}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((l)=>` · ${l}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Es(e.modelId,r.tokens,e.outputCeiling).split(`
64
+ `);return o}finally{await s.stop("cli-exit")}}function ki(e){let s=e.replace(/\s+/g," ").trim();return s.length<=cs?s:`${s.slice(0,cs-1)}…`}function ne(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function us(e,s){return e.passage.source===s?`${e.passage.source} *`:e.passage.source}var Si=["context_length","context_window","max_context_length","max_model_len"],Ei=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let s=e.prompt_tokens_details;return Qe(s)?s.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Mn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function fs(e,s){let r=Qe(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let n=s.toLowerCase();for(let a of i){if(!Qe(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===n||l.endsWith(`/${n}`)||n.endsWith(`/${l}`)))continue;for(let p of Si){let w=Mn(a[p]);if(w!==void 0)return{technique:"metadata",tokens:w,bound:"ceiling",detail:`GET /models published ${p}: ${w}`}}return}return}function Dn(e){let s=[/(?: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 s){let n=i.exec(e);if(n?.[1]===void 0)continue;let a=Mn(Number(n[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function ps(e){if(!Qe(e))return;let s=Mn(e.prompt_tokens)??0;for(let[r,i]of Ei){let n=i(e);if(typeof n==="number"&&Number.isFinite(n))return{cached:n,promptTokens:s,field:r}}return{cached:void 0,promptTokens:s,field:void 0}}function hs(e,s,r){if(e===void 0||s===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(s.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=s.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${s.promptTokens} prompt tokens, via ${s.field}`};return{supported:!1,detail:`${s.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 Oe(e){let s=e.filter((i)=>i.bound==="ceiling");return(s.length>0?s:e).reduce((i,n)=>i===void 0||n.tokens>i.tokens?n:i,void 0)}function ys(e,s,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${s.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(`
65
+ `)}function ws(e,s,r){return`measured ${s} against ${e} — ${r}`}function bs(e,s){let r=Math.max(1,e),i=0,n=0;while(r<s)i+=r,n+=1,r*=2;return i+=s,n+=1,{requests:n,tokens:i}}var Ri=2000000000,$s=1024,Ss=8192,Es=2097152;function Rs(e){return"context ".repeat(Math.max(1,e))}async function _e(e){let s=await e.text();try{return{text:s,json:JSON.parse(s)}}catch{return{text:s,json:void 0}}}function Ps(e,s){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 n=i.message;if(typeof n==="string")return n}if(typeof r.message==="string")return r.message}return s}async function Pi(e,s,r){try{let i=await s(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:n}=await _e(i),a=fs(n,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 Ti(e,s,r){try{let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:Ri})}),{text:n,json:a}=await _e(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 l=Ps(a,n.slice(0,400)),c=Dn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let p=/max_?tokens/i.test(l);return{window:p?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:p?c: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 vs(e,s,r){let i=await s(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:n}=await _e(i),a=typeof n==="object"&&n!==null?n.usage:void 0;return ps(a)}async function Oi(e,s,r){let i=`${Rs($s)}
66
+ Reply with the single character x.`;try{let n=await vs(e,s,i),a=await vs(e,s,i);return hs(n,a,$s)}catch(n){return r.push(`the caching probe failed: ${n instanceof Error?n.message:String(n)}`),{supported:void 0,detail:"the probe did not complete"}}}async function _i(e,s,r){let i=Ss,n=0;while(i<=Es){let a;try{a=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Rs(i)}],max_tokens:1})})}catch(w){r.push(`the search stopped at ${i}: ${w instanceof Error?w.message:String(w)}`);break}if(a.ok){let{json:w}=await _e(a),m=typeof w==="object"&&w!==null?w.usage:void 0,h=typeof m==="object"&&m!==null?m.prompt_tokens:void 0;n=typeof h==="number"&&Number.isFinite(h)?h:n,i*=2;continue}let{text:l,json:c}=await _e(a),p=Dn(Ps(c,l.slice(0,400)));if(p!==void 0)return{technique:"search",tokens:p,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${p}`};break}if(n===0)return;return{technique:"search",tokens:n,bound:"floor",detail:`accepted a prompt the endpoint counted at ${n} tokens; nothing above it named a number`}}function Ci(e,s){let r=Oe(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,n=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[k(` ${e.role} · ${e.modelId}`),d([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:n},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...s===void 0?[]:[{label:"price",value:`$${s}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((l)=>` · ${l}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",ys(e.modelId,r.tokens,e.outputCeiling).split(`
67
67
  `).map((l)=>` ${l}`).join(`
68
68
  `)]].join(`
69
- `)}async function js(e){let s=e.fetch??globalThis.fetch;try{let r=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:i}=r,n=NA(i).filter((p)=>p.role===p.configuredAs),a=!1;if(e.window){let p=Ps(Os,_s),w=p.tokens*n.length,m=e.price===void 0?"":` ≈ $${(w/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${p.requests} requests per role, about ${w.toLocaleString("en-US")} input tokens in total${m}.
69
+ `)}async function xs(e){let s=e.fetch??globalThis.fetch;try{let r=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:i}=r,n=Nt(i).filter((p)=>p.role===p.configuredAs),a=!1;if(e.window){let p=bs(Ss,Es),w=p.tokens*n.length,m=e.price===void 0?"":` ≈ $${(w/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${p.requests} requests per role, about ${w.toLocaleString("en-US")} input tokens in total${m}.
70
70
  That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
71
71
  Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
72
- `),a=e.yes||await bt("spend it?"),process.stdout.write(a?`
72
+ `),a=e.yes||await bA("spend it?"),process.stdout.write(a?`
73
73
  `:`
74
74
  Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
75
75
 
76
76
  `)}let l=[];for(let p of n){let w=i.model[p.role]??i.model.main;if(w.baseUrl===void 0){process.stdout.write(`model.${p.role} uses the ${w.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${p.window.contextWindow.toLocaleString("en-US")} tokens (${p.window.source}).
77
- `);continue}let m={chat:Co(w.baseUrl),models:ti(w.baseUrl),headers:ni(w.apiKeyEnv,r.env,`model.${p.role}`),modelId:w.id},h=[],g=[],b=await Fi(m,s,h);if(b!==void 0)g.push(b);let P=await Li(m,s,h);if(P.window!==void 0)g.push(P.window);let R=await Ui(m,s,h);if(a){let S=await Ki(m,s,h);if(S!==void 0)g.push(S)}l.push({role:p.role,modelId:w.id,baseUrl:w.baseUrl,declared:p.window.contextWindow,declaredSource:p.window.source,findings:g,cache:R,outputCeiling:P.outputCeiling,failures:h})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:l},null,2)}
78
- `),o;let c=e.write?await Di(r.path,l):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${l.length} role${l.length===1?"":"s"}`,...l.map((p)=>Mi(p,e.price)),"",...e.write?[...c.written.length===0?[]:[" written to the manifest:",...c.written.map((p)=>` ${p}`)],...c.refused.length===0?[]:[" not written:",...c.refused.map((p)=>` ${p}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Bi(l)],""].join(`
77
+ `);continue}let m={chat:Co(w.baseUrl),models:Ai(w.baseUrl),headers:ni(w.apiKeyEnv,r.env,`model.${p.role}`),modelId:w.id},h=[],g=[],b=await Pi(m,s,h);if(b!==void 0)g.push(b);let P=await Ti(m,s,h);if(P.window!==void 0)g.push(P.window);let R=await Oi(m,s,h);if(a){let S=await _i(m,s,h);if(S!==void 0)g.push(S)}l.push({role:p.role,modelId:w.id,baseUrl:w.baseUrl,declared:p.window.contextWindow,declaredSource:p.window.source,findings:g,cache:R,outputCeiling:P.outputCeiling,failures:h})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:l},null,2)}
78
+ `),o;let c=e.write?await Ni(r.path,l):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${l.length} role${l.length===1?"":"s"}`,...l.map((p)=>Ci(p,e.price)),"",...e.write?[...c.written.length===0?[]:[" written to the manifest:",...c.written.map((p)=>` ${p}`)],...c.refused.length===0?[]:[" not written:",...c.refused.map((p)=>` ${p}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Fi(l)],""].join(`
79
79
  `)),o}catch(r){if(f(r))return process.stderr.write(`${r.format()}
80
- `),d;throw r}}async function Di(e,s){let r=[],i=[];for(let n of s){let a=_e(n.findings);if(a===void 0){i.push(`${n.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${n.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===n.declared){i.push(`${n.role}: already ${a.tokens}, nothing to change`);continue}await We({file:e,path:["model",n.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${n.role}: ${n.declared} → ${a.tokens}`)}return{written:r,refused:i}}function Bi(e){let s=e.filter((a)=>_e(a.findings)?.bound==="ceiling");if(s.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=s[0],i=r===void 0?void 0:_e(r.findings);if(r===void 0||i===void 0)return"";let n=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}`,` # ${Rs(n,new Date().toISOString().slice(0,10),i.detail)}`].join(`
81
- `)}import{existsSync as Bs,rmSync as oa}from"node:fs";import{resolve as ia}from"node:path";var Yi={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Us(e){if(e===null||typeof e!=="object")return!1;let s=e.kind;return s==="network"||s==="env"||s==="fs"||s==="exec"||s==="store"}async function Ks(e,s={}){let r=[],i=[],n=s.hostVersion??Ge,a=(g,b,P)=>{r.push({level:"error",check:g,message:b,hint:P})},l=(g,b,P)=>{r.push({level:"warning",check:g,message:b,hint:P})};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(lr(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 c=lr(n,e.dispachApi);if(c===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(!c)l("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${n}).`,"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()==="*")l("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[g,b]of(e.permissions??[]).entries())if(!Us(b))a("permissions",`\`permissions[${g}]\` 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 p=s.config??{};if(e.configSchema!==void 0){let g=e.configSchema.safeParse(p);if(g.success)p=g.data;else l("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 w={defineChannel:(g)=>i.push(`channel:${g}`),defineToolProvider:(g)=>i.push(`toolProvider:${g}`),defineModelTransport:(g)=>i.push(`modelTransport:${g}`),defineMediaProvider:(g)=>i.push(`mediaProvider:${g}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(g)=>i.push(`middleware:${g.name}`),defineRoute:(g)=>i.push(`route:${g.method} ${g.path}`),config:p,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Yi,events:new cr({runtimeId:"conformance"})},m=performance.now();try{await e.setup(w)}catch(g){a("setup",`\`setup\` threw: ${g instanceof Error?g.message:String(g)}`,"`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 h=Math.round((performance.now()-m)*100)/100;if(h>Ir)a("setup budget",`\`setup\` took ${h} ms against a ${Ir} 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)l("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((g)=>g.level!=="error"),findings:r,registered:i,setupMs:h,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Us)}}}import{existsSync as pe,mkdirSync as Qi,readdirSync as ea,readFileSync as Gn,renameSync as Ms,rmSync as le,writeFileSync as na}from"node:fs";import{join as X}from"node:path";var Ds=".origin.json";function ta(e){let s=X(e,Ds);if(!pe(s))return;try{return JSON.parse(Gn(s,"utf8"))}catch{return}}function Bn(e){let s=se(e),r;try{r=ea(s)}catch{return[]}let i=[];for(let n of r.sort()){if(n.startsWith(".")||n.endsWith(".partial"))continue;let a=X(s,n);if(!pe(X(a,"package.json"))&&!pe(X(a,"index.js")))continue;let l=ta(a);i.push({name:n,dir:a,...l===void 0?{}:{origin:l}})}return i}function Hs(e){let s=X(e,"package.json");if(!pe(s))return X(e,"index.js");try{let r=JSON.parse(Gn(s,"utf8"));if(typeof r.main==="string"&&r.main!=="")return X(e,r.main)}catch{}return X(e,"index.js")}function Ws(e){let s=X(e,"package.json");if(!pe(s))return;let r;try{r=JSON.parse(Gn(s,"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(pe(X(e,"node_modules")))return;let n=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${n}${i.length>4?", …":""}) and ships no node_modules`}function Gs(e,s){let i=((s??e).split("/").filter((n)=>n.length>0).pop()??"").replace(/\.git$/,"");if(!Tt(i))throw new t({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 qs(e,s={}){let r=s.git??Hr,i=Sr(e.name,s.env),n=`${i}.partial`;Qi(se(s.env),{recursive:!0}),le(n,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,n]);if(a.code!==0)throw le(n,{recursive:!0,force:!0}),sa(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],n),c=l.code===0?l.stdout.trim():"unknown",p=e.path===void 0?n:X(n,e.path);if(!pe(p))throw le(n,{recursive:!0,force:!0}),new t({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${c}`,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."});le(X(p,".git"),{recursive:!0,force:!0});try{await s.inspect?.(p)}catch(m){throw le(n,{recursive:!0,force:!0}),m}if(le(i,{recursive:!0,force:!0}),p===n)Ms(n,i);else Ms(p,i),le(n,{recursive:!0,force:!0});let w={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:c,fetchedAt:new Date().toISOString()};return na(X(i,Ds),`${JSON.stringify(w,null,4)}
82
- `),{dir:i,commit:c}}function sa(e,s,r){let i=s.trim().split(`
83
- `).slice(-3).join(" ");if(r)return new t({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 t({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 Xs(e){switch(e.action){case"list":return await aa(e);case"add":return await la(e);case"remove":return await fa(e);default:throw new t({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 s=await ue.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(e.env),scriptRunner:de(),channels:ce,env:_([e.manifestPath]),store:F(e.env),lease:!1});U(()=>s.stop("cli-exit"));let r=[...s.plugins.values()].flat(),i=Bn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:Kr},null,2)}
80
+ `),u;throw r}}async function Ni(e,s){let r=[],i=[];for(let n of s){let a=Oe(n.findings);if(a===void 0){i.push(`${n.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${n.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===n.declared){i.push(`${n.role}: already ${a.tokens}, nothing to change`);continue}await We({file:e,path:["model",n.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${n.role}: ${n.declared} → ${a.tokens}`)}return{written:r,refused:i}}function Fi(e){let s=e.filter((a)=>Oe(a.findings)?.bound==="ceiling");if(s.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=s[0],i=r===void 0?void 0:Oe(r.findings);if(r===void 0||i===void 0)return"";let n=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}`,` # ${ws(n,new Date().toISOString().slice(0,10),i.detail)}`].join(`
81
+ `)}import{existsSync as Ms,rmSync as Yi}from"node:fs";import{resolve as Qi}from"node:path";var Li={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Ts(e){if(e===null||typeof e!=="object")return!1;let s=e.kind;return s==="network"||s==="env"||s==="fs"||s==="exec"||s==="store"}async function Os(e,s={}){let r=[],i=[],n=s.hostVersion??Ge,a=(g,b,P)=>{r.push({level:"error",check:g,message:b,hint:P})},l=(g,b,P)=>{r.push({level:"warning",check:g,message:b,hint:P})};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(lr(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 c=lr(n,e.dispachApi);if(c===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(!c)l("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${n}).`,"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()==="*")l("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[g,b]of(e.permissions??[]).entries())if(!Ts(b))a("permissions",`\`permissions[${g}]\` 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 p=s.config??{};if(e.configSchema!==void 0){let g=e.configSchema.safeParse(p);if(g.success)p=g.data;else l("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 w={defineChannel:(g)=>i.push(`channel:${g}`),defineToolProvider:(g)=>i.push(`toolProvider:${g}`),defineModelTransport:(g)=>i.push(`modelTransport:${g}`),defineMediaProvider:(g)=>i.push(`mediaProvider:${g}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(g)=>i.push(`middleware:${g.name}`),defineRoute:(g)=>i.push(`route:${g.method} ${g.path}`),config:p,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Li,events:new cr({runtimeId:"conformance"})},m=performance.now();try{await e.setup(w)}catch(g){a("setup",`\`setup\` threw: ${g instanceof Error?g.message:String(g)}`,"`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 h=Math.round((performance.now()-m)*100)/100;if(h>Ir)a("setup budget",`\`setup\` took ${h} ms against a ${Ir} 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)l("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((g)=>g.level!=="error"),findings:r,registered:i,setupMs:h,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Ts)}}}import{existsSync as he,mkdirSync as Ui,readdirSync as Ki,readFileSync as Wn,renameSync as _s,rmSync as pe,writeFileSync as Mi}from"node:fs";import{join as X}from"node:path";var Cs=".origin.json";function Di(e){let s=X(e,Cs);if(!he(s))return;try{return JSON.parse(Wn(s,"utf8"))}catch{return}}function Gn(e){let s=se(e),r;try{r=Ki(s)}catch{return[]}let i=[];for(let n of r.sort()){if(n.startsWith(".")||n.endsWith(".partial"))continue;let a=X(s,n);if(!he(X(a,"package.json"))&&!he(X(a,"index.js")))continue;let l=Di(a);i.push({name:n,dir:a,...l===void 0?{}:{origin:l}})}return i}function Ns(e){let s=X(e,"package.json");if(!he(s))return X(e,"index.js");try{let r=JSON.parse(Wn(s,"utf8"));if(typeof r.main==="string"&&r.main!=="")return X(e,r.main)}catch{}return X(e,"index.js")}function js(e){let s=X(e,"package.json");if(!he(s))return;let r;try{r=JSON.parse(Wn(s,"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(he(X(e,"node_modules")))return;let n=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${n}${i.length>4?", …":""}) and ships no node_modules`}function Us(e,s){let i=((s??e).split("/").filter((n)=>n.length>0).pop()??"").replace(/\.git$/,"");if(!TA(i))throw new A({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 Ks(e,s={}){let r=s.git??Hr,i=Sr(e.name,s.env),n=`${i}.partial`;Ui(se(s.env),{recursive:!0}),pe(n,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,n]);if(a.code!==0)throw pe(n,{recursive:!0,force:!0}),Bi(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],n),c=l.code===0?l.stdout.trim():"unknown",p=e.path===void 0?n:X(n,e.path);if(!he(p))throw pe(n,{recursive:!0,force:!0}),new A({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${c}`,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."});pe(X(p,".git"),{recursive:!0,force:!0});try{await s.inspect?.(p)}catch(m){throw pe(n,{recursive:!0,force:!0}),m}if(pe(i,{recursive:!0,force:!0}),p===n)_s(n,i);else _s(p,i),pe(n,{recursive:!0,force:!0});let w={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:c,fetchedAt:new Date().toISOString()};return Mi(X(i,Cs),`${JSON.stringify(w,null,4)}
82
+ `),{dir:i,commit:c}}function Bi(e,s,r){let i=s.trim().split(`
83
+ `).slice(-3).join(" ");if(r)return new A({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 A({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 Ds(e){switch(e.action){case"list":return await ea(e);case"add":return await ta(e);case"remove":return await aa(e);default:throw new A({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${t.slug} plugins list <agent>\`.`})}}async function ea(e){let s=await de.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(e.env),scriptRunner:ue(),channels:ce,env:_([e.manifestPath]),store:F(e.env),lease:!1});U(()=>s.stop("cli-exit"));let r=[...s.plugins.values()].flat(),i=Gn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:Kr},null,2)}
84
84
  `),o;if(r.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
85
85
 
86
86
  ${Kr.map((c)=>` - "${c}"`).join(`
87
87
  `)}
88
88
 
89
- Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${A.slug} plugins add <agent> <repo>\`.
89
+ Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${t.slug} plugins add <agent> <repo>\`.
90
90
  `),i.length>0)process.stdout.write(`
91
91
  Installed in ${se(e.env)} and named by no agent:
92
92
  ${i.map((c)=>` - "${c.name}"`).join(`
93
93
  `)}
94
- `);return o}let n=r.map((c)=>({label:c.name,value:`${c.version} ${`${c.setupMs} ms`.padStart(9)}`,note:`${da(c.spec,c.lookup,i)} — ${c.registered.length===0?"registered nothing":c.registered.join(", ")}`}));process.stdout.write(`${u(n)}
94
+ `);return o}let n=r.map((c)=>({label:c.name,value:`${c.version} ${`${c.setupMs} ms`.padStart(9)}`,note:`${na(c.spec,c.lookup,i)} — ${c.registered.length===0?"registered nothing":c.registered.join(", ")}`}));process.stdout.write(`${d(n)}
95
95
  `);let a=r.filter((c)=>c.permissions.length>0);if(a.length>0){process.stdout.write(`
96
96
  Declared access — advisory in v1, recorded and not enforced:
97
- `);for(let c of a)for(let p of c.permissions)process.stdout.write(` ${c.name} ${p.kind} ${zs(p)}
97
+ `);for(let c of a)for(let p of c.permissions)process.stdout.write(` ${c.name} ${p.kind} ${Hs(p)}
98
98
  `)}let l=i.filter((c)=>!r.some((p)=>p.spec===c.name));if(l.length>0)process.stdout.write(`
99
99
  Also installed, named by no agent: ${l.map((c)=>c.name).join(", ")}
100
- `);return o}function da(e,s,r){if(s!=="installed")return s==="registry"?"built in":"imported";let i=r.find((n)=>n.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function zs(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 la(e){let s=e.rest?.[0];if(s===void 0||s==="")throw new t({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=sr(s)?{url:ia(s.replace(/^file:\/\//,""))}:rr(s),i=e.ref??r.ref,n=e.name===void 0?Gs(r.url,r.path):ca(e.name),a=Bn(e.env).find((h)=>h.name===n);if(a?.origin!==void 0&&a.origin.url!==r.url)throw new t({code:"plugin_name_taken",message:`A different plugin is already installed as "${n}" — 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> ${n}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${n}"…
101
- `);let l,c=await qs({name:n,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(h)=>{let g=Ws(h);if(g!==void 0)throw new t({code:"plugin_not_self_contained",message:`${n} cannot be loaded as fetched: ${g}`,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 b=Hs(h);if(!Bs(b))throw new t({code:"plugin_entry_missing",message:`${n} has no entry file — ${b.slice(h.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 P=await ua(n,b);if(l=await Ks(P),!l.ok)throw new t({code:"plugin_not_conformant",message:`${l.declared.name} does not meet the plugin contract:
100
+ `);return o}function na(e,s,r){if(s!=="installed")return s==="registry"?"built in":"imported";let i=r.find((n)=>n.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function Hs(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 ta(e){let s=e.rest?.[0];if(s===void 0||s==="")throw new A({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${t.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=sr(s)?{url:Qi(s.replace(/^file:\/\//,""))}:rr(s),i=e.ref??r.ref,n=e.name===void 0?Us(r.url,r.path):sa(e.name),a=Gn(e.env).find((h)=>h.name===n);if(a?.origin!==void 0&&a.origin.url!==r.url)throw new A({code:"plugin_name_taken",message:`A different plugin is already installed as "${n}" — 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 \`${t.slug} plugins remove <agent> ${n}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${n}"…
101
+ `);let l,c=await Ks({name:n,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(h)=>{let g=js(h);if(g!==void 0)throw new A({code:"plugin_not_self_contained",message:`${n} cannot be loaded as fetched: ${g}`,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 b=Ns(h);if(!Ms(b))throw new A({code:"plugin_entry_missing",message:`${n} has no entry file — ${b.slice(h.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 P=await oa(n,b);if(l=await Os(P),!l.ok)throw new A({code:"plugin_not_conformant",message:`${l.declared.name} does not meet the plugin contract:
102
102
  ${l.findings.filter((R)=>R.level==="error").map((R)=>` ${R.check}: ${R.message}`).join(`
103
- `)}`,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(mo(J,l.declared.apiRange)!==!0)throw new t({code:"plugin_api_mismatch",message:`${l.declared.name} ${l.declared.version} supports host ${l.declared.apiRange}, and this host is ${J}`,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."})}}),p=l?.declared;if(process.stdout.write(`
103
+ `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${t.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(mo(J,l.declared.apiRange)!==!0)throw new A({code:"plugin_api_mismatch",message:`${l.declared.name} ${l.declared.version} supports host ${l.declared.apiRange}, and this host is ${J}`,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."})}}),p=l?.declared;if(process.stdout.write(`
104
104
  ${p?.name??n} ${p?.version??"?"} (${c.commit})
105
105
  from ${r.url}${i===void 0?"":` at ${i}`}
106
106
  installed ${c.dir}
@@ -108,7 +108,7 @@ ${p?.name??n} ${p?.version??"?"} (${c.commit})
108
108
  registers ${l===void 0||l.registered.length===0?"nothing":l.registered.join(", ")}
109
109
  `),p!==void 0&&p.permissions.length>0)process.stdout.write(`
110
110
  It declares access to:
111
- ${p.permissions.map((h)=>` ${h.kind} ${zs(h)}`).join(`
111
+ ${p.permissions.map((h)=>` ${h.kind} ${Hs(h)}`).join(`
112
112
  `)}
113
113
  `+"\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
114
114
  boundary. Install plugins you trust.
@@ -119,41 +119,41 @@ plugin that declares nothing can still do anything this process can. Install plu
119
119
  note: ${h.check} — ${h.message}
120
120
  `);if(p!==void 0&&p.name!==n)process.stdout.write(`
121
121
  note: it calls itself "${p.name}"; the \`plugins:\` entry is the directory, "${n}".
122
- `);let m=await ma(e.manifestPath,n);return process.stdout.write(m==="already"?`
122
+ `);let m=await ia(e.manifestPath,n);return process.stdout.write(m==="already"?`
123
123
  ${e.manifestPath} already names "${n}".
124
124
  `:`
125
125
  Added "${n}" to the plugins: block in ${e.manifestPath}.
126
126
  It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
127
- `),o}function ca(e){if(Tt(e))return e;throw new t({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 ua(e,s){let r;try{r=await import(s)}catch(n){throw new t({code:"plugin_import_failed",message:`${e}: ${s} could not be imported — ${n instanceof Error?n.message:String(n)}`,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:n})}let i=r.default;if(i===null||typeof i!=="object")throw new t({code:"plugin_malformed",message:`${e}: ${s} 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 t({code:"plugin_malformed",message:`${e}: the default export of ${s} 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 ma(e,s){let i=G(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===s))return"already";return await We({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),s]}),"written"}async function fa(e){let s=e.rest?.[0];if(s===void 0||s==="")throw new t({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=(G(e.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec);if(i.includes(s))await We({file:e.manifestPath,path:["plugins"],value:i.filter((l)=>l!==s)}),process.stdout.write(`Dropped "${s}" from ${e.manifestPath}.
128
- Run \`${A.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
127
+ `),o}function sa(e){if(TA(e))return e;throw new A({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 oa(e,s){let r;try{r=await import(s)}catch(n){throw new A({code:"plugin_import_failed",message:`${e}: ${s} could not be imported — ${n instanceof Error?n.message:String(n)}`,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:n})}let i=r.default;if(i===null||typeof i!=="object")throw new A({code:"plugin_malformed",message:`${e}: ${s} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${t.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 A({code:"plugin_malformed",message:`${e}: the default export of ${s} 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,s){let i=G(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===s))return"already";return await We({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),s]}),"written"}async function aa(e){let s=e.rest?.[0];if(s===void 0||s==="")throw new A({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${t.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(G(e.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec);if(i.includes(s))await We({file:e.manifestPath,path:["plugins"],value:i.filter((l)=>l!==s)}),process.stdout.write(`Dropped "${s}" from ${e.manifestPath}.
128
+ Run \`${t.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
129
129
  `);else process.stdout.write(`${e.manifestPath} does not name "${s}".
130
- `);let n=Sr(s,e.env);if(!Bs(n))return process.stdout.write(`Nothing installed at ${n}.
131
- `),o;let a=pa(s,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${n} — still named by ${a.join(", ")}.
130
+ `);let n=Sr(s,e.env);if(!Ms(n))return process.stdout.write(`Nothing installed at ${n}.
131
+ `),o;let a=da(s,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${n} — still named by ${a.join(", ")}.
132
132
  Remove it from those agents first, or delete the directory by hand.
133
- `),o;return oa(n,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${n}.
134
- `),o}function pa(e,s,r){let i=[];for(let n of Ae(r)){if(n.manifestPath===s)continue;try{if((G(n.manifestPath).plugins??[]).map((c)=>typeof c==="string"?c:c.spec).includes(e))i.push(n.ref)}catch{}}return i}import{existsSync as Sa,readdirSync as br,rmSync as zn,statSync as vr}from"node:fs";import{homedir as Ea}from"node:os";import{join as kr}from"node:path";function Ys(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let s=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${s} — 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 Qs(e){let s=[];if(e.running!==void 0)s.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)s.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(s.push({kind:"store",detail:`delete ${M(r.sessions,"conversation")}, ${M(r.messages,"message")}, ${M(r.passages,"memory passage")}`}),e.logs.length>0)s.push({kind:"logs",detail:`delete ${M(e.logs.length,"log file")}`})}return s.push({kind:"directory",detail:`delete ${e.dir}`}),s}function tr(e){let s=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${M(e.files.count,"file")}, ${At(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(s.sessions,"conversation")}, ${M(s.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${M(s.sessions,"conversation")}, ${M(s.messages,"message")}, ${M(s.turns,"turn")}`},{label:"memory",value:`${M(s.passages,"passage")} from ${M(s.memorySources,"source")}`},{label:"outbox",value:s.outbox===0?"nothing queued":`${M(s.outbox,"delivery")}${s.outboxPending===0?"":`, ${s.outboxPending} not yet sent`}`,...s.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:s.schedules===0?"none":M(s.schedules,"schedule"),...s.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${M(e.logs.length,"file")}, ${At(e.logs.reduce((i,n)=>i+n.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})`}),u(r)}function fr(e){if(e.length===0)return"";return e.map((s)=>{let r=s.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(s.logs.length>0)i.push(`${M(s.logs.length,"log file")}, ${At(s.logs.reduce((n,a)=>n+a.bytes,0))}`);return` ${s.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
135
- `)}function M(e,s){return`${e} ${s}${e===1?"":"s"}`}import{homedir as ha}from"node:os";var pr=12000,ga=250;async function en(e){if(e.manifestPath!==void 0)return await ya(e,e.manifestPath);return await wa(e)}async function ya(e,s){let r=ka(s),i=[];if(e.dryRun===!0){let c=await je(r,e.store);return process.stdout.write(`would stop 1 agent:
133
+ `),o;return Yi(n,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${n}.
134
+ `),o}function da(e,s,r){let i=[];for(let n of te(r)){if(n.manifestPath===s)continue;try{if((G(n.manifestPath).plugins??[]).map((c)=>typeof c==="string"?c:c.spec).includes(e))i.push(n.ref)}catch{}}return i}import{existsSync as ya,readdirSync as Ys,rmSync as zn,statSync as Qs}from"node:fs";import{homedir as wa}from"node:os";import{join as fr}from"node:path";function Ws(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let s=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${s} — 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 Gs(e){let s=[];if(e.running!==void 0)s.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)s.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(s.push({kind:"store",detail:`delete ${M(r.sessions,"conversation")}, ${M(r.messages,"message")}, ${M(r.passages,"memory passage")}`}),e.logs.length>0)s.push({kind:"logs",detail:`delete ${M(e.logs.length,"log file")}`})}return s.push({kind:"directory",detail:`delete ${e.dir}`}),s}function qs(e){let s=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${M(e.files.count,"file")}, ${tA(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(s.sessions,"conversation")}, ${M(s.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${M(s.sessions,"conversation")}, ${M(s.messages,"message")}, ${M(s.turns,"turn")}`},{label:"memory",value:`${M(s.passages,"passage")} from ${M(s.memorySources,"source")}`},{label:"outbox",value:s.outbox===0?"nothing queued":`${M(s.outbox,"delivery")}${s.outboxPending===0?"":`, ${s.outboxPending} not yet sent`}`,...s.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:s.schedules===0?"none":M(s.schedules,"schedule"),...s.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${M(e.logs.length,"file")}, ${tA(e.logs.reduce((i,n)=>i+n.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})`}),d(r)}function Bs(e){if(e.length===0)return"";return e.map((s)=>{let r=s.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(s.logs.length>0)i.push(`${M(s.logs.length,"log file")}, ${tA(s.logs.reduce((n,a)=>n+a.bytes,0))}`);return` ${s.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
135
+ `)}function M(e,s){return`${e} ${s}${e===1?"":"s"}`}import{homedir as la}from"node:os";var Xs=12000,ca=250;async function en(e){if(e.manifestPath!==void 0)return await ua(e,e.manifestPath);return await ma(e)}async function ua(e,s){let r=ga(s),i=[];if(e.dryRun===!0){let c=await je(r,e.store);return process.stdout.write(`would stop 1 agent:
136
136
  ${Q(`${r} — ${c===void 0?"not running; would be switched off for the next start":c.baseUrl===void 0?`pid ${c.pid} (${c.mode}), which serves no HTTP — would be signalled`:`pid ${c.pid} (${c.mode}) at ${c.baseUrl}, which would drop it and keep serving`}`)}
137
- `),o}await nr(r,!1,e.reason,e.store),i.push("switched off for the next start");let n=await je(r,e.store),a=!0;if(n===void 0)i.push("nothing was running");else if(n.baseUrl===void 0){let c=await Ze(n.pid,"SIGTERM");a=c||await Ze(n.pid,"SIGKILL",!0),i.push(c?`pid ${n.pid} stopped cleanly`:a?`pid ${n.pid} had to be killed`:`pid ${n.pid} would not stop — check it by hand`)}else{let c=await dA(n,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},s);if(c.ok)i.push(`pid ${n.pid} dropped it and kept serving`);else if(c.status===409)a=!1,i.push(c.detail??"a turn is running");else if(c.status===401)a=!1,i.push(`pid ${n.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${n.pid} at ${n.baseUrl} could not be reached${c.detail===void 0?"":`: ${c.detail}`}`)}let l={agentId:r,service:!1,...n===void 0?{}:{pid:n.pid,mode:n.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[l]},null,2)}
138
- `);else process.stdout.write(`${u([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:l.note}])}
137
+ `),o}await nr(r,!1,e.reason,e.store),i.push("switched off for the next start");let n=await je(r,e.store),a=!0;if(n===void 0)i.push("nothing was running");else if(n.baseUrl===void 0){let c=await Ze(n.pid,"SIGTERM");a=c||await Ze(n.pid,"SIGKILL",!0),i.push(c?`pid ${n.pid} stopped cleanly`:a?`pid ${n.pid} had to be killed`:`pid ${n.pid} would not stop — check it by hand`)}else{let c=await ut(n,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},s);if(c.ok)i.push(`pid ${n.pid} dropped it and kept serving`);else if(c.status===409)a=!1,i.push(c.detail??"a turn is running");else if(c.status===401)a=!1,i.push(`pid ${n.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${n.pid} at ${n.baseUrl} could not be reached${c.detail===void 0?"":`: ${c.detail}`}`)}let l={agentId:r,service:!1,...n===void 0?{}:{pid:n.pid,mode:n.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[l]},null,2)}
138
+ `);else process.stdout.write(`${d([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:l.note}])}
139
139
  `),process.stdout.write(`
140
- Stays off across restarts. \`${A.slug} start ${r}\` switches it back on.
141
- `);return a?o:d}async function wa(e){let s=e.platform??process.platform,r=s==="darwin"?nn(s,{home:ha(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await ba(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
140
+ Stays off across restarts. \`${t.slug} start ${r}\` switches it back on.
141
+ `);return a?o:u}async function ma(e){let s=e.platform??process.platform,r=s==="darwin"?nn(s,{home:la(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await fa(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
142
142
  `:`Nothing is running — no service is installed and no process holds an agent.
143
143
  `),o;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
144
- ${i.map((a)=>Q(va(a))).join(`
144
+ ${i.map((a)=>Q(ha(a))).join(`
145
145
  `)}
146
- `),o;let n=[];for(let a of i)n.push(await $a(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:n},null,2)}
147
- `);else{let a=n.map((l)=>({label:hr(l.agentId),value:l.stopped?"stopped":"STILL RUNNING",note:l.note}));if(process.stdout.write(`${u(a)}
146
+ `),o;let n=[];for(let a of i)n.push(await pa(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:n},null,2)}
147
+ `);else{let a=n.map((l)=>({label:zs(l.agentId),value:l.stopped?"stopped":"STILL RUNNING",note:l.note}));if(process.stdout.write(`${d(a)}
148
148
  `),n.some((l)=>l.service&&l.stopped))process.stdout.write(`
149
149
  Services are disabled as well as unloaded, so they stay stopped across a reboot.
150
- Start one again with \`${A.slug} daemon start <agent>\`.
150
+ Start one again with \`${t.slug} daemon start <agent>\`.
151
151
  `);if(n.some((l)=>l.forced===!0))process.stdout.write(`
152
152
  Something had to be killed rather than asked. A forced stop skips the runtime's own
153
153
  cleanup, so a command the agent had left running in the background may still be alive —
154
154
  \`ps\` will show it if so.
155
- `)}return n.every((a)=>a.stopped)?o:d}async function ba(e,s){let r=`${A.slug}.agent.`,i=new Map;for(let n of e?.labels(r)??[]){let a=n.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let n=await fe.open({path:s??F()});for(let a of await n.leases.all()){if(a.pid===process.pid||!z(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await n.close()}catch{}return[...i.values()].sort((n,a)=>n.agentId.localeCompare(a.agentId))}async function $a(e,s){let r=[];if(e.service&&s!==void 0)try{s.stop($o(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(!z(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await Ze(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let n=await Ze(e.pid,"SIGKILL",!0);return r.push(n?`pid ${e.pid} did not stop in ${Math.round(pr/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:n,forced:!0,note:r.join(" · ")}}async function Ze(e,s,r=!1){try{process.kill(r?-e:e,s)}catch(n){if(n.code==="ESRCH")return!0;if(r)try{process.kill(e,s)}catch{return!z(e)}}let i=Date.now()+(s==="SIGKILL"?3000:pr);while(Date.now()<i){if(!z(e))return!0;await new Promise((n)=>setTimeout(n,ga))}return!z(e)}function va(e){let s=[];if(e.service)s.push("background service");if(e.pid!==void 0)s.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${hr(e.agentId)} — ${s.join(", ")}`}function hr(e){return e===UA?"(host, no agents)":e}function ka(e){let s=G(e);if(s.id===void 0||s.id==="")throw new t({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 s.id}async function Rr(e){let s=await fe.open({path:e.store??F()});try{if(e.prune===!0)return await xa(e,s);if(e.all===!0)return await Pa(e,s);if(e.ref===void 0)throw new t({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 Ra(e.ref,e,s)}finally{await s.close()}}async function Ra(e,s,r){let i=await Tr(e,s,r),n=Ys(i);if(n.length>0){let c=n[0];throw new t({code:c.code,message:c.message,hint:c.hint})}let a=Qs(i),l=`${k(`removing ${e} will:`,!0)}
156
- ${tr(i)}
155
+ `)}return n.every((a)=>a.stopped)?o:u}async function fa(e,s){let r=`${t.slug}.agent.`,i=new Map;for(let n of e?.labels(r)??[]){let a=n.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let n=await fe.open({path:s??F()});for(let a of await n.leases.all()){if(a.pid===process.pid||!z(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await n.close()}catch{}return[...i.values()].sort((n,a)=>n.agentId.localeCompare(a.agentId))}async function pa(e,s){let r=[];if(e.service&&s!==void 0)try{s.stop($o(t.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(!z(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await Ze(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let n=await Ze(e.pid,"SIGKILL",!0);return r.push(n?`pid ${e.pid} did not stop in ${Math.round(Xs/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:n,forced:!0,note:r.join(" · ")}}async function Ze(e,s,r=!1){try{process.kill(r?-e:e,s)}catch(n){if(n.code==="ESRCH")return!0;if(r)try{process.kill(e,s)}catch{return!z(e)}}let i=Date.now()+(s==="SIGKILL"?3000:Xs);while(Date.now()<i){if(!z(e))return!0;await new Promise((n)=>setTimeout(n,ca))}return!z(e)}function ha(e){let s=[];if(e.service)s.push("background service");if(e.pid!==void 0)s.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${zs(e.agentId)} — ${s.join(", ")}`}function zs(e){return e===Ut?"(host, no agents)":e}function ga(e){let s=G(e);if(s.id===void 0||s.id==="")throw new A({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 \`${t.slug} stop\` with no argument to stop everything.`});return s.id}async function pr(e){let s=await fe.open({path:e.store??F()});try{if(e.prune===!0)return await va(e,s);if(e.all===!0)return await $a(e,s);if(e.ref===void 0)throw new A({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${t.slug} remove <name>\` takes a sandbox agent's name — the ones \`${t.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await ba(e.ref,e,s)}finally{await s.close()}}async function ba(e,s,r){let i=await br(e,s,r),n=Ws(i);if(n.length>0){let c=n[0];throw new A({code:c.code,message:c.message,hint:c.hint})}let a=Gs(i),l=`${k(`removing ${e} will:`,!0)}
156
+ ${qs(i)}
157
157
 
158
158
  ${a.map((c)=>Q(c.detail)).join(`
159
159
  `)}
@@ -162,16 +162,16 @@ ${a.map((c)=>Q(c.detail)).join(`
162
162
  Nothing was deleted — this was --dry-run.
163
163
  `),o;if(process.stdout.write(l),!await Qn(s,e,"type the agent's name to confirm:"))return process.stdout.write(`
164
164
  Nothing was deleted.
165
- `),o;return await Pr(i,s,r)}async function Pr(e,s,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await en({manifestPath:e.manifestPath,...s.exec===void 0?{}:{exec:s.exec},...s.platform===void 0?{}:{platform:s.platform}})!==o)return process.stderr.write(`
165
+ `),o;return await hr(i,s,r)}async function hr(e,s,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await en({manifestPath:e.manifestPath,...s.exec===void 0?{}:{exec:s.exec},...s.platform===void 0?{}:{platform:s.platform}})!==o)return process.stderr.write(`
166
166
  Stopping ${e.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
167
- hint: check what is still running with \`${A.slug} stop --dry-run\`, then run remove again.
168
- `),d;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let n=Or(s);try{n?.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 n=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${n.sessions} conversation(s), ${n.messages} message(s), ${n.passages} passage(s)`});for(let a of e.logs)zn(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(zn(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),s.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
167
+ hint: check what is still running with \`${t.slug} stop --dry-run\`, then run remove again.
168
+ `),u;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let n=vr(s);try{n?.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 n=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${n.sessions} conversation(s), ${n.messages} message(s), ${n.passages} passage(s)`});for(let a of e.logs)zn(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(zn(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),s.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
169
169
  `),o;if(process.stdout.write(`
170
170
  ${e.ref} removed.
171
- ${u(i)}
171
+ ${d(i)}
172
172
  `),e.filesOnly)process.stdout.write(`
173
173
  Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
174
- `);return o}async function Pa(e,s){let r=Ae();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
174
+ `);return o}async function $a(e,s){let r=te();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
175
175
  `),o;if(process.stdout.write(`${k(`removing every agent in ${ie()}:`,!0)}
176
176
  ${r.map((n)=>Q(`${n.ref}${n.id===void 0||n.id===n.ref?"":` (id ${n.id})`}`)).join(`
177
177
  `)}
@@ -179,10 +179,10 @@ ${r.map((n)=>Q(`${n.ref}${n.id===void 0||n.id===n.ref?"":` (id ${n.id})`}`)).joi
179
179
  Nothing was deleted — this was --dry-run.
180
180
  `),o;if(!await Qn(e,"all",`type \`all\` to remove all ${r.length}:`))return process.stdout.write(`
181
181
  Nothing was deleted.
182
- `),o;let i=o;for(let n of r){let a=await Tr(n.ref,e,s),l=await Pr({...a,sharesIdWith:[]},e,s);if(l!==o)i=l}return i}async function xa(e,s){let r=new Set(Ae().map((l)=>l.id??l.ref).filter((l)=>l!=="")),i=new Set((await s.agentIds()).filter((l)=>!r.has(l)));for(let l of Ia())if(!r.has(l))i.add(l);let n=[];for(let l of[...i].sort())n.push({agentId:l,footprint:await s.agentFootprint(l),logs:_r(l)});if(n.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
182
+ `),o;let i=o;for(let n of r){let a=await br(n.ref,e,s),l=await hr({...a,sharesIdWith:[]},e,s);if(l!==o)i=l}return i}async function va(e,s){let r=new Set(te().map((l)=>l.id??l.ref).filter((l)=>l!=="")),i=new Set((await s.agentIds()).filter((l)=>!r.has(l)));for(let l of Sa())if(!r.has(l))i.add(l);let n=[];for(let l of[...i].sort())n.push({agentId:l,footprint:await s.agentFootprint(l),logs:kr(l)});if(n.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
183
183
  `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${ie()}.
184
184
  `),o;if(process.stdout.write(`${k("no sandbox directory claims these:",!0)}
185
- ${fr(n)}
185
+ ${Bs(n)}
186
186
  `),e.dryRun===!0)return process.stdout.write(`
187
187
  Nothing was deleted — this was --dry-run.
188
188
  `),o;if(!await Qn(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
@@ -190,27 +190,27 @@ Nothing was deleted.
190
190
  `),o;let a=[];for(let l of n){let c=await s.purgeAgent(l.agentId);for(let p of l.logs)zn(p.path,{force:!0});a.push({label:l.agentId,value:`${c.sessions} conversation(s), ${c.passages} passage(s), ${l.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:n.map((l)=>l.agentId)},null,2)}
191
191
  `:`
192
192
  pruned ${n.length} agent id(s).
193
- ${u(a)}
194
- `),o}async function Tr(e,s,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new t({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${ie()} 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=Ae(),n=i.find((g)=>g.ref===e);if(n===void 0){let g=i.map((b)=>b.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${g.length===0?", which is empty":""}.`,hint:g.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${g.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=n.id;if(a===void 0)try{a=G(n.manifestPath).id}catch{}let l=s.filesOnly===!0||a===void 0,c=a??e,p=await r.agentFootprint(c),w=p.lease?await r.leases.get(c):void 0,m=Or(s),h=$o(A.slug,c);return{ref:e,agentId:c,manifestPath:n.manifestPath,dir:n.dir,files:Ta(n.dir),footprint:p,logs:_r(c),sharesIdWith:i.filter((g)=>g.ref!==e&&(g.id??"")===c).map((g)=>g.ref),...w!==void 0&&z(w.pid)?{running:{pid:w.pid,mode:w.mode}}:{},...m?.state(h).installed===!0?{service:h}:{},filesOnly:l}}function Or(e){let s=e.platform??process.platform;if(s!=="darwin")return;return nn(s,{home:Ea(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Ta(e){let s=0,r=0,i=(n)=>{let a;try{a=br(n)}catch{return}for(let l of a){let c=kr(n,l);try{let p=vr(c);if(p.isDirectory()){i(c);continue}s+=1,r+=p.size}catch{}}};return i(e),{count:s,bytes:r}}function _r(e){let s=un(e),r=[];for(let i of[s.out,s.err])try{if(!Sa(i))continue;r.push({path:i,bytes:vr(i).size})}catch{}return r}function Ia(){let e;try{e=br(kr(we(),"logs"))}catch{return[]}let s=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))s.add(r.slice(0,-i.length));return[...s]}async function Qn(e,s,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,s)}async function Cr(e){if(e.manifestPath===void 0)return await FA({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let s=me(e.manifestPath),r=await Kn(e.manifestPath,e.store),i,n,a=o;switch(r.kind){case"reloaded":i="reloaded",n=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",n=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",n=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=d;break;case"failed":i="not reloaded",n=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=d;break;case"no-host":{let l=await Je(e.store);if(l===void 0)throw new t({code:"cli_restart_nothing_running",message:`Nothing is hosting ${s}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${s}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${s}\` reloads it in place.`});let c=await Dt(l,e.manifestPath,e.store);if(c.ok)i="started",n=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",n=`pid ${l.pid} did not adopt it${c.detail===void 0?"":`: ${c.detail}`}`,a=d;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:s,result:r,ok:a===o},null,2)}
195
- `);else process.stdout.write(`${u([{label:s,value:i,note:n}])}
196
- `);return a}import{randomBytes as rt}from"node:crypto";import{existsSync as La}from"node:fs";import{createInterface as qr}from"node:readline";class ge extends Error{code;hint;field;status;request;constructor(e,s={}){super(e.hint===void 0?e.message:`${e.message}
197
- hint: ${e.hint}`);if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.status=s.status,this.request=s.method===void 0||s.path===void 0?void 0:{method:s.method,path:s.path},s.cause!==void 0)this.cause=s.cause}}function Aa(e,s){let r=e instanceof Error?e.message:String(e);return new ge({code:"transport_failed",message:`${s.method} ${s.path} did not reach ${s.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."},{...s,cause:e})}async function Oa(e,s){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 ge(r??{code:`http_${e.status}`,message:`${s.method} ${s.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,...s})}var jr=new Set(JA);async function*Fr(e){for await(let s of dr(_a(e))){if(s.event===void 0||s.data==="")continue;let r;try{r=JSON.parse(s.data)}catch{continue}yield{name:s.event,data:r}}}async function*_a(e){let s=e.getReader();try{while(!0){let{done:r,value:i}=await s.read();if(r)return;if(i!==void 0)yield i}}finally{s.releaseLock()}}async function*Ca(e){for await(let{name:s,data:r}of Fr(e)){if(jr.has(s)){yield{kind:"event",event:r};continue}let i=r??{};switch(s){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*Na(e){for await(let{name:s,data:r}of Fr(e)){if(jr.has(s)){yield{kind:"event",event:r};continue}if(s==="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*ja(e,s={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&s.allowTruncated!==!0)throw new ge({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 ge({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 Lr(e){let s=e.baseUrl.length;while(s>0&&e.baseUrl[s-1]==="/")s-=1;let r=e.baseUrl.slice(0,s),i=e.fetch??fetch,n=(m={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...m});async function a(m,h,g={}){let b;try{b=await i(`${r}${h}`,{method:m,headers:n({...g.body===void 0?{}:{"content-type":"application/json"},...g.accept===void 0?{}:{accept:g.accept},...g.headers}),...g.body===void 0?{}:{body:JSON.stringify(g.body)},...g.signal===void 0?{}:{signal:g.signal}})}catch(P){throw Aa(P,{method:m,path:h,baseUrl:r})}if(!b.ok)throw await Oa(b,{method:m,path:h});return b}async function l(m,h,g){return await(await a(m,h,g??{})).json()}async function c(m,h){let g=await a("GET",m,{accept:"text/event-stream",...h===void 0?{}:{signal:h}});if(g.body===null)throw new ge({code:"no_response_body",message:`GET ${m} returned ${g.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:g.status,method:"GET",path:m});return g.body}function p(m,h,g,b={}){let P=(S)=>{let L=new URLSearchParams;if(S?.chunks===!0)L.set("chunks","true");if(S?.children===!0)L.set("children","true");let D=L.toString();return D===""?"":`?${D}`},R={turnId:h,sessionKey:g,replayed:b.replayed===!0,async*stream(S){let L=await c(`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}/stream${P(S)}`,S?.signal);yield*Ca(L)},async*tokens(S){yield*ja(R.stream({chunks:!0,...S,children:!1}),{...S?.allowTruncated===void 0?{}:{allowTruncated:S.allowTruncated}})},async text(){for await(let S of R.stream()){if(S.kind==="ended")break;if(S.kind==="unavailable")break;if(S.kind==="event"&&S.event.type==="turn.end")break}return(await R.get()).text},get:()=>l("GET",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}/stop`)}};return R}function w(m){let h=(g)=>`/v1/agents/${encodeURIComponent(m)}${g}`;return{id:m,async send(g,b){let P=await l("POST",h("/messages"),{body:{text:g,...b?.sessionKey===void 0?{}:{sessionKey:b.sessionKey},...b?.deliver===void 0?{}:{deliver:b.deliver},...b?.from===void 0?{}:{from:b.from},...b?.images===void 0?{}:{images:b.images},...b?.runtimeNote===void 0?{}:{runtimeNote:b.runtimeNote},...b?.chunks===!0?{chunks:!0}:{},...b?.role===void 0?{}:{role:b.role}},...b?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":b.idempotencyKey}},...b?.signal===void 0?{}:{signal:b.signal}});return p(m,P.turnId,P.sessionKey,{replayed:P.replayed===!0})},turn:(g)=>p(m,g,""),describe:()=>l("GET",h("")),tools:()=>l("GET",h("/tools")),skills:()=>l("GET",h("/skills")),sessions:()=>l("GET",h("/sessions")),messages:(g,b)=>{let P=new URLSearchParams;if(b?.before!==void 0)P.set("before",String(b.before));if(b?.limit!==void 0)P.set("limit",String(b.limit));let R=P.size===0?"":`?${P.toString()}`;return l("GET",h(`/sessions/${encodeURIComponent(g)}/messages${R}`))},clearSession:(g)=>l("DELETE",h(`/sessions/${encodeURIComponent(g)}`)),reload:()=>l("POST",h("/reload"),{body:{}}),usage:(g)=>l("GET",h(`/usage${Nr(g)}`)),turns:(g)=>{let b=new URLSearchParams;if(g?.limit!==void 0)b.set("limit",String(g.limit));if(g?.before!==void 0)b.set("before",String(g.before));let P=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/turns${P}`))},secrets:async()=>(await l("GET",h("/secrets"))).secrets,setSecrets:(g)=>l("PUT",h("/secrets"),{body:{values:g}}),schedules:async()=>(await l("GET",h("/schedules"))).schedules,approvals:async()=>(await l("GET",h("/approvals"))).approvals,createSchedule:(g)=>l("POST",h("/schedules"),{body:g}),updateSchedule:(g,b)=>l("PATCH",h(`/schedules/${encodeURIComponent(g)}`),{body:b}),deleteSchedule:async(g)=>{await l("DELETE",h(`/schedules/${encodeURIComponent(g)}`))},runSchedule:(g)=>l("POST",h(`/schedules/${encodeURIComponent(g)}/run`),{body:{}}),config:()=>l("GET",h("/config")),setConfig:(g,b,P)=>l("PATCH",h("/config"),{body:{path:g,value:b,...P?.confirm===void 0?{}:{confirm:P.confirm}}}),removeConfig:(g,b)=>l("PATCH",h("/config"),{body:{path:g,remove:!0,...b?.confirm===void 0?{}:{confirm:b.confirm}}}),setConfigs:(g)=>l("PATCH",h("/config"),{body:{changes:g.map((b)=>({...b}))}}),setChannel:(g,b)=>l("PATCH",h(`/channels/${encodeURIComponent(g)}`),{body:{...b}}),unpairChannel:(g)=>l("POST",h(`/channels/${encodeURIComponent(g)}/unpair`)),session:(g)=>l("GET",h(`/sessions/${encodeURIComponent(g)}`)),setPhase:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/phase`),{body:{phase:b}}),setRecall:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/recall`),{body:{recall:b}}),approve:async(g,b)=>{await l("POST",h(`/approvals/${encodeURIComponent(g)}`),{body:{granted:b}})},stop:(g)=>l("POST",h("/stop"),{body:g===void 0?{}:{reason:g}}),start:()=>l("POST",h("/start"),{body:{}}),assign:(g)=>l("PUT",h("/assignee"),{body:{participantId:g}}),unassign:()=>l("DELETE",h("/assignee")),exportBundle:(g)=>l("GET",h(`/export${g===void 0?"":`?paths=${encodeURIComponent(g.join(","))}`}`)),importBundle:(g,b)=>l("POST",h("/import"),{body:{bundle:g,...b===void 0?{}:{mode:b}}}),context:(g)=>{let b=new URLSearchParams;if(g?.sessionKey!==void 0)b.set("sessionKey",g.sessionKey);if(g?.input!==void 0)b.set("input",g.input);let P=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/context${P}`))}}}return{agent:w,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(m){if(m instanceof ge&&m.status===503)return!1;throw m}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(m)=>l("POST","/v1/keys",{body:m}),revokeKey:(m)=>l("DELETE",`/v1/keys/${encodeURIComponent(m)}`),createAgent:(m)=>l("POST","/v1/agents",{body:{answers:m}}),usage:(m)=>l("GET",`/v1/usage${Nr(m)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(m)=>l("POST","/v1/participants",{body:m}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(m)=>l("POST","/v1/conversations",{body:m}),conversation:(m)=>l("GET",`/v1/conversations/${encodeURIComponent(m)}`),setMembers:(m,h)=>l("PATCH",`/v1/conversations/${encodeURIComponent(m)}/members`,{body:h}),postMessage:(m,h)=>l("POST",`/v1/conversations/${encodeURIComponent(m)}/messages`,{body:h}),conversationMessages:(m,h={})=>{let g=new URLSearchParams;if(h.after!==void 0)g.set("after",String(h.after));if(h.limit!==void 0)g.set("limit",String(h.limit));let b=g.size===0?"":`?${g}`;return l("GET",`/v1/conversations/${encodeURIComponent(m)}/messages${b}`)},setPresence:(m,h)=>l("PUT",`/v1/participants/${encodeURIComponent(m)}/presence`,{body:{presence:h}}),actions:async(m={})=>(await l("GET",`/v1/actions${m.status===void 0?"":`?status=${m.status}`}`)).actions,decideAction:(m,h)=>l("POST",`/v1/actions/${encodeURIComponent(m)}`,{body:{approve:h}}),addNote:(m)=>l("POST","/v1/memory/notes",{body:m}),notes:async(m)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(m)}`)).notes,deleteNote:(m)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(m)}`),memoryReads:async(m)=>(await l("GET",`/v1/participants/${encodeURIComponent(m)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(m,h)=>l("PUT",`/v1/projects/${encodeURIComponent(m)}`,{body:h}),deleteProject:(m)=>l("DELETE",`/v1/projects/${encodeURIComponent(m)}`),setSpaceWriter:(m)=>l("PUT","/v1/memory/space/writer",{body:{writer:m}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(m)=>l("POST","/v1/webhooks",{body:m}),deleteWebhook:(m)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(m)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(m)=>l("POST","/v1/agents",{body:m}),async*events(m){let h=new URLSearchParams;if(m?.agentId!==void 0)h.set("agentId",m.agentId);if(m?.types!==void 0&&m.types.length>0)h.set("types",m.types.join(","));if(m?.chunks===!0)h.set("chunks","true");let g=h.size===0?"":`?${h.toString()}`,b=await c(`/v1/events${g}`,m?.signal);yield*Na(b)}}}function Nr(e){let s=new URLSearchParams;if(e?.by!==void 0)s.set("by",e.by.join(","));if(e?.from!==void 0)s.set("from",e.from);if(e?.to!==void 0)s.set("to",e.to);return s.size===0?"":`?${s.toString()}`}function Ne(e,s){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 n=Ii(i,s);if(n==="")continue;r.push({role:i.role,text:n})}return r}function Ur(e){let s=e.ref??"<your agent>",r=`${A.slug} run ${s} --session ${e.sessionKey}`;return`
193
+ ${d(a)}
194
+ `),o}async function br(e,s,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new A({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${ie()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${t.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=te(),n=i.find((g)=>g.ref===e);if(n===void 0){let g=i.map((b)=>b.ref);throw new A({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${g.length===0?", which is empty":""}.`,hint:g.length===0?`Nothing to remove. \`${t.slug} init\` creates one.`:`Known agents: ${g.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=n.id;if(a===void 0)try{a=G(n.manifestPath).id}catch{}let l=s.filesOnly===!0||a===void 0,c=a??e,p=await r.agentFootprint(c),w=p.lease?await r.leases.get(c):void 0,m=vr(s),h=$o(t.slug,c);return{ref:e,agentId:c,manifestPath:n.manifestPath,dir:n.dir,files:ka(n.dir),footprint:p,logs:kr(c),sharesIdWith:i.filter((g)=>g.ref!==e&&(g.id??"")===c).map((g)=>g.ref),...w!==void 0&&z(w.pid)?{running:{pid:w.pid,mode:w.mode}}:{},...m?.state(h).installed===!0?{service:h}:{},filesOnly:l}}function vr(e){let s=e.platform??process.platform;if(s!=="darwin")return;return nn(s,{home:wa(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function ka(e){let s=0,r=0,i=(n)=>{let a;try{a=Ys(n)}catch{return}for(let l of a){let c=fr(n,l);try{let p=Qs(c);if(p.isDirectory()){i(c);continue}s+=1,r+=p.size}catch{}}};return i(e),{count:s,bytes:r}}function kr(e){let s=dn(e),r=[];for(let i of[s.out,s.err])try{if(!ya(i))continue;r.push({path:i,bytes:Qs(i).size})}catch{}return r}function Sa(){let e;try{e=Ys(fr(we(),"logs"))}catch{return[]}let s=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))s.add(r.slice(0,-i.length));return[...s]}async function Qn(e,s,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,s)}async function Rr(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 s=me(e.manifestPath),r=await Kn(e.manifestPath,e.store),i,n,a=o;switch(r.kind){case"reloaded":i="reloaded",n=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",n=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",n=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=u;break;case"failed":i="not reloaded",n=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=u;break;case"no-host":{let l=await Je(e.store);if(l===void 0)throw new A({code:"cli_restart_nothing_running",message:`Nothing is hosting ${s}, and no server is running to adopt it.`,hint:`\`${t.slug} serve ${s}\` runs it in this terminal; \`${t.slug} daemon install\` keeps a server running that hosts every agent. Then \`${t.slug} restart ${s}\` reloads it in place.`});let c=await DA(l,e.manifestPath,e.store);if(c.ok)i="started",n=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",n=`pid ${l.pid} did not adopt it${c.detail===void 0?"":`: ${c.detail}`}`,a=u;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:s,result:r,ok:a===o},null,2)}
195
+ `);else process.stdout.write(`${d([{label:s,value:i,note:n}])}
196
+ `);return a}import{randomBytes as et}from"node:crypto";import{existsSync as Oa}from"node:fs";import{createInterface as Fr}from"node:readline";class ge extends Error{code;hint;field;status;request;constructor(e,s={}){super(e.hint===void 0?e.message:`${e.message}
197
+ hint: ${e.hint}`);if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.status=s.status,this.request=s.method===void 0||s.path===void 0?void 0:{method:s.method,path:s.path},s.cause!==void 0)this.cause=s.cause}}function Ea(e,s){let r=e instanceof Error?e.message:String(e);return new ge({code:"transport_failed",message:`${s.method} ${s.path} did not reach ${s.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."},{...s,cause:e})}async function Ra(e,s){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 ge(r??{code:`http_${e.status}`,message:`${s.method} ${s.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,...s})}var Tr=new Set(Jt);async function*Ar(e){for await(let s of ur(Pa(e))){if(s.event===void 0||s.data==="")continue;let r;try{r=JSON.parse(s.data)}catch{continue}yield{name:s.event,data:r}}}async function*Pa(e){let s=e.getReader();try{while(!0){let{done:r,value:i}=await s.read();if(r)return;if(i!==void 0)yield i}}finally{s.releaseLock()}}async function*xa(e){for await(let{name:s,data:r}of Ar(e)){if(Tr.has(s)){yield{kind:"event",event:r};continue}let i=r??{};switch(s){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*Ta(e){for await(let{name:s,data:r}of Ar(e)){if(Tr.has(s)){yield{kind:"event",event:r};continue}if(s==="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*Ia(e,s={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&s.allowTruncated!==!0)throw new ge({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 ge({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 Or(e){let s=e.baseUrl.length;while(s>0&&e.baseUrl[s-1]==="/")s-=1;let r=e.baseUrl.slice(0,s),i=e.fetch??fetch,n=(m={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...m});async function a(m,h,g={}){let b;try{b=await i(`${r}${h}`,{method:m,headers:n({...g.body===void 0?{}:{"content-type":"application/json"},...g.accept===void 0?{}:{accept:g.accept},...g.headers}),...g.body===void 0?{}:{body:JSON.stringify(g.body)},...g.signal===void 0?{}:{signal:g.signal}})}catch(P){throw Ea(P,{method:m,path:h,baseUrl:r})}if(!b.ok)throw await Ra(b,{method:m,path:h});return b}async function l(m,h,g){return await(await a(m,h,g??{})).json()}async function c(m,h){let g=await a("GET",m,{accept:"text/event-stream",...h===void 0?{}:{signal:h}});if(g.body===null)throw new ge({code:"no_response_body",message:`GET ${m} returned ${g.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:g.status,method:"GET",path:m});return g.body}function p(m,h,g,b={}){let P=(S)=>{let L=new URLSearchParams;if(S?.chunks===!0)L.set("chunks","true");if(S?.children===!0)L.set("children","true");let D=L.toString();return D===""?"":`?${D}`},R={turnId:h,sessionKey:g,replayed:b.replayed===!0,async*stream(S){let L=await c(`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}/stream${P(S)}`,S?.signal);yield*xa(L)},async*tokens(S){yield*Ia(R.stream({chunks:!0,...S,children:!1}),{...S?.allowTruncated===void 0?{}:{allowTruncated:S.allowTruncated}})},async text(){for await(let S of R.stream()){if(S.kind==="ended")break;if(S.kind==="unavailable")break;if(S.kind==="event"&&S.event.type==="turn.end")break}return(await R.get()).text},get:()=>l("GET",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(h)}/stop`)}};return R}function w(m){let h=(g)=>`/v1/agents/${encodeURIComponent(m)}${g}`;return{id:m,async send(g,b){let P=await l("POST",h("/messages"),{body:{text:g,...b?.sessionKey===void 0?{}:{sessionKey:b.sessionKey},...b?.deliver===void 0?{}:{deliver:b.deliver},...b?.from===void 0?{}:{from:b.from},...b?.images===void 0?{}:{images:b.images},...b?.runtimeNote===void 0?{}:{runtimeNote:b.runtimeNote},...b?.chunks===!0?{chunks:!0}:{},...b?.role===void 0?{}:{role:b.role}},...b?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":b.idempotencyKey}},...b?.signal===void 0?{}:{signal:b.signal}});return p(m,P.turnId,P.sessionKey,{replayed:P.replayed===!0})},turn:(g)=>p(m,g,""),describe:()=>l("GET",h("")),tools:()=>l("GET",h("/tools")),skills:()=>l("GET",h("/skills")),sessions:()=>l("GET",h("/sessions")),messages:(g,b)=>{let P=new URLSearchParams;if(b?.before!==void 0)P.set("before",String(b.before));if(b?.limit!==void 0)P.set("limit",String(b.limit));let R=P.size===0?"":`?${P.toString()}`;return l("GET",h(`/sessions/${encodeURIComponent(g)}/messages${R}`))},clearSession:(g)=>l("DELETE",h(`/sessions/${encodeURIComponent(g)}`)),reload:()=>l("POST",h("/reload"),{body:{}}),usage:(g)=>l("GET",h(`/usage${Pr(g)}`)),turns:(g)=>{let b=new URLSearchParams;if(g?.limit!==void 0)b.set("limit",String(g.limit));if(g?.before!==void 0)b.set("before",String(g.before));let P=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/turns${P}`))},secrets:async()=>(await l("GET",h("/secrets"))).secrets,setSecrets:(g)=>l("PUT",h("/secrets"),{body:{values:g}}),schedules:async()=>(await l("GET",h("/schedules"))).schedules,approvals:async()=>(await l("GET",h("/approvals"))).approvals,createSchedule:(g)=>l("POST",h("/schedules"),{body:g}),updateSchedule:(g,b)=>l("PATCH",h(`/schedules/${encodeURIComponent(g)}`),{body:b}),deleteSchedule:async(g)=>{await l("DELETE",h(`/schedules/${encodeURIComponent(g)}`))},runSchedule:(g)=>l("POST",h(`/schedules/${encodeURIComponent(g)}/run`),{body:{}}),config:()=>l("GET",h("/config")),setConfig:(g,b,P)=>l("PATCH",h("/config"),{body:{path:g,value:b,...P?.confirm===void 0?{}:{confirm:P.confirm}}}),removeConfig:(g,b)=>l("PATCH",h("/config"),{body:{path:g,remove:!0,...b?.confirm===void 0?{}:{confirm:b.confirm}}}),setConfigs:(g)=>l("PATCH",h("/config"),{body:{changes:g.map((b)=>({...b}))}}),setChannel:(g,b)=>l("PATCH",h(`/channels/${encodeURIComponent(g)}`),{body:{...b}}),unpairChannel:(g)=>l("POST",h(`/channels/${encodeURIComponent(g)}/unpair`)),session:(g)=>l("GET",h(`/sessions/${encodeURIComponent(g)}`)),setPhase:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/phase`),{body:{phase:b}}),setRecall:(g,b)=>l("POST",h(`/sessions/${encodeURIComponent(g)}/recall`),{body:{recall:b}}),approve:async(g,b)=>{await l("POST",h(`/approvals/${encodeURIComponent(g)}`),{body:{granted:b}})},stop:(g)=>l("POST",h("/stop"),{body:g===void 0?{}:{reason:g}}),start:()=>l("POST",h("/start"),{body:{}}),assign:(g)=>l("PUT",h("/assignee"),{body:{participantId:g}}),unassign:()=>l("DELETE",h("/assignee")),exportBundle:(g)=>l("GET",h(`/export${g===void 0?"":`?paths=${encodeURIComponent(g.join(","))}`}`)),importBundle:(g,b)=>l("POST",h("/import"),{body:{bundle:g,...b===void 0?{}:{mode:b}}}),context:(g)=>{let b=new URLSearchParams;if(g?.sessionKey!==void 0)b.set("sessionKey",g.sessionKey);if(g?.input!==void 0)b.set("input",g.input);let P=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/context${P}`))}}}return{agent:w,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(m){if(m instanceof ge&&m.status===503)return!1;throw m}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(m)=>l("POST","/v1/keys",{body:m}),revokeKey:(m)=>l("DELETE",`/v1/keys/${encodeURIComponent(m)}`),createAgent:(m)=>l("POST","/v1/agents",{body:{answers:m}}),usage:(m)=>l("GET",`/v1/usage${Pr(m)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(m)=>l("POST","/v1/participants",{body:m}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(m)=>l("POST","/v1/conversations",{body:m}),conversation:(m)=>l("GET",`/v1/conversations/${encodeURIComponent(m)}`),setMembers:(m,h)=>l("PATCH",`/v1/conversations/${encodeURIComponent(m)}/members`,{body:h}),postMessage:(m,h)=>l("POST",`/v1/conversations/${encodeURIComponent(m)}/messages`,{body:h}),conversationMessages:(m,h={})=>{let g=new URLSearchParams;if(h.after!==void 0)g.set("after",String(h.after));if(h.limit!==void 0)g.set("limit",String(h.limit));let b=g.size===0?"":`?${g}`;return l("GET",`/v1/conversations/${encodeURIComponent(m)}/messages${b}`)},setPresence:(m,h)=>l("PUT",`/v1/participants/${encodeURIComponent(m)}/presence`,{body:{presence:h}}),actions:async(m={})=>(await l("GET",`/v1/actions${m.status===void 0?"":`?status=${m.status}`}`)).actions,decideAction:(m,h)=>l("POST",`/v1/actions/${encodeURIComponent(m)}`,{body:{approve:h}}),addNote:(m)=>l("POST","/v1/memory/notes",{body:m}),notes:async(m)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(m)}`)).notes,deleteNote:(m)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(m)}`),memoryReads:async(m)=>(await l("GET",`/v1/participants/${encodeURIComponent(m)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(m,h)=>l("PUT",`/v1/projects/${encodeURIComponent(m)}`,{body:h}),deleteProject:(m)=>l("DELETE",`/v1/projects/${encodeURIComponent(m)}`),setSpaceWriter:(m)=>l("PUT","/v1/memory/space/writer",{body:{writer:m}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(m)=>l("POST","/v1/webhooks",{body:m}),deleteWebhook:(m)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(m)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(m)=>l("POST","/v1/agents",{body:m}),async*events(m){let h=new URLSearchParams;if(m?.agentId!==void 0)h.set("agentId",m.agentId);if(m?.types!==void 0&&m.types.length>0)h.set("types",m.types.join(","));if(m?.chunks===!0)h.set("chunks","true");let g=h.size===0?"":`?${h.toString()}`,b=await c(`/v1/events${g}`,m?.signal);yield*Ta(b)}}}function Pr(e){let s=new URLSearchParams;if(e?.by!==void 0)s.set("by",e.by.join(","));if(e?.from!==void 0)s.set("from",e.from);if(e?.to!==void 0)s.set("to",e.to);return s.size===0?"":`?${s.toString()}`}function Ce(e,s){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 n=Ii(i,s);if(n==="")continue;r.push({role:i.role,text:n})}return r}function _r(e){let s=e.ref??"<your agent>",r=`${t.slug} run ${s} --session ${e.sessionKey}`;return`
198
198
  ${ra}Resume this session with:
199
199
  ${r}${Ro}
200
- `}function Zn(e,s){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 s===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${s}, still in the store. /sessions goes back to it.`}}function Fa(e){return e==="nlt"?Er():ur()}function Mr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(s)=>e.bus.on("*",s,{chunks:!0}),send:(s,r)=>e.send(s,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,tools:async()=>Zo(e.agent),context:e.context,close:async()=>{}}}function Dr(e){let s=e.client.agent(e.agentId),r=new Set,i=new AbortController,n,a=()=>{if(n!==void 0)return;n=(async()=>{for await(let l of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(l.kind!=="event"||l.event===void 0)continue;for(let c of r)c(l.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(l)=>(r.add(l),a(),()=>r.delete(l)),send:async(l,c)=>{let p=!1,w,m=()=>{if(p=!0,w!==void 0)s.turn(w).stop().catch(()=>{})};c.signal.addEventListener("abort",m,{once:!0});let h,g=new Promise((b)=>{let P=(R)=>{if(w!==void 0&&R.turnId!==void 0&&R.turnId!==w)return;if(R.type==="error"){h=R.data;return}if(R.type!=="turn.end")return;r.delete(P),b({text:"",reason:R.data.reason,steps:R.data.steps,durationMs:R.data.durationMs,tokens:R.data.tokens,...h===void 0?{}:{error:h}})};r.add(P),a()});try{if(w=(await s.send(l,{sessionKey:c.sessionKey})).turnId,p)s.turn(w).stop().catch(()=>{});return await g}finally{c.signal.removeEventListener("abort",m)}},streamFilter:()=>Fa(e.description.dialect),history:async(l)=>{let c=await s.messages(l);return Ne([...c.messages].reverse().map((p)=>({role:p.role,content:p.content,...p.origin===void 0?{}:{origin:p.origin}})),e.description.dialect)},sessions:()=>s.sessions(),clearSession:async(l)=>{await s.clearSession(l)},tools:async()=>{let l=await s.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:l.map((c)=>({slug:c.slug,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},summary:c.summary}))}},context:async(l)=>{let c=await s.context({sessionKey:l});return{...c,windowSource:"as the host resolved it",...c.lastCompaction===void 0&&c.compactions!==void 0?{lastCompaction:c.compactions===0?void 0:`${c.compactions} stage${c.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await s.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Wr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function Ua(e,s,r,i,n,a=[],l){let c=e.describe(),[p,w]=await Promise.all([e.turns(s,1),e.store.messages.count(e.id,s)]),m=[`${A.name} ${J} · ${c.id} · ${c.model}`,`session ${s} · ${w} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],h=Zn(n,l);if(h!==void 0)m.push(h);if(p[0]?.errorCode==="turn_abandoned")m.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let g of[...e.warnings,...e.tools.warnings])m.push(`note: ${g.message}
200
+ `}function Zn(e,s){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 s===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${s}, still in the store. /sessions goes back to it.`}}function Aa(e){return e==="nlt"?Er():dr()}function Cr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(s)=>e.bus.on("*",s,{chunks:!0}),send:(s,r)=>e.send(s,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,tools:async()=>Zo(e.agent),context:e.context,close:async()=>{}}}function Nr(e){let s=e.client.agent(e.agentId),r=new Set,i=new AbortController,n,a=()=>{if(n!==void 0)return;n=(async()=>{for await(let l of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(l.kind!=="event"||l.event===void 0)continue;for(let c of r)c(l.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(l)=>(r.add(l),a(),()=>r.delete(l)),send:async(l,c)=>{let p=!1,w,m=()=>{if(p=!0,w!==void 0)s.turn(w).stop().catch(()=>{})};c.signal.addEventListener("abort",m,{once:!0});let h,g=new Promise((b)=>{let P=(R)=>{if(w!==void 0&&R.turnId!==void 0&&R.turnId!==w)return;if(R.type==="error"){h=R.data;return}if(R.type!=="turn.end")return;r.delete(P),b({text:"",reason:R.data.reason,steps:R.data.steps,durationMs:R.data.durationMs,tokens:R.data.tokens,...h===void 0?{}:{error:h}})};r.add(P),a()});try{if(w=(await s.send(l,{sessionKey:c.sessionKey})).turnId,p)s.turn(w).stop().catch(()=>{});return await g}finally{c.signal.removeEventListener("abort",m)}},streamFilter:()=>Aa(e.description.dialect),history:async(l)=>{let c=await s.messages(l);return Ce([...c.messages].reverse().map((p)=>({role:p.role,content:p.content,...p.origin===void 0?{}:{origin:p.origin}})),e.description.dialect)},sessions:()=>s.sessions(),clearSession:async(l)=>{await s.clearSession(l)},tools:async()=>{let l=await s.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:l.map((c)=>({slug:c.slug,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},summary:c.summary}))}},context:async(l)=>{let c=await s.context({sessionKey:l});return{...c,windowSource:"as the host resolved it",...c.lastCompaction===void 0&&c.compactions!==void 0?{lastCompaction:c.compactions===0?void 0:`${c.compactions} stage${c.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await s.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function jr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function _a(e,s,r,i,n,a=[],l){let c=e.describe(),[p,w]=await Promise.all([e.turns(s,1),e.store.messages.count(e.id,s)]),m=[`${t.name} ${J} · ${c.id} · ${c.model}`,`session ${s} · ${w} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],h=Zn(n,l);if(h!==void 0)m.push(h);if(p[0]?.errorCode==="turn_abandoned")m.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let g of[...e.warnings,...e.tools.warnings])m.push(`note: ${g.message}
201
201
  ${g.hint}`);if(a.length>0)m.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"}.
202
- 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 m}async function ot(e){let s=e.once!==void 0,r=oA({json:!1,plain:e.plain===!0,oneShot:s}),{mode:i}=r;if(e.manifestPath===void 0){let R=await Ma(i,r.because,e);if(typeof R==="number")return R;return ot({...e,manifestPath:R})}let n=ci();if(e.store===void 0&&e.ephemeral!==!0&&La(n))process.stdout.write(`note: a session store exists at ${n} from an earlier version — pass --store ${n} to keep using it; the default is now ${F()}
203
- `);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},p={current:e.sessionKey},w={current:!1},m={current:void 0},h=e.quiet===!0,g="first",b={current:void 0},P=e.ephemeral===!0?void 0:Wr(await je(me(e.manifestPath),e.store));if(P!==void 0)return await Ga({...e,host:P,mode:i==="rich"?"rich":"plain",quiet:h,oneShot:s,reader:l,draft:c,session:p,random:rt});for(;;){let R=await ue.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??F()});a=R;let S=R.list()[0];if(S===void 0)throw Error("The manifest produced no agent.");if(p.current===void 0||p.current===""){let W=await Br({list:async()=>zr(await S.store.sessions.list(S.id)),mode:i,asked:p.current,wantsContinue:e.continueSession===!0,random:rt});if(typeof W==="number")return await R.stop("cli-exit"),W;p.current=W.sessionKey,w.current=W.fresh}let L=p.current,D=S.roles.main.capabilities.thinking!=="none",v=e.noReasoning===!0?!1:D,x=h||s?[]:await Ua(S,L,R.store.location,g==="first"?R.boot.processMs:R.boot.bootMs,g,Fs([e.manifestPath]),m.current),I=i==="rich"&&!h&&!s?Ne(await S.history(L),S.describe().dialect):[],N=Mr({agent:S,bus:R.bus,send:(W,ae)=>S.send(W,ae),history:async(W)=>Ne(await S.history(W),S.describe().dialect),sessions:async()=>await S.store.sessions.list(S.id),clearSession:async(W)=>{await S.clearSession(W)},context:async(W)=>qa(S,W),streamFilter:()=>S.streamFilter(),description:{agentId:S.id,name:S.describe().name,model:S.describe().model,dialect:S.describe().dialect,window:S.describe().window,catalogueTokens:S.describe().catalogueTokens,thinking:S.roles.main.capabilities.thinking,warnings:[...S.warnings,...S.tools.warnings]}}),K={...e,source:N,embedded:{agent:S,runtime:R},sessionKey:L,banner:x,prior:I,quiet:h,reader:l,draft:c,showReasoning:v,freshSession:w.current,switchTo:b,random:rt},O=i==="rich"?await Vr(K):await Jr(K);if(await R.stop(O===$e?"restart":"cli-exit"),O!==$e)return O;if(b.current===void 0)g="restart";else g=b.current.reason,m.current=L,p.current=b.current.key,b.current=void 0;w.current=!1}}function Ka(e,s){let r=[];for(let i of e)KA({action:"install",manifestPath:s,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var $e=Symbol("restart");async function Ma(e,s,r){let i=Ae();if(i.length===0){if(e==="rich"){let m=await Cn({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
204
- `),o;if(m.kind==="failed")return m.code;return m.manifestPath}throw new t({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
202
+ 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 m}async function tt(e){let s=e.once!==void 0,r=ot({json:!1,plain:e.plain===!0,oneShot:s}),{mode:i}=r;if(e.manifestPath===void 0){let R=await Na(i,r.because,e);if(typeof R==="number")return R;return tt({...e,manifestPath:R})}let n=ci();if(e.store===void 0&&e.ephemeral!==!0&&Oa(n))process.stdout.write(`note: a session store exists at ${n} from an earlier version — pass --store ${n} to keep using it; the default is now ${F()}
203
+ `);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},p={current:e.sessionKey},w={current:!1},m={current:void 0},h=e.quiet===!0,g="first",b={current:void 0},P=e.ephemeral===!0?void 0:jr(await je(me(e.manifestPath),e.store));if(P!==void 0)return await Ua({...e,host:P,mode:i==="rich"?"rich":"plain",quiet:h,oneShot:s,reader:l,draft:c,session:p,random:et});for(;;){let R=await de.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??F()});a=R;let S=R.list()[0];if(S===void 0)throw Error("The manifest produced no agent.");if(p.current===void 0||p.current===""){let W=await Lr({list:async()=>Wr(await S.store.sessions.list(S.id)),mode:i,asked:p.current,wantsContinue:e.continueSession===!0,random:et});if(typeof W==="number")return await R.stop("cli-exit"),W;p.current=W.sessionKey,w.current=W.fresh}let L=p.current,D=S.roles.main.capabilities.thinking!=="none",v=e.noReasoning===!0?!1:D,x=h||s?[]:await _a(S,L,R.store.location,g==="first"?R.boot.processMs:R.boot.bootMs,g,Fs([e.manifestPath]),m.current),I=i==="rich"&&!h&&!s?Ce(await S.history(L),S.describe().dialect):[],N=Cr({agent:S,bus:R.bus,send:(W,le)=>S.send(W,le),history:async(W)=>Ce(await S.history(W),S.describe().dialect),sessions:async()=>await S.store.sessions.list(S.id),clearSession:async(W)=>{await S.clearSession(W)},context:async(W)=>Ka(S,W),streamFilter:()=>S.streamFilter(),description:{agentId:S.id,name:S.describe().name,model:S.describe().model,dialect:S.describe().dialect,window:S.describe().window,catalogueTokens:S.describe().catalogueTokens,thinking:S.roles.main.capabilities.thinking,warnings:[...S.warnings,...S.tools.warnings]}}),K={...e,source:N,embedded:{agent:S,runtime:R},sessionKey:L,banner:x,prior:I,quiet:h,reader:l,draft:c,showReasoning:v,freshSession:w.current,switchTo:b,random:et},O=i==="rich"?await Ur(K):await Mr(K);if(await R.stop(O===$e?"restart":"cli-exit"),O!==$e)return O;if(b.current===void 0)g="restart";else g=b.current.reason,m.current=L,p.current=b.current.key,b.current=void 0;w.current=!1}}function Ca(e,s){let r=[];for(let i of e)Kt({action:"install",manifestPath:s,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var $e=Symbol("restart");async function Na(e,s,r){let i=te();if(i.length===0){if(e==="rich"){let m=await _n({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
204
+ `),o;if(m.kind==="failed")return m.code;return m.manifestPath}throw new A({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${t.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
205
205
  `),i[0].manifestPath;if(e!=="rich"){for(let m of i)process.stdout.write(`${m.ref} ${m.problem??m.modelId??"?"} ${m.dir}
206
206
  `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${s})
207
- `),d}let[{render:n},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-jkmd5xnx.js")]),c={kind:"quit"};to();let p=n(a(l,{title:`${A.name} ${J}`,agents:i,onDone:(m)=>{c=m}}),{exitOnCtrlC:!1,...Pe(r.noEnhancedKeys)});U(()=>p.unmount()),await p.waitUntilExit(),p.unmount();let w=c;if(w.kind==="quit")return process.stdout.write(`nothing run
208
- `),o;if(w.kind==="create"){let m=await Cn({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
209
- `),o;if(m.kind==="failed")return m.code;return m.manifestPath}return w.manifestPath}async function Br(e){let s=()=>({sessionKey:zo(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new t({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=Da(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
207
+ `),u}let[{render:n},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-b09hr4tk.js")]),c={kind:"quit"};Ao();let p=n(a(l,{title:`${t.name} ${J}`,agents:i,onDone:(m)=>{c=m}}),{exitOnCtrlC:!1,...Pe(r.noEnhancedKeys)});U(()=>p.unmount()),await p.waitUntilExit(),p.unmount();let w=c;if(w.kind==="quit")return process.stdout.write(`nothing run
208
+ `),o;if(w.kind==="create"){let m=await _n({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
209
+ `),o;if(m.kind==="failed")return m.code;return m.manifestPath}return w.manifestPath}async function Lr(e){let s=()=>({sessionKey:zo(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new A({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=ja(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
210
210
  `),s();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
211
211
  `),s();if(e.mode!=="rich"){for(let n of[...r].sort(cn))process.stdout.write(`${n.sessionKey} ${n.messages} ${n.turns} ${n.lastActivityAt}
212
212
  `);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
213
- `),d}let i=await Ha([...r].sort(cn));return i===void 0?s():{sessionKey:i,fresh:!1}}return e.asked===void 0?s():{sessionKey:e.asked,fresh:!1}}function cn(e,s){return Date.parse(s.lastActivityAt)-Date.parse(e.lastActivityAt)}function Da(e){return[...e].sort(cn)[0]}async function Ha(e){let[{render:s},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-3712ke3k.js")]),n;to();let a=s(r(i,{sessions:e.map((l)=>({sessionKey:l.sessionKey,messages:l.messages,turns:l.turns,lastActivityAt:l.lastActivityAt,phase:l.phase})),now:Date.now(),columns:ke(process.stdout.columns,be),maxRows:yn,onDone:(l)=>{n=l,a.unmount()}}),{exitOnCtrlC:!1,...Pe()});return U(()=>a.unmount()),await a.waitUntilExit(),n}function Wa(e,s,r,i,n){let a=e.describe(),l=[`${A.name} ${J} · ${a.agentId} · ${a.model}`,`session ${s} · 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"],c=Zn(i,n);if(c!==void 0)l.push(c);for(let p of a.warnings)l.push(`warning: ${p.message}`);return l}async function Ga(e){let s=e.manifestPath??"",r=me(s),i=Nt(s),n=Lr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await n.agent(r).describe();if(a.status==="disabled")throw new t({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${r}\`, then run again.`});let l=Dr({client:n,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??[]}}),c={current:void 0},p="first",w={current:void 0},m={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let S=await Br({list:()=>Yr(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof S==="number")return S;e.session.current=S.sessionKey,m.current=S.fresh}let h=e.session.current??"",g=e.quiet||e.oneShot?[]:Wa(l,h,e.host,p,w.current),b=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(h):[],P={...e,source:l,sessionKey:h,banner:g,prior:b,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:m.current,switchTo:c,random:e.random},R=e.mode==="rich"?await Vr(P):await Jr(P);if(R!==$e)return await l.close(),R;if(c.current===void 0)p="restart";else p=c.current.reason,w.current=h,e.session.current=c.current.key,c.current=void 0;m.current=!1}}async function Vr(e){let[{render:s},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-pmqmzsb3.js")]),n=Ve();U(()=>{n.close()}),SA(),gs(),process.stdout.write(`${RA}${Zs}`);let a=!1,l=s(r(i,{source:e.source,onSwitch:(c,p)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=p},onNew:(c)=>{a=!0,e.switchTo.current={key:zo(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await Yr(e.source)].sort(cn).map((p)=>({sessionKey:p.sessionKey,messages:p.messages,turns:p.turns,lastActivityAt:p.lastActivityAt,phase:p.phase})),onRestart:(c)=>{a=!0,e.draft.current=c},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((c)=>c.message),initial:Hi(xi(e.banner.slice(1)),e.prior),correctKeys:n.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>_t({onStatus:c}),install:async(c,p)=>hn(Ka(c,p))},status:()=>e.embedded===void 0?Zr(e.source):Xr(e.embedded),contextView:()=>eo(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Pe(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),qe(),!a)process.stdout.write(Ur({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?$e:o}async function Jr(e){let{source:s,sessionKey:r,quiet:i}=e,n=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),n=x.endsWith(`
213
+ `),u}let i=await Fa([...r].sort(cn));return i===void 0?s():{sessionKey:i,fresh:!1}}return e.asked===void 0?s():{sessionKey:e.asked,fresh:!1}}function cn(e,s){return Date.parse(s.lastActivityAt)-Date.parse(e.lastActivityAt)}function ja(e){return[...e].sort(cn)[0]}async function Fa(e){let[{render:s},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-wtfxwdxg.js")]),n;Ao();let a=s(r(i,{sessions:e.map((l)=>({sessionKey:l.sessionKey,messages:l.messages,turns:l.turns,lastActivityAt:l.lastActivityAt,phase:l.phase})),now:Date.now(),columns:ke(process.stdout.columns,be),maxRows:yn,onDone:(l)=>{n=l,a.unmount()}}),{exitOnCtrlC:!1,...Pe()});return U(()=>a.unmount()),await a.waitUntilExit(),n}function La(e,s,r,i,n){let a=e.describe(),l=[`${t.name} ${J} · ${a.agentId} · ${a.model}`,`session ${s} · 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"],c=Zn(i,n);if(c!==void 0)l.push(c);for(let p of a.warnings)l.push(`warning: ${p.message}`);return l}async function Ua(e){let s=e.manifestPath??"",r=me(s),i=NA(s),n=Or({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await n.agent(r).describe();if(a.status==="disabled")throw new A({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${t.slug} start ${r}\`, then run again.`});let l=Nr({client:n,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??[]}}),c={current:void 0},p="first",w={current:void 0},m={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let S=await Lr({list:()=>qr(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof S==="number")return S;e.session.current=S.sessionKey,m.current=S.fresh}let h=e.session.current??"",g=e.quiet||e.oneShot?[]:La(l,h,e.host,p,w.current),b=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(h):[],P={...e,source:l,sessionKey:h,banner:g,prior:b,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:m.current,switchTo:c,random:e.random},R=e.mode==="rich"?await Ur(P):await Mr(P);if(R!==$e)return await l.close(),R;if(c.current===void 0)p="restart";else p=c.current.reason,w.current=h,e.session.current=c.current.key,c.current=void 0;m.current=!1}}async function Ur(e){let[{render:s},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-hjn867nc.js")]),n=Ve();U(()=>{n.close()}),St(),gs(),process.stdout.write(`${Rt}${Zs}`);let a=!1,l=s(r(i,{source:e.source,onSwitch:(c,p)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=p},onNew:(c)=>{a=!0,e.switchTo.current={key:zo(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await qr(e.source)].sort(cn).map((p)=>({sessionKey:p.sessionKey,messages:p.messages,turns:p.turns,lastActivityAt:p.lastActivityAt,phase:p.phase})),onRestart:(c)=>{a=!0,e.draft.current=c},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((c)=>c.message),initial:Hi(xi(e.banner.slice(1)),e.prior),correctKeys:n.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>_A({onStatus:c}),install:async(c,p)=>Bn(Ca(c,p))},status:()=>e.embedded===void 0?Br(e.source):Dr(e.embedded),contextView:()=>Vr(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Pe(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),qe(),!a)process.stdout.write(_r({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?$e:o}async function Mr(e){let{source:s,sessionKey:r,quiet:i}=e,n=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),n=x.endsWith(`
214
214
  `)},l=(x)=>{if(!n)a(`
215
215
  `);a(`${x}
216
216
  `)};if(e.banner.length>0)a(`${e.banner.join(`
@@ -221,45 +221,45 @@ ${r}${Ro}
221
221
  `);if(e.showReasoning===!0)a(N==="reasoning"?`· reasoning ·
222
222
  `:`· reply ·
223
223
  `);w=N}if(N==="reasoning"){a(I),p=!0;return}h(m.push(I));return}case"tool.result":{if(!c)return;let{slug:I,ok:N,latencyMs:K,truncated:O}=x.data;l(` · ${I} — ${N?"ok":"failed"} · ${K} ms${O?" · observation trimmed":""}`);return}case"agent.warning":l(` · ${x.data.message}
224
- ${x.data.hint}`);return;case"tool.repair":if(c)l(` · ${x.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":l(` · ${x.data.slug} — blocked: ${x.data.reason}`);return;case"context.dropped":l(` · context: ${x.data.messages} older message(s) did not fit the ${x.data.budget}-token budget and were left out`);return;default:return}}),b=async(x)=>{let I=Fn(x,xn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let N=s.reload;if(N===void 0)return"restart";try{let K=await N();l(`reloaded ${K.join(", ")} — this conversation continues`)}catch(K){l(`could not reload: ${K instanceof Error?K.message:String(K)}`)}return"handled"}case"new":return e.switchTo.current={key:zo(e.random),reason:"new"},"restart";case"help":return l(Un()),"handled";case"tools":return l(St(await s.tools())),"handled";case"status":return l(e.embedded===void 0?await Zr(s):await Xr(e.embedded)),"handled";case"context":return l(await eo(e,r)),"handled";case"reset":return await s.clearSession(r),l("session cleared — memory files on disk are untouched"),"handled";case"unknown":return l(An(I)),"handled";case"command":return l(`${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"}},P,R=0,S=o,L=(x=e.reader.current)=>{if(P!==void 0&&!P.signal.aborted){R=performance.now(),P.abort();return}x?.close(),a(`
224
+ ${x.data.hint}`);return;case"tool.repair":if(c)l(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":l(` · ${x.data.slug} — blocked: ${x.data.reason}`);return;case"context.dropped":l(` · context: ${x.data.messages} older message(s) did not fit the ${x.data.budget}-token budget and were left out`);return;default:return}}),b=async(x)=>{let I=Fn(x,xn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let N=s.reload;if(N===void 0)return"restart";try{let K=await N();l(`reloaded ${K.join(", ")} — this conversation continues`)}catch(K){l(`could not reload: ${K instanceof Error?K.message:String(K)}`)}return"handled"}case"new":return e.switchTo.current={key:zo(e.random),reason:"new"},"restart";case"help":return l(Un()),"handled";case"tools":return l(SA(await s.tools())),"handled";case"status":return l(e.embedded===void 0?await Br(s):await Dr(e.embedded)),"handled";case"context":return l(await Vr(e,r)),"handled";case"reset":return await s.clearSession(r),l("session cleared — memory files on disk are untouched"),"handled";case"unknown":return l(tn(I)),"handled";case"command":return l(`${I.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${t.slug} ${I.name}${I.rest===""?"":` ${I.rest}`}\``),"handled"}},P,R=0,S=o,L=(x=e.reader.current)=>{if(P!==void 0&&!P.signal.aborted){R=performance.now(),P.abort();return}x?.close(),a(`
225
225
  `)},D=async(x)=>{P=new AbortController,p=!1,w=void 0,m=s.streamFilter();let I=await s.send(x,{sessionKey:r,signal:P.signal});if(P=void 0,h(m.end()),p&&!n)a(`
226
226
  `);else if(!p&&I.text!=="")a(`${I.text}
227
- `);let N=MA(I.reason,{steps:I.steps,durationMs:I.durationMs,...R===0?{}:{cancelledAfterMs:performance.now()-R}});if(N!==void 0)a(`
227
+ `);let N=Mt(I.reason,{steps:I.steps,durationMs:I.durationMs,...R===0?{}:{cancelledAfterMs:performance.now()-R}});if(N!==void 0)a(`
228
228
  (${N})
229
229
  `);if(I.reason==="error"&&I.error!==void 0)process.stderr.write(`
230
230
  ${I.error.code}: ${I.error.message}
231
231
  hint: ${I.error.hint}
232
- `);if(po(I.reason))S=d;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
232
+ `);if(po(I.reason))S=u;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
233
233
 
234
- `);await EA()},v=()=>L();process.on("SIGINT",v);try{if(e.once!==void 0)return await D(e.once),S;if(process.stdin.isTTY!==!0){let I=e.reader.current??qr({input:process.stdin});e.reader.current=I;for await(let N of I){let K=N.trim();if(K==="")continue;let O=await b(K);if(O==="exit")break;if(O==="restart"){S=$e;break}if(O==="handled")continue;await D(K)}return S}let x=e.reader.current??qr({input:process.stdin,output:process.stdout,prompt:Lo,terminal:!1});e.reader.current=x,x.prompt();for await(let I of x){let N=I.trim();if(N===""){x.prompt();continue}let K=await b(N);if(K==="exit")break;if(K==="restart"){S=$e;break}if(K==="handled"){x.prompt();continue}await D(N),x.prompt()}if(S!==$e)x.close(),e.reader.current=void 0;return S}finally{process.off("SIGINT",v),g()}}async function Xr(e){let{agent:s,runtime:r}=e,i=s.describe(),n=s.manifest,a=n.channels.filter((m)=>m.enabled).map((m)=>`${m.id} (${m.type})`).join(", "),l=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`,c=!n.server.enabled?"off":`enabled on ${n.server.host}:${n.server.port}, NOT bound here — \`serve\` binds it`,p=NA(n),w=p.filter((m)=>m.role!=="main"&&m.role===m.configuredAs);return u([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${n.tools.dialect} · ${i.window} token window (${st(p[0]?.window)})`},...w.map((m)=>({label:m.role,value:`${m.modelId} · ${m.window.contextWindow} token window (${st(m.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await Ba(r,i.id)}])}function zr(e){return e.filter((s)=>!li(s.sessionKey))}async function Yr(e){return zr(await e.sessions())}async function Zr(e){let s=e.describe(),r=e.host,[i,n]=await Promise.all([e.tools(),e.sessions()]);return u([{label:"agent",value:`${s.agentId} (${s.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:`${s.model} · ${s.window} token window`},{label:"dialect",value:s.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${n.length} on this agent`},{label:"warnings",value:s.warnings.length===0?"none":s.warnings.map((a)=>a.message).join("; ")}])}async function qa(e,s){let r=await e.previewContext({sessionKey:s}),[i]=NA(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:st(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 eo(e,s){return Gi(await e.source.context(s))}async function Ba(e,s){if(e.owned.includes(s))return"this session is serving this agent";let r=await e.store.leases.get(s);if(r!==void 0&&z(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${A.slug} daemon status ${s}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${A.slug} daemon install ${s}\` keeps it running without a terminal`}function Z(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function Va(e,s){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-s;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let n=Math.round(r/3600000);return n<48?`in ${n}h`:`in ${Math.round(n/24)}d`}function Ja(e,s){if(e.lastFiredAt===void 0)return"never run";let r=nt(e.lastFiredAt,s);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function Xa(e,s){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(`${Z("SCHEDULE",r)} ${Z("WHEN",i)} ${Z("NEXT",7)} LAST
235
- `);for(let a of e)process.stdout.write(`${Z(a.id,r)} ${Z(`${a.kind} ${a.expr}`,i)} ${Z(Va(a,s),7)} ${Ja(a,s)}
234
+ `);await Et()},v=()=>L();process.on("SIGINT",v);try{if(e.once!==void 0)return await D(e.once),S;if(process.stdin.isTTY!==!0){let I=e.reader.current??Fr({input:process.stdin});e.reader.current=I;for await(let N of I){let K=N.trim();if(K==="")continue;let O=await b(K);if(O==="exit")break;if(O==="restart"){S=$e;break}if(O==="handled")continue;await D(K)}return S}let x=e.reader.current??Fr({input:process.stdin,output:process.stdout,prompt:Lo,terminal:!1});e.reader.current=x,x.prompt();for await(let I of x){let N=I.trim();if(N===""){x.prompt();continue}let K=await b(N);if(K==="exit")break;if(K==="restart"){S=$e;break}if(K==="handled"){x.prompt();continue}await D(N),x.prompt()}if(S!==$e)x.close(),e.reader.current=void 0;return S}finally{process.off("SIGINT",v),g()}}async function Dr(e){let{agent:s,runtime:r}=e,i=s.describe(),n=s.manifest,a=n.channels.filter((m)=>m.enabled).map((m)=>`${m.id} (${m.type})`).join(", "),l=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`,c=!n.server.enabled?"off":`enabled on ${n.server.host}:${n.server.port}, NOT bound here — \`serve\` binds it`,p=Nt(n),w=p.filter((m)=>m.role!=="main"&&m.role===m.configuredAs);return d([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${n.tools.dialect} · ${i.window} token window (${sA(p[0]?.window)})`},...w.map((m)=>({label:m.role,value:`${m.modelId} · ${m.window.contextWindow} token window (${sA(m.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await Ma(r,i.id)}])}function Wr(e){return e.filter((s)=>!li(s.sessionKey))}async function qr(e){return Wr(await e.sessions())}async function Br(e){let s=e.describe(),r=e.host,[i,n]=await Promise.all([e.tools(),e.sessions()]);return d([{label:"agent",value:`${s.agentId} (${s.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:`${s.model} · ${s.window} token window`},{label:"dialect",value:s.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${n.length} on this agent`},{label:"warnings",value:s.warnings.length===0?"none":s.warnings.map((a)=>a.message).join("; ")}])}async function Ka(e,s){let r=await e.previewContext({sessionKey:s}),[i]=Nt(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:sA(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 Vr(e,s){return Gi(await e.source.context(s))}async function Ma(e,s){if(e.owned.includes(s))return"this session is serving this agent";let r=await e.store.leases.get(s);if(r!==void 0&&z(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${t.slug} daemon status ${s}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${t.slug} daemon install ${s}\` keeps it running without a terminal`}function Z(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function Da(e,s){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-s;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let n=Math.round(r/3600000);return n<48?`in ${n}h`:`in ${Math.round(n/24)}d`}function Ha(e,s){if(e.lastFiredAt===void 0)return"never run";let r=nA(e.lastFiredAt,s);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function Wa(e,s){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(`${Z("SCHEDULE",r)} ${Z("WHEN",i)} ${Z("NEXT",7)} LAST
235
+ `);for(let a of e)process.stdout.write(`${Z(a.id,r)} ${Z(`${a.kind} ${a.expr}`,i)} ${Z(Da(a,s),7)} ${Ha(a,s)}
236
236
  `);let n=e.filter((a)=>a.lastStatus==="error");if(n.length>0)process.stdout.write(`
237
237
  ${n.length} failing — \`schedules --id ${n[0]?.id}\` for the error
238
- `)}function za(e){let s=[["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)s.push(["last error",e.lastError]);let r=Math.max(...s.map(([i])=>i.length));process.stdout.write(`${e.id}
238
+ `)}function Ga(e){let s=[["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)s.push(["last error",e.lastError]);let r=Math.max(...s.map(([i])=>i.length));process.stdout.write(`${e.id}
239
239
  `);for(let[i,n]of s)process.stdout.write(` ${Z(i,r)} ${n}
240
- `)}function Ya(e,s){let r=new Set(s),i=new Map;for(let n of e){if(!r.has(n.channel))continue;let a=`${n.channel}\x00${n.peerId}`,l=i.get(a);if(l!==void 0&&l.lastSeen>=n.lastActivityAt)continue;i.set(a,{channelId:n.channel,address:n.peerId,lastSeen:n.lastActivityAt})}return[...i.values()].sort((n,a)=>n.channelId===a.channelId?a.lastSeen.localeCompare(n.lastSeen):n.channelId.localeCompare(a.channelId))}function Qa(e,s){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
240
+ `)}function qa(e,s){let r=new Set(s),i=new Map;for(let n of e){if(!r.has(n.channel))continue;let a=`${n.channel}\x00${n.peerId}`,l=i.get(a);if(l!==void 0&&l.lastSeen>=n.lastActivityAt)continue;i.set(a,{channelId:n.channel,address:n.peerId,lastSeen:n.lastActivityAt})}return[...i.values()].sort((n,a)=>n.channelId===a.channelId?a.lastSeen.localeCompare(n.lastSeen):n.channelId.localeCompare(a.channelId))}function Ba(e,s){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
241
241
  `+` An address appears here once a first message arrives on one.
242
242
  `);return}let r=Math.max(7,...e.map((n)=>n.channelId.length)),i=Math.max(7,...e.map((n)=>n.address.length));process.stdout.write(`${Z("CHANNEL",r)} ${Z("ADDRESS",i)} LAST SEEN
243
- `);for(let n of e)process.stdout.write(`${Z(n.channelId,r)} ${Z(n.address,i)} ${nt(n.lastSeen,s)}
243
+ `);for(let n of e)process.stdout.write(`${Z(n.channelId,r)} ${Z(n.address,i)} ${nA(n.lastSeen,s)}
244
244
  `);process.stdout.write(`
245
245
  Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
246
246
  `+`never a person — a private chat is reached by the numeric id above.
247
- `)}async function no(e){let s=await ue.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_([e.manifestPath]),lease:!1});U(()=>s.stop("cli-exit"));let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,l]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let c=await r.store.schedules.get(r.id,a);if(c===void 0)return process.stderr.write(`no schedule "${a}" on ${r.id}
247
+ `)}async function Jr(e){let s=await de.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_([e.manifestPath]),lease:!1});U(()=>s.stop("cli-exit"));let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,l]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let c=await r.store.schedules.get(r.id,a);if(c===void 0)return process.stderr.write(`no schedule "${a}" on ${r.id}
248
248
  hint: run \`schedules\` with no flags to see what this agent has.
249
- `),d;if(c.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
249
+ `),u;if(c.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
250
250
  `+` Writing it here would last until the next start — reconciliation restores every
251
251
  `+` field from the file, enabled included.
252
252
 
253
253
  hint: set \`enabled: ${l}\` on the "${a}" entry under schedules: in
254
254
  ${e.manifestPath}
255
- `),d;await r.store.schedules.setEnabled(r.id,a,l,new Date(i).toISOString()),process.stdout.write(l?`${a} enabled — it fires at its next occurrence, not now
255
+ `),u;await r.store.schedules.setEnabled(r.id,a,l,new Date(i).toISOString()),process.stdout.write(l?`${a} enabled — it fires at its next occurrence, not now
256
256
  `:`${a} disabled — still listed, and it keeps its place in the sequence
257
- `)}if(e.recipients===!0){let a=Ya(await r.store.sessions.list(r.id),r.manifest.channels.map((l)=>l.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
258
- `),o;return Qa(a,i),o}let n=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:n},null,2)}
257
+ `)}if(e.recipients===!0){let a=qa(await r.store.sessions.list(r.id),r.manifest.channels.map((l)=>l.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
258
+ `),o;return Ba(a,i),o}let n=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:n},null,2)}
259
259
  `),o;if(e.id!==void 0){let a=n.find((l)=>l.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
260
- `),d;return za(a),o}if(e.enable===void 0&&e.disable===void 0)Xa(n,i);return o}import{rmSync as od}from"node:fs";import{dirname as id}from"node:path";import{readFileSync as Za}from"node:fs";var ed="server.tokenEnv";function dt(e){let s=Za(e,"utf8"),r=GA(e),i=new Map,n=new Set(Kt(s).filter((a)=>a.path===ed).map((a)=>a.name));for(let a of Kt(s)){if(n.has(a.name))continue;let l=i.get(a.name)??[];l.push(a.path),i.set(a.name,l)}return[...i].map(([a,l])=>({name:a,set:tn(r,a),usedBy:l}))}function so(e,s){let r=dt(e).map((l)=>l.name);for(let[l,c]of Object.entries(s)){if(!r.includes(l))throw new t({code:"secret_not_referenced",message:`"${l}" 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.${l}`});if(c==="")throw new t({code:"secret_value_empty",message:`An empty value for ${l} 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.${l}`})}let i=_([e]),n=[],a=[];for(let[l,c]of Object.entries(s))if(Ye(e,l,c),n.push(l),tn(i,l))a.push(l);return{written:n,shadowed:a}}import{createHash as nd}from"node:crypto";import{existsSync as xe,lstatSync as mt,mkdirSync as ct,readdirSync as oo,readFileSync as fn,renameSync as td,rmSync as io,writeFileSync as Ue}from"node:fs";import{basename as Ke,dirname as ao,join as Y}from"node:path";var Le="template.yaml",co=/^[a-z0-9][a-z0-9-]*$/;function ft(e){let s;try{s=oo(e)}catch{return[]}let r=[];for(let i of s.sort()){if(!co.test(i))continue;let n=Y(e,i);if(!mt(n).isDirectory())continue;try{let a=gn(n);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((l)=>({name:l.name,...l.description===void 0?{}:{description:l.description},required:l.required,...l.default===void 0?{}:{default:l.default},secret:l.secret!==void 0}))})}catch(a){if(!f(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function gn(e){let s=Y(e,Le);if(!xe(s))throw new t({code:"template_spec_missing",message:`${Ke(e)} has no ${Le}.`,hint:`A template is an agent directory with a ${Le} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return ii(fn(s,"utf8"),`${Ke(e)}/${Le}`)}function pt(e,s=""){let r=[];for(let i of oo(Y(e,s)).sort()){let n=s===""?i:`${s}/${i}`;if(n===Le)continue;let a=Y(e,n),l=mt(a);if(l.isSymbolicLink())throw new t({code:"template_symlink",message:`${n} 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:n});if(l.isDirectory()){r.push(...pt(e,n));continue}let c=fn(a);if(c.includes(0))throw new t({code:"template_binary_file",message:`${n} 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:n});r.push({relPath:n,contents:c.toString("utf8")})}return r}function uo(e){if(!co.test(e.template))throw ut(e.template,e.templatesDir);let s=Y(e.templatesDir,e.template);if(!xe(s)||!mt(s).isDirectory())throw ut(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new t({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=iA(r),n=Y(e.agentDirBase,i);if(xe(n))throw new t({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=wr({spec:gn(s),files:pt(s),id:i,name:r,vars:e.vars}),l=Y(ao(e.agentDirBase),`.${Ke(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);ct(l,{recursive:!0});try{Oe(l,a.files),vo(l,{template:e.template,name:r,vars:yo(gn(s),e.vars),files:sd(a.files)});let c=Y(l,"agent.yaml");for(let[m,h]of Object.entries(a.env))Ye(c,m,h);let p=a.files.find((m)=>m.relPath==="agent.yaml"),w={};for(let m of Kt(p?.contents??""))if(a.env[m.name]===void 0)w[m.name]="(pending)";He(c,w),ct(e.agentDirBase,{recursive:!0}),td(l,n)}catch(c){throw io(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:n,manifestPath:Y(n,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ut(e,s){let r=ft(s).map((i)=>i.name);return new t({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 ${s}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var go=".template.json";function mn(e){return nd("sha256").update(e).digest("hex")}function sd(e){return Object.fromEntries(e.map((s)=>[s.relPath,mn(s.contents)]))}function yo(e,s){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(s).filter(([i])=>!r.has(i)))}function vo(e,s){Ue(Y(e,go),`${JSON.stringify({version:1,...s},null,2)}
261
- `,{mode:384})}function ko(e){let s=Y(e.agentDir,go);if(!xe(s))throw new t({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(fn(s,"utf8")),i=Y(e.templatesDir,r.template);if(!xe(i))throw ut(r.template,e.templatesDir);let n=gn(i);for(let h of Object.keys(e.vars)){let g=n.vars.find((b)=>b.name===h);if(g?.secret!==void 0)throw new t({code:"template_var_secret",message:`"${h}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${g.secret}.`,field:`vars.${h}`})}let a={...r.vars,...e.vars},l=wr({spec:n,files:pt(i),id:Ke(e.agentDir),name:r.name,vars:{...Object.fromEntries(n.vars.filter((h)=>h.secret!==void 0&&h.required).map((h)=>[h.name,"(in .env)"])),...a}}),c=[],p=[],w=[],m={...r.files};try{for(let h of l.files){let g=Y(e.agentDir,h.relPath),b=r.files[h.relPath];if(!xe(g)){if(b!==void 0){w.push({file:h.relPath,reason:"removed"});continue}ct(ao(g),{recursive:!0}),Ue(g,h.contents),c.push({path:g,before:void 0}),m[h.relPath]=mn(h.contents),p.push(h.relPath);continue}let P=fn(g,"utf8");if(rd(h.relPath,P)){w.push({file:h.relPath,reason:"memory"});continue}if(b===void 0||mn(P)!==b){w.push({file:h.relPath,reason:"edited"});continue}if(P===h.contents)continue;Ue(g,h.contents),c.push({path:g,before:P}),m[h.relPath]=mn(h.contents),p.push(h.relPath)}vo(e.agentDir,{template:r.template,name:r.name,vars:yo(n,a),files:m})}catch(h){throw ro(c),h}return{rendered:p,skipped:w,undo:()=>{ro(c),Ue(s,`${JSON.stringify(r,null,2)}
262
- `,{mode:384})}}}function ro(e){for(let s of e)if(s.before===void 0)io(s.path,{force:!0});else Ue(s.path,s.before)}function rd(e,s){if(Ke(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return Ut(e,s).frontmatter.eviction==="oldest"}catch{return!1}}function ad(){return xt.shape.server.parse({})}async function Eo(e){let s=_(e.manifestPaths),r=dd(s),i=e.store??F(),n=await ts(e.manifestPaths,s,i),a=n.filter((E)=>!E.enabled),l=n.filter((E)=>E.enabled),c=e.manifestPaths.length===0,p=[],w=[];for(let E of l)try{p.push({path:E.manifestPath,loaded:q(E.manifestPath,{env:s})})}catch(T){if(!c)throw T;w.push({path:E.manifestPath,detail:f(T)?T.message:String(T),...f(T)&&T.hint!==void 0?{hint:T.hint}:{}})}let m=p[0],h=m?.loaded,g=h?.manifest.server??ad();for(let E of p.slice(1)){let T=E.loaded.manifest.server;for(let[C,V,Me,Re]of[["server.port",g.port,T.port,e.port!==void 0],["server.host",g.host,T.host,e.host!==void 0],["server.tokenEnv",g.tokenEnv,T.tokenEnv,!1]]){if(Re||V===Me)continue;throw new t({code:"serve_bind_conflict",message:`${m?.path??"the first manifest"} sets ${C} to ${String(V)} and ${E.path} sets it to ${String(Me)}.`,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:C})}}let b=e.port??g.port,P=e.port===void 0,R=e.host??g.host,S=h===void 0?s[g.tokenEnv]:h.env[g.tokenEnv],L=s[g.tokenEnv],D=p.every((E)=>Ft(id(E.path),s)),v=S;if(D&&(L===void 0||L==="")){let E=En(ie(s));if(E!==void 0)v=E;else if(S!==void 0&&S!=="")$r(ie(s),S)}let x=s[`${A.envPrefix}SERVICE`]!==void 0,I=new DA({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)I.on("agent.channel.status",(E)=>{let T=E.data,C=T.input===void 0?"":T.input.kind==="pairing_code"?`
260
+ `),u;return Ga(a),o}if(e.enable===void 0&&e.disable===void 0)Wa(n,i);return o}import{rmSync as Za}from"node:fs";import{dirname as ed}from"node:path";import{readFileSync as Va}from"node:fs";var Ja="server.tokenEnv";function st(e){let s=Va(e,"utf8"),r=Gt(e),i=new Map,n=new Set(KA(s).filter((a)=>a.path===Ja).map((a)=>a.name));for(let a of KA(s)){if(n.has(a.name))continue;let l=i.get(a.name)??[];l.push(a.path),i.set(a.name,l)}return[...i].map(([a,l])=>({name:a,set:An(r,a),usedBy:l}))}function Xr(e,s){let r=st(e).map((l)=>l.name);for(let[l,c]of Object.entries(s)){if(!r.includes(l))throw new A({code:"secret_not_referenced",message:`"${l}" 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.${l}`});if(c==="")throw new A({code:"secret_value_empty",message:`An empty value for ${l} 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.${l}`})}let i=_([e]),n=[],a=[];for(let[l,c]of Object.entries(s))if(Ye(e,l,c),n.push(l),An(i,l))a.push(l);return{written:n,shadowed:a}}import{createHash as Xa}from"node:crypto";import{existsSync as xe,lstatSync as lt,mkdirSync as rt,readdirSync as Yr,readFileSync as fn,renameSync as za,rmSync as Zr,writeFileSync as Le}from"node:fs";import{basename as Ue,dirname as eo,join as Y}from"node:path";var Ne="template.yaml",no=/^[a-z0-9][a-z0-9-]*$/;function ct(e){let s;try{s=Yr(e)}catch{return[]}let r=[];for(let i of s.sort()){if(!no.test(i))continue;let n=Y(e,i);if(!lt(n).isDirectory())continue;try{let a=hn(n);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((l)=>({name:l.name,...l.description===void 0?{}:{description:l.description},required:l.required,...l.default===void 0?{}:{default:l.default},secret:l.secret!==void 0}))})}catch(a){if(!f(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function hn(e){let s=Y(e,Ne);if(!xe(s))throw new A({code:"template_spec_missing",message:`${Ue(e)} has no ${Ne}.`,hint:`A template is an agent directory with a ${Ne} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return ii(fn(s,"utf8"),`${Ue(e)}/${Ne}`)}function mt(e,s=""){let r=[];for(let i of Yr(Y(e,s)).sort()){let n=s===""?i:`${s}/${i}`;if(n===Ne)continue;let a=Y(e,n),l=lt(a);if(l.isSymbolicLink())throw new A({code:"template_symlink",message:`${n} 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:n});if(l.isDirectory()){r.push(...mt(e,n));continue}let c=fn(a);if(c.includes(0))throw new A({code:"template_binary_file",message:`${n} 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:n});r.push({relPath:n,contents:c.toString("utf8")})}return r}function to(e){if(!no.test(e.template))throw at(e.template,e.templatesDir);let s=Y(e.templatesDir,e.template);if(!xe(s)||!lt(s).isDirectory())throw at(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new A({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=it(r),n=Y(e.agentDirBase,i);if(xe(n))throw new A({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=wr({spec:hn(s),files:mt(s),id:i,name:r,vars:e.vars}),l=Y(eo(e.agentDirBase),`.${Ue(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);rt(l,{recursive:!0});try{Ae(l,a.files),oo(l,{template:e.template,name:r,vars:ro(hn(s),e.vars),files:Ya(a.files)});let c=Y(l,"agent.yaml");for(let[m,h]of Object.entries(a.env))Ye(c,m,h);let p=a.files.find((m)=>m.relPath==="agent.yaml"),w={};for(let m of KA(p?.contents??""))if(a.env[m.name]===void 0)w[m.name]="(pending)";De(c,w),rt(e.agentDirBase,{recursive:!0}),za(l,n)}catch(c){throw Zr(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:n,manifestPath:Y(n,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function at(e,s){let r=ct(s).map((i)=>i.name);return new A({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 ${s}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var so=".template.json";function mn(e){return Xa("sha256").update(e).digest("hex")}function Ya(e){return Object.fromEntries(e.map((s)=>[s.relPath,mn(s.contents)]))}function ro(e,s){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(s).filter(([i])=>!r.has(i)))}function oo(e,s){Le(Y(e,so),`${JSON.stringify({version:1,...s},null,2)}
261
+ `,{mode:384})}function io(e){let s=Y(e.agentDir,so);if(!xe(s))throw new A({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(fn(s,"utf8")),i=Y(e.templatesDir,r.template);if(!xe(i))throw at(r.template,e.templatesDir);let n=hn(i);for(let h of Object.keys(e.vars)){let g=n.vars.find((b)=>b.name===h);if(g?.secret!==void 0)throw new A({code:"template_var_secret",message:`"${h}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${g.secret}.`,field:`vars.${h}`})}let a={...r.vars,...e.vars},l=wr({spec:n,files:mt(i),id:Ue(e.agentDir),name:r.name,vars:{...Object.fromEntries(n.vars.filter((h)=>h.secret!==void 0&&h.required).map((h)=>[h.name,"(in .env)"])),...a}}),c=[],p=[],w=[],m={...r.files};try{for(let h of l.files){let g=Y(e.agentDir,h.relPath),b=r.files[h.relPath];if(!xe(g)){if(b!==void 0){w.push({file:h.relPath,reason:"removed"});continue}rt(eo(g),{recursive:!0}),Le(g,h.contents),c.push({path:g,before:void 0}),m[h.relPath]=mn(h.contents),p.push(h.relPath);continue}let P=fn(g,"utf8");if(Qa(h.relPath,P)){w.push({file:h.relPath,reason:"memory"});continue}if(b===void 0||mn(P)!==b){w.push({file:h.relPath,reason:"edited"});continue}if(P===h.contents)continue;Le(g,h.contents),c.push({path:g,before:P}),m[h.relPath]=mn(h.contents),p.push(h.relPath)}oo(e.agentDir,{template:r.template,name:r.name,vars:ro(n,a),files:m})}catch(h){throw zr(c),h}return{rendered:p,skipped:w,undo:()=>{zr(c),Le(s,`${JSON.stringify(r,null,2)}
262
+ `,{mode:384})}}}function zr(e){for(let s of e)if(s.before===void 0)Zr(s.path,{force:!0});else Le(s.path,s.before)}function Qa(e,s){if(Ue(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return UA(e,s).frontmatter.eviction==="oldest"}catch{return!1}}function nd(){return xA.shape.server.parse({})}async function ao(e){let s=_(e.manifestPaths),r=td(s),i=e.store??F(),n=await As(e.manifestPaths,s,i),a=n.filter((E)=>!E.enabled),l=n.filter((E)=>E.enabled),c=e.manifestPaths.length===0,p=[],w=[];for(let E of l)try{p.push({path:E.manifestPath,loaded:q(E.manifestPath,{env:s})})}catch(T){if(!c)throw T;w.push({path:E.manifestPath,detail:f(T)?T.message:String(T),...f(T)&&T.hint!==void 0?{hint:T.hint}:{}})}let m=p[0],h=m?.loaded,g=h?.manifest.server??nd();for(let E of p.slice(1)){let T=E.loaded.manifest.server;for(let[C,V,Ke,Re]of[["server.port",g.port,T.port,e.port!==void 0],["server.host",g.host,T.host,e.host!==void 0],["server.tokenEnv",g.tokenEnv,T.tokenEnv,!1]]){if(Re||V===Ke)continue;throw new A({code:"serve_bind_conflict",message:`${m?.path??"the first manifest"} sets ${C} to ${String(V)} and ${E.path} sets it to ${String(Ke)}.`,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:C})}}let b=e.port??g.port,P=e.port===void 0,R=e.host??g.host,S=h===void 0?s[g.tokenEnv]:h.env[g.tokenEnv],L=s[g.tokenEnv],D=p.every((E)=>FA(ed(E.path),s)),v=S;if(D&&(L===void 0||L==="")){let E=En(ie(s));if(E!==void 0)v=E;else if(S!==void 0&&S!=="")$r(ie(s),S)}let x=s[`${t.envPrefix}SERVICE`]!==void 0,I=new Dt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)I.on("agent.channel.status",(E)=>{let T=E.data,C=T.input===void 0?"":T.input.kind==="pairing_code"?`
263
263
 
264
264
  ${T.input.payload}
265
265
  ${T.input.expiresAt===void 0?"":`
@@ -269,102 +269,102 @@ ${T.input.expiresAt===void 0?"":`
269
269
  `)}),I.on("error",(E)=>{let T=E.data,C=E.sessionKey===void 0?"":` [${E.sessionKey}]`;process.stderr.write(` turn failed${C}: ${T.code}: ${T.message}
270
270
  hint: ${T.hint}
271
271
  `)}),I.on("agent.channel.rejected",(E)=>{let T=E.data;process.stdout.write(` ${T.channelId}: ${T.reason} — ${T.detail}
272
- `)});let N=xr(),K=(E)=>({agents:E,approve:N.approver,env:s,bus:I,toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),O;try{O=await ue.create(K(p.map((E)=>E.path)))}catch(E){if(!c||p.length===0)throw E;let T=[];for(let C of p)try{await(await ue.create({...K([C.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),T.push(C)}catch(V){w.push({path:C.path,detail:f(V)?V.message:String(V),...f(V)&&V.hint!==void 0?{hint:V.hint}:{}})}if(T.length===p.length)throw E;p.splice(0,p.length,...T),O=await ue.create(K(T.map((C)=>C.path)))}ls();let W=ld(),ae=await O.store.operatorKeys.liveCount(),ee=ae===0||e.claim===!0?Wi():void 0,B,Ee=[];try{B=await ud(b,P,(E)=>(Ee.push(E),Xi({runtime:O,host:R,port:E,approvals:N,allowedOrigins:g.allowedOrigins,allowedHosts:g.allowedHosts,resolveAgent:(T)=>Xn(T,s),provision:{steps:()=>Vt({agentDirBase:ie(s)}),create:(T)=>Jt({answers:T,defaults:{agentDirBase:ie(s)}}),templates:()=>ft(mr(s)),createFromTemplate:(T)=>uo({...T,templatesDir:mr(s),agentDirBase:ie(s)}),rerender:(T)=>ko({...T,templatesDir:mr(s)})},secrets:{status:dt,write:so},remover:fd(s),home:we(s),channels:{setEnabled:Jn,setCredential:qn,unpair:Vn},...ee===void 0?{}:{claim:ee},...v===void 0||v===""?{}:{token:v}})))}catch(E){if(await O.stop("server failed to bind"),f(E))throw E;let T=Ee.length>1?` — also tried ${Ee.slice(1).join(", ")}`:"";throw new t({code:"server_bind_failed",message:`Could not bind ${R}:${b}${T}: ${E instanceof Error?E.message:String(E)}`,hint:P?`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:E})}let Ho=O.owned.length===0&&await ns(O.store.leases,{runtimeId:O.runtimeId,mode:x?"daemon":"terminal"});await O.publishAddress(B.url);let te=O.list(),ht=te[0];if(ht!==void 0)process.title=te.length===1?`${A.slug} ${ht.id}`:`${A.slug} ${te.length} agents`;for(let E of te)E.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:B.url,websocket:B.websocket,authenticated:v!==void 0&&v!=="",keys:ae,...ee===void 0?{}:{claim:ee.token},agents:te.map((E)=>({id:E.id,channels:O.channels.statusOf(E.id)})),declined:O.declined.map((E)=>({agentId:E.agentId,pid:E.pid,mode:E.mode,since:E.startedAt})),disabled:a.map((E)=>({agentId:E.agentId,...E.reason===void 0?{}:{reason:E.reason}})),broken:w.map((E)=>({path:E.path,detail:E.detail,...E.hint===void 0?{}:{hint:E.hint}}))})}
273
- `);else{let E=`http://${rn(R)}:${B.port}`,T=E===B.url?"":` (bound ${R} — every interface)`;if(process.stdout.write(`${A.name} serving on ${E}${T}
272
+ `)});let N=xr(),K=(E)=>({agents:E,approve:N.approver,env:s,bus:I,toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),O;try{O=await de.create(K(p.map((E)=>E.path)))}catch(E){if(!c||p.length===0)throw E;let T=[];for(let C of p)try{await(await de.create({...K([C.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),T.push(C)}catch(V){w.push({path:C.path,detail:f(V)?V.message:String(V),...f(V)&&V.hint!==void 0?{hint:V.hint}:{}})}if(T.length===p.length)throw E;p.splice(0,p.length,...T),O=await de.create(K(T.map((C)=>C.path)))}ls();let W=sd(),le=await O.store.operatorKeys.liveCount(),ee=le===0||e.claim===!0?Wi():void 0,B,Ee=[];try{B=await od(b,P,(E)=>(Ee.push(E),Xi({runtime:O,host:R,port:E,approvals:N,allowedOrigins:g.allowedOrigins,allowedHosts:g.allowedHosts,resolveAgent:(T)=>Xn(T,s),provision:{steps:()=>At({agentDirBase:ie(s)}),create:(T)=>Ot({answers:T,defaults:{agentDirBase:ie(s)}}),templates:()=>ct(mr(s)),createFromTemplate:(T)=>to({...T,templatesDir:mr(s),agentDirBase:ie(s)}),rerender:(T)=>io({...T,templatesDir:mr(s)})},secrets:{status:st,write:Xr},remover:ad(s),home:we(s),channels:{setEnabled:Jn,setCredential:qn,unpair:Vn},...ee===void 0?{}:{claim:ee},...v===void 0||v===""?{}:{token:v}})))}catch(E){if(await O.stop("server failed to bind"),f(E))throw E;let T=Ee.length>1?` — also tried ${Ee.slice(1).join(", ")}`:"";throw new A({code:"server_bind_failed",message:`Could not bind ${R}:${b}${T}: ${E instanceof Error?E.message:String(E)}`,hint:P?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${t.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:E})}let _o=O.owned.length===0&&await ns(O.store.leases,{runtimeId:O.runtimeId,mode:x?"daemon":"terminal"});await O.publishAddress(B.url);let re=O.list(),ft=re[0];if(ft!==void 0)process.title=re.length===1?`${t.slug} ${ft.id}`:`${t.slug} ${re.length} agents`;for(let E of re)E.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:B.url,websocket:B.websocket,authenticated:v!==void 0&&v!=="",keys:le,...ee===void 0?{}:{claim:ee.token},agents:re.map((E)=>({id:E.id,channels:O.channels.statusOf(E.id)})),declined:O.declined.map((E)=>({agentId:E.agentId,pid:E.pid,mode:E.mode,since:E.startedAt})),disabled:a.map((E)=>({agentId:E.agentId,...E.reason===void 0?{}:{reason:E.reason}})),broken:w.map((E)=>({path:E.path,detail:E.detail,...E.hint===void 0?{}:{hint:E.hint}}))})}
273
+ `);else{let E=`http://${rn(R)}:${B.port}`,T=E===B.url?"":` (bound ${R} — every interface)`;if(process.stdout.write(`${t.name} serving on ${E}${T}
274
274
  `),B.port!==b)process.stdout.write(` moved from ${b} — something else is on it. \`--port ${b}\` would refuse instead of moving.
275
275
  `);process.stdout.write(` web UI ${E}/ · API reference ${E}/docs
276
- `);for(let C of te){let V=O.channels.statusOf(C.id),Me=V.length===0?"no channels":V.map((Te)=>`${Te.id} (${Te.type}${Te.status==="error"?", BROKEN":""})`).join(", "),Re=C.manifest.schedules.filter((Te)=>Te.enabled),Wo=C.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${C.manifest.schedules.length>Re.length?` (+${C.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${C.id} — ${Me}${Wo}
277
- `)}for(let C of a)process.stdout.write(` ${C.agentId} — stopped${C.reason===void 0?"":` (${C.reason})`}, \`${A.slug} start ${C.agentId}\`
276
+ `);for(let C of re){let V=O.channels.statusOf(C.id),Ke=V.length===0?"no channels":V.map((Te)=>`${Te.id} (${Te.type}${Te.status==="error"?", BROKEN":""})`).join(", "),Re=C.manifest.schedules.filter((Te)=>Te.enabled),No=C.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${C.manifest.schedules.length>Re.length?` (+${C.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${C.id} — ${Ke}${No}
277
+ `)}for(let C of a)process.stdout.write(` ${C.agentId} — stopped${C.reason===void 0?"":` (${C.reason})`}, \`${t.slug} start ${C.agentId}\`
278
278
  `);for(let C of w)if(process.stdout.write(` ${C.path} — NOT served: ${C.detail}
279
279
  `),C.hint!==void 0)process.stdout.write(` hint: ${C.hint}
280
280
  `);for(let C of O.declined)process.stdout.write(` ${C.agentId} — NOT served here: pid ${C.pid} (${C.mode}) already has it
281
- `);if(O.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
281
+ `);if(O.declined.length>0)process.stdout.write(` \`${t.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
282
282
  `);if(ee!==void 0){if(process.stdout.write(` open once to claim this server:
283
283
  ${zi(R,B.port,ee.token)}
284
284
  without a browser: ${Zi(R,B.port,ee.token)}
285
285
  `),v===void 0||v==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
286
286
  `)}if(v===void 0||v==="")process.stdout.write(` unauthenticated — loopback only. Set ${g.tokenEnv} to bind a public host.
287
- `);if(x)process.stdout.write(` running as a background service · ${A.slug} daemon status ${te[0]?.id??""}
287
+ `);if(x)process.stdout.write(` running as a background service · ${t.slug} daemon status ${re[0]?.id??""}
288
288
  `);else if(Gr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
289
- `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${te[0]?.id===void 0?"":` ${te[0].id}`}\` keeps it running.
290
- `)}let gt=!1,yt=async()=>{if(gt)return;if(gt=!0,r>0&&O.all().some((E)=>E.inFlight>0)){let E=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
289
+ `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${t.slug} daemon install${re[0]?.id===void 0?"":` ${re[0].id}`}\` keeps it running.
290
+ `)}let pt=!1,gt=async()=>{if(pt)return;if(pt=!0,r>0&&O.all().some((E)=>E.inFlight>0)){let E=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
291
291
  `);let T=await O.drain(r);process.stdout.write(T===0?`drained in ${Date.now()-E} ms
292
292
  `:`${T} turn(s) still running after ${r} ms; the next start marks them interrupted
293
- `)}if(await B.stop(),Ho)await O.store.leases.release(UA,O.runtimeId).catch(()=>{});await O.stop("interrupted")};return U(yt),await W,process.stdout.write(`stopping
294
- `),await yt(),o}function dd(e){let s=`${A.envPrefix}DRAIN_MS`,r=e[s];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new t({code:"serve_drain_invalid",message:`${s} 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:s});return Number(r)}function ld(){return new Promise((e)=>{let s=()=>{process.off("SIGINT",s),process.off("SIGTERM",s),e()};process.once("SIGINT",s),process.once("SIGTERM",s)})}var cd=16;async function ud(e,s,r){let i=s&&e!==0?e+cd:e;for(let n=e;;n+=1)try{return await r(n)}catch(a){if(n>=i||!md(a))throw a}}function md(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let s=e instanceof Error?e.message:String(e);return s.includes("EADDRINUSE")||s.includes("in use")}function fd(e){return{locate(s){let r=Ae(e).filter((n)=>n.id===s),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${s}" 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 "${s}": ${r.map((n)=>n.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(s){if(!Ft(s,e))throw Error(`refusing to delete ${s}: it is outside the sandbox`);od(s,{recursive:!0,force:!0})}}}function H(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function pd(e){let s=new Map,r=[];for(let i of e){let n=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(n.length!==3||n[0]!=="schedule"){r.push(a);continue}let l=`schedule:${n[1]}`,c=s.get(l);if(c===void 0){let p={...a,sessionKey:`${l}:*`,runs:1};s.set(l,p),r.push(p);continue}if(c.runs=(c.runs??1)+1,c.messages+=i.messages,c.turns+=i.turns,i.lastActivityAt>c.lastActivityAt)c.lastActivityAt=i.lastActivityAt}return r}function hd(e){if(e.length===0){process.stdout.write(`no sessions yet
295
- `);return}let s=pd(e),r=Math.max(7,...s.map((i)=>i.sessionKey.length));process.stdout.write(`${H("SESSION",r)} ${H("MSGS",5)} ${H("TURNS",5)} ${H("PHASE",8)} LAST
296
- `);for(let i of s){let n=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${H(i.sessionKey,r)} ${H(String(i.messages),5)} ${H(String(i.turns),5)} ${H(i.phase??"-",8)} ${nt(i.lastActivityAt,Date.now())}${n}
297
- `)}}async function gd(e,s,r){let i=await e.store.messages.page(e.id,s,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${s}
293
+ `)}if(await B.stop(),_o)await O.store.leases.release(Ut,O.runtimeId).catch(()=>{});await O.stop("interrupted")};return U(gt),await W,process.stdout.write(`stopping
294
+ `),await gt(),o}function td(e){let s=`${t.envPrefix}DRAIN_MS`,r=e[s];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new A({code:"serve_drain_invalid",message:`${s} 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:s});return Number(r)}function sd(){return new Promise((e)=>{let s=()=>{process.off("SIGINT",s),process.off("SIGTERM",s),e()};process.once("SIGINT",s),process.once("SIGTERM",s)})}var rd=16;async function od(e,s,r){let i=s&&e!==0?e+rd:e;for(let n=e;;n+=1)try{return await r(n)}catch(a){if(n>=i||!id(a))throw a}}function id(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let s=e instanceof Error?e.message:String(e);return s.includes("EADDRINUSE")||s.includes("in use")}function ad(e){return{locate(s){let r=te(e).filter((n)=>n.id===s),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${s}" 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 "${s}": ${r.map((n)=>n.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(s){if(!FA(s,e))throw Error(`refusing to delete ${s}: it is outside the sandbox`);Za(s,{recursive:!0,force:!0})}}}function H(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function dd(e){let s=new Map,r=[];for(let i of e){let n=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(n.length!==3||n[0]!=="schedule"){r.push(a);continue}let l=`schedule:${n[1]}`,c=s.get(l);if(c===void 0){let p={...a,sessionKey:`${l}:*`,runs:1};s.set(l,p),r.push(p);continue}if(c.runs=(c.runs??1)+1,c.messages+=i.messages,c.turns+=i.turns,i.lastActivityAt>c.lastActivityAt)c.lastActivityAt=i.lastActivityAt}return r}function ld(e){if(e.length===0){process.stdout.write(`no sessions yet
295
+ `);return}let s=dd(e),r=Math.max(7,...s.map((i)=>i.sessionKey.length));process.stdout.write(`${H("SESSION",r)} ${H("MSGS",5)} ${H("TURNS",5)} ${H("PHASE",8)} LAST
296
+ `);for(let i of s){let n=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${H(i.sessionKey,r)} ${H(String(i.messages),5)} ${H(String(i.turns),5)} ${H(i.phase??"-",8)} ${nA(i.lastActivityAt,Date.now())}${n}
297
+ `)}}async function cd(e,s,r){let i=await e.store.messages.page(e.id,s,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${s}
298
298
  `);return}for(let n of[...i.messages].reverse())process.stdout.write(`${n.role}: ${n.content}
299
299
  `);if(i.nextBefore!==void 0)process.stdout.write(`
300
300
  … older messages exist; raise --limit
301
- `)}async function yd(e,s,r){let i=await e.turns(s,r);if(i.length===0){process.stdout.write(`no turns in ${s}
301
+ `)}async function ud(e,s,r){let i=await e.turns(s,r);if(i.length===0){process.stdout.write(`no turns in ${s}
302
302
  `);return}process.stdout.write(`${H("TURN",22)} ${H("STATUS",9)} ${H("STEPS",5)} ${H("TOKENS",13)} ${H("MS",6)} SOURCE
303
303
  `);for(let n of i)if(process.stdout.write(`${H(n.turnId,22)} ${H(n.status,9)} ${H(String(n.steps),5)} ${H(`${n.promptTokens}/${n.outputTokens}`,13)} ${H(String(n.durationMs??"-"),6)} ${n.source}
304
304
  `),n.errorCode!==void 0){if(process.stdout.write(` ${n.errorCode}: ${n.errorMessage}
305
305
  `),n.errorHint!==void 0)process.stdout.write(` hint: ${n.errorHint}
306
- `)}}async function Po(e){let s=await ue.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_([e.manifestPath])});U(()=>s.stop("cli-exit"));let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Uo;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
306
+ `)}}async function co(e){let s=await de.create({agents:[e.manifestPath],store:e.store??F(),toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_([e.manifestPath])});U(()=>s.stop("cli-exit"));let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Uo;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
307
307
  `),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:s.store.location,sessions:await r.sessions()}:{store:s.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)}
308
308
  `),o}if(process.stdout.write(`store: ${s.store.location}
309
309
 
310
- `),e.sessionKey===void 0)return hd(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}
310
+ `),e.sessionKey===void 0)return ld(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}
311
311
  hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
312
- `),d;if(e.turns===!0)await yd(r,e.sessionKey,i);else await gd(r,e.sessionKey,i);return o}import{existsSync as wd,readFileSync as bd,writeFileSync as $d}from"node:fs";import{basename as vd,dirname as kd,join as Sd}from"node:path";var Ed=/^(#{1,6})\s+(.*)$/,Rd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Pd=/^[ \t]*<\/rules>[ \t]*$/,xd=/^\s*(?:```|~~~)/;function xo(e){if(e.action!=="distill")throw new t({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 s;try{s=bd(e.file,"utf8")}catch{throw new t({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=vd(e.file),i=e.out??Sd(kd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(wd(i))throw new t({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:n}=Ut(r,s),a=Td(r,n);return $d(i,a,"utf8"),process.stdout.write(`wrote ${i}
312
+ `),u;if(e.turns===!0)await ud(r,e.sessionKey,i);else await cd(r,e.sessionKey,i);return o}import{existsSync as md,readFileSync as fd,writeFileSync as pd}from"node:fs";import{basename as hd,dirname as gd,join as yd}from"node:path";var wd=/^(#{1,6})\s+(.*)$/,bd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,$d=/^[ \t]*<\/rules>[ \t]*$/,vd=/^\s*(?:```|~~~)/;function uo(e){if(e.action!=="distill")throw new A({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 s;try{s=fd(e.file,"utf8")}catch{throw new A({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=hd(e.file),i=e.out??yd(gd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(md(i))throw new A({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:n}=UA(r,s),a=kd(r,n);return pd(i,a,"utf8"),process.stdout.write(`wrote ${i}
313
313
 
314
314
  The scaffold copies ${r}'s headings and its <rules> blocks verbatim, and leaves a
315
315
  {{PLACEHOLDER}} under each heading. Now:
316
316
  `+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
317
317
  `+` document's own voice. The workspace command warns until none are left.
318
318
  2. Name the file in context.soul.distilled.
319
- `),o}function Td(e,s){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,n=!1,a=0,l=!1;for(let c of s.split(`
320
- `)){if(xd.test(c)){if(i=!i,n)r.push(c);continue}if(i){if(n)r.push(c);continue}if(Rd.test(c)){n=!0,r.push(c);continue}if(n){if(r.push(c),Pd.test(c))n=!1,r.push("");continue}if(Ed.exec(c)!==null)l=!0,a+=1,r.push(c),r.push(""),r.push(`{{SECTION_${a}}}`),r.push("")}if(!l)r.push("{{ESSENCE}}"),r.push("");return`${r.join(`
319
+ `),o}function kd(e,s){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,n=!1,a=0,l=!1;for(let c of s.split(`
320
+ `)){if(vd.test(c)){if(i=!i,n)r.push(c);continue}if(i){if(n)r.push(c);continue}if(bd.test(c)){n=!0,r.push(c);continue}if(n){if(r.push(c),$d.test(c))n=!1,r.push("");continue}if(wd.exec(c)!==null)l=!0,a+=1,r.push(c),r.push(""),r.push(`{{SECTION_${a}}}`),r.push("")}if(!l)r.push("{{ESSENCE}}"),r.push("");return`${r.join(`
321
321
  `).replace(/\n{3,}/g,`
322
322
 
323
323
  `).trimEnd()}
324
- `}var Id=["list","add","remove","update","search"],Ad=12;async function To(e){try{switch(e.action){case"list":return Od(e);case"add":return _d(e);case"remove":return Nd(e);case"update":return await jd(e);case"search":return await Fd(e);default:throw new t({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Id.join(", ")}.`})}}catch(s){if(f(s))return process.stdout.write(`${s.message}
324
+ `}var Sd=["list","add","remove","update","search"],Ed=12;async function go(e){try{switch(e.action){case"list":return Rd(e);case"add":return Pd(e);case"remove":return Td(e);case"update":return await Id(e);case"search":return await Ad(e);default:throw new A({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Sd.join(", ")}.`})}}catch(s){if(f(s))return process.stdout.write(`${s.message}
325
325
 
326
326
  ${s.hint}
327
- `),d;throw s}}function Od(e){let r=ve(e.env).map((i)=>{let n=ir(i.name,e.env);return{...i,cached:uA(i.name,e.env),commit:n.commit,fetchedAt:n.fetchedAt,skills:n.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:$n(e.env),sources:r},null,2)}
327
+ `),u;throw s}}function Rd(e){let r=ve(e.env).map((i)=>{let n=ir(i.name,e.env);return{...i,cached:dt(i.name,e.env),commit:n.commit,fetchedAt:n.fetchedAt,skills:n.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:$n(e.env),sources:r},null,2)}
328
328
  `),o;if(r.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
329
329
 
330
- \`sources add <name> <url>\` to add one, or \`sources add ${Mt[0]?.name??"anthropic"} ${Mt[0]?.url??""}\` to put a built-in back.
330
+ \`sources add <name> <url>\` to add one, or \`sources add ${MA[0]?.name??"anthropic"} ${MA[0]?.url??""}\` to put a built-in back.
331
331
  `),o;process.stdout.write(k("sources",!0));for(let i of r)process.stdout.write(`
332
332
  ${Q(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
333
- `),process.stdout.write(y(u([{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(`
333
+ `),process.stdout.write(y(d([{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(`
334
334
  ${k("registry")}
335
335
  ${y($n(e.env))}
336
- `),o}function _d(e){let[s,r]=e.rest;if(s===void 0)throw new t({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,n=i?r:s,a=rr(n),l=i?s:Cd(a.url);if(!Tt(l))throw new t({code:"sources_name_invalid",message:`${JSON.stringify(l)} 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 c=ve(e.env).find((h)=>h.name===l);if(c!==void 0&&!i)throw new t({code:"sources_name_taken",message:`${l} is already a source, pointing at ${c.url}`,hint:`Give this one its own name: \`sources add <name> ${n}\`.`});let p=e.path??a.path,w=e.ref??a.ref,m={name:l,url:a.url,...p===void 0?{}:{path:p},...w===void 0?{}:{ref:w}};if(os(m,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:m},null,2)}
337
- `),o;return process.stdout.write(`${u([{label:c===void 0?"added":"replaced",value:l},{label:"url",value:m.url},...m.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:m.path}],...m.ref===void 0?[]:[{label:"branch",value:m.ref}]])}
336
+ `),o}function Pd(e){let[s,r]=e.rest;if(s===void 0)throw new A({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,n=i?r:s,a=rr(n),l=i?s:xd(a.url);if(!TA(l))throw new A({code:"sources_name_invalid",message:`${JSON.stringify(l)} 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 c=ve(e.env).find((h)=>h.name===l);if(c!==void 0&&!i)throw new A({code:"sources_name_taken",message:`${l} is already a source, pointing at ${c.url}`,hint:`Give this one its own name: \`sources add <name> ${n}\`.`});let p=e.path??a.path,w=e.ref??a.ref,m={name:l,url:a.url,...p===void 0?{}:{path:p},...w===void 0?{}:{ref:w}};if(os(m,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:m},null,2)}
337
+ `),o;return process.stdout.write(`${d([{label:c===void 0?"added":"replaced",value:l},{label:"url",value:m.url},...m.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:m.path}],...m.ref===void 0?[]:[{label:"branch",value:m.ref}]])}
338
338
  `),process.stdout.write(`${k("next")}
339
339
  ${Q(`sources update ${l}`)}
340
340
  ${Q("sources search <what you need>")}
341
- `),o}function Cd(e){let s=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(s[s.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Nd(e){let s=e.rest[0];if(s===void 0)throw new t({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=ve(e.env).map((n)=>n.name);if(!rs(s,e.env)){let n=j(s,r);throw new t({code:"sources_unknown",message:`no source called ${s}`,hint:n===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${n}?`})}let i=Mt.some((n)=>n.name===s);return process.stdout.write(`removed ${s}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
341
+ `),o}function xd(e){let s=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(s[s.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Td(e){let s=e.rest[0];if(s===void 0)throw new A({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=ve(e.env).map((n)=>n.name);if(!rs(s,e.env)){let n=j(s,r);throw new A({code:"sources_unknown",message:`no source called ${s}`,hint:n===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${n}?`})}let i=MA.some((n)=>n.name===s);return process.stdout.write(`removed ${s}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
342
342
  `),process.stdout.write(`
343
343
  The cached copy is left on disk; nothing already installed into an agent is touched.
344
- `),o}async function jd(e){let s=ve(e.env),r=e.rest.length===0?s:e.rest.map((a)=>{let l=s.find((c)=>c.name===a);if(l===void 0){let c=j(a,s.map((p)=>p.name));throw new t({code:"sources_unknown",message:`no source called ${a}`,hint:c===void 0?`Configured: ${s.map((p)=>p.name).join(", ")||"none"}.`:`Did you mean ${c}?`})}return l});if(r.length===0)return process.stdout.write(`no sources configured
344
+ `),o}async function Id(e){let s=ve(e.env),r=e.rest.length===0?s:e.rest.map((a)=>{let l=s.find((c)=>c.name===a);if(l===void 0){let c=j(a,s.map((p)=>p.name));throw new A({code:"sources_unknown",message:`no source called ${a}`,hint:c===void 0?`Configured: ${s.map((p)=>p.name).join(", ")||"none"}.`:`Did you mean ${c}?`})}return l});if(r.length===0)return process.stdout.write(`no sources configured
345
345
 
346
346
  \`sources add <url>\` to add one.
347
- `),o;let i=[],n=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let l=await Rt(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:l.commit,skills:l.skills}),e.json!==!0)process.stdout.write(`${l.skills} skills at ${l.commit}${l.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
347
+ `),o;let i=[],n=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let l=await RA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:l.commit,skills:l.skills}),e.json!==!0)process.stdout.write(`${l.skills} skills at ${l.commit}${l.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
348
348
  `)}catch(l){let c=l instanceof Error?l.message:String(l);if(n.push({name:a.name,reason:c}),e.json!==!0)process.stdout.write(`failed
349
349
  `);if(e.json!==!0&&f(l))process.stdout.write(`${y(l.message)}
350
350
  ${y(l.hint,4)}
351
351
  `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:n},null,2)}
352
- `);return i.length===0?d:o}async function Fd(e){let s=e.rest.join(" ").trim(),r=ve(e.env);if(r.length===0)return process.stdout.write(`no sources configured
352
+ `);return i.length===0?u:o}async function Ad(e){let s=e.rest.join(" ").trim(),r=ve(e.env);if(r.length===0)return process.stdout.write(`no sources configured
353
353
 
354
354
  \`sources add <url>\` to add one.
355
- `),d;let i=r.filter((c)=>!uA(c.name,e.env));for(let c of i){if(e.json!==!0)process.stdout.write(`fetching ${c.name} for the first time … `);try{let p=await Rt(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${p.skills} skills
355
+ `),u;let i=r.filter((c)=>!dt(c.name,e.env));for(let c of i){if(e.json!==!0)process.stdout.write(`fetching ${c.name} for the first time … `);try{let p=await RA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${p.skills} skills
356
356
  `)}catch(p){if(e.json!==!0){if(process.stdout.write(`failed
357
357
  `),f(p))process.stdout.write(`${y(p.message)}
358
- `)}}}let n=r.flatMap((c)=>HA(c,e.env));if(n.length===0)return process.stdout.write(`
358
+ `)}}}let n=r.flatMap((c)=>Ht(c,e.env));if(n.length===0)return process.stdout.write(`
359
359
  nothing to search — no source has been fetched successfully
360
360
 
361
361
  \`sources update\` reports why.
362
- `),d;let a=s.length===0?n:Ld(s,n);if(a.length===0)return process.stdout.write(`
362
+ `),u;let a=s.length===0?n:Od(s,n);if(a.length===0)return process.stdout.write(`
363
363
  nothing in ${n.length} skills across ${r.length} sources matches ${JSON.stringify(s)}
364
364
 
365
365
  Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
366
366
  `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:s,searched:n.length,results:a.map((c)=>({source:c.source,skill:c.skill,description:c.description,tokens:c.tokens,scripts:c.scripts.length,repoPath:c.repoPath,...c.problem===void 0?{}:{problem:c.problem}}))},null,2)}
367
- `),o;let l=a.slice(0,Ad);process.stdout.write(`
367
+ `),o;let l=a.slice(0,Ed);process.stdout.write(`
368
368
  ${k(s.length===0?`${n.length} skills`:`${a.length} of ${n.length} skills match ${JSON.stringify(s)}`,!0)}
369
369
  `);for(let c of l){process.stdout.write(`${Q(`${c.source}/${c.skill}`)} ${c.tokens} tokens${c.scripts.length===0?"":`, ${c.scripts.length} runnable file${c.scripts.length===1?"":"s"}`}${c.problem===void 0?"":" — will not load"}
370
370
  `);let p=c.problem??c.description;process.stdout.write(`${y(p.length>160?`${p.slice(0,157)}…`:p,4)}
@@ -373,23 +373,23 @@ ${y(`… and ${a.length-l.length} more; narrow the query or use --json`)}
373
373
  `);return process.stdout.write(`
374
374
  ${k("install")}
375
375
  ${y(`skills install <agent> ${l[0]?.source}/${l[0]?.skill}`)}
376
- `),o}function Ld(e,s){let r=new Map,i=s.map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return Yt(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}async function Ao(e){let s=Ud(e.manifestPath),r=await or(s,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await nr(s,!0,void 0,e.store);let n=await Je(e.store),a=!1;if(n===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(n.baseUrl===void 0)i.push(`pid ${n.pid} is a ${n.mode} session, which serves no HTTP to adopt into`);else{let l=await dA(n,`/v1/agents/${encodeURIComponent(s)}/start`,{},e.manifestPath);if(l.ok)a=!0,i.push(`adopted by pid ${n.pid}, live now`);else if(l.status===501)i.push(`pid ${n.pid} cannot look up manifests — restart it to pick this up`);else if(l.status===401)i.push(`pid ${n.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${n.pid} could not adopt it${l.detail===void 0?"":`: ${l.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:s,enabled:!0,running:a,...n===void 0?{}:{pid:n.pid,mode:n.mode},note:i.join(" · ")}]},null,2)}
377
- `);else if(process.stdout.write(`${u([{label:s,value:a?"running":"switched on",note:i.join(" · ")}])}
376
+ `),o}function Od(e,s){let r=new Map,i=s.map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return YA(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}async function yo(e){let s=_d(e.manifestPath),r=await or(s,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await nr(s,!0,void 0,e.store);let n=await Je(e.store),a=!1;if(n===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(n.baseUrl===void 0)i.push(`pid ${n.pid} is a ${n.mode} session, which serves no HTTP to adopt into`);else{let l=await ut(n,`/v1/agents/${encodeURIComponent(s)}/start`,{},e.manifestPath);if(l.ok)a=!0,i.push(`adopted by pid ${n.pid}, live now`);else if(l.status===501)i.push(`pid ${n.pid} cannot look up manifests — restart it to pick this up`);else if(l.status===401)i.push(`pid ${n.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${n.pid} could not adopt it${l.detail===void 0?"":`: ${l.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:s,enabled:!0,running:a,...n===void 0?{}:{pid:n.pid,mode:n.mode},note:i.join(" · ")}]},null,2)}
377
+ `);else if(process.stdout.write(`${d([{label:s,value:a?"running":"switched on",note:i.join(" · ")}])}
378
378
  `),!a&&n!==void 0&&n.baseUrl!==void 0)process.stdout.write(`
379
- Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
380
- `);return n!==void 0&&n.baseUrl!==void 0&&!a?d:o}function Ud(e){let s=G(e);if(s.id===void 0||s.id==="")throw new t({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 s.id}async function Oo(e){let s=await bn(e.store),r=new Map;for(let a of s){if(a.serving===void 0)continue;let l=await on(a.manifestPath,e.store);if(l!==void 0)r.set(a.ref,l)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:s.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
381
- `),o;let i=await FA({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${u(vn(s))}
379
+ Switched on but not yet running. \`${t.slug} daemon restart\` picks it up.
380
+ `);return n!==void 0&&n.baseUrl!==void 0&&!a?u:o}function _d(e){let s=G(e);if(s.id===void 0||s.id==="")throw new A({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 s.id}async function vo(e){let s=await wn(e.store),r=new Map;for(let a of s){if(a.serving===void 0)continue;let l=await on(a.manifestPath,e.store);if(l!==void 0)r.set(a.ref,l)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:s.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
381
+ `),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${d(bn(s))}
382
382
  `);let n=[];for(let[a,l]of r)for(let c of l.values())n.push({label:`${a} / ${c.id}`,value:c.status,note:c.input!==void 0?`${c.detail??"enter this code"}: ${c.input.payload}`:c.detail??""});if(n.length>0)process.stdout.write(`
383
- ${u(n)}
384
- `);return i}import{copyFileSync as Kd,existsSync as Md,mkdirSync as Dd,readFileSync as Hd,writeFileSync as Wd}from"node:fs";import{dirname as Gd,join as _o}from"node:path";async function No(e){let s=e.env??_([]),r=e.home??s.HOME??"",i=Xe(s),n=ze(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:n?.how??"unknown",configPath:n?.configPath===void 0?void 0:_o(r,n.configPath),line:n?.line,steps:n?.steps},null,2)}
385
- `),n===void 0?d:o;if(process.stdout.write(`${k("shift+enter",!0)}
383
+ ${d(n)}
384
+ `);return i}import{copyFileSync as Cd,existsSync as Nd,mkdirSync as jd,readFileSync as Fd,writeFileSync as Ld}from"node:fs";import{dirname as Ud,join as ko}from"node:path";async function Eo(e){let s=e.env??_([]),r=e.home??s.HOME??"",i=Xe(s),n=ze(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:n?.how??"unknown",configPath:n?.configPath===void 0?void 0:ko(r,n.configPath),line:n?.line,steps:n?.steps},null,2)}
385
+ `),n===void 0?u:o;if(process.stdout.write(`${k("shift+enter",!0)}
386
386
  ${y("⌥ 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.")}
387
387
  `),n===void 0)return process.stdout.write(`
388
388
  ${k("this terminal was not recognised")}
389
389
  ${y(`TERM_PROGRAM=${s.TERM_PROGRAM??"(unset)"} TERM=${s.TERM??"(unset)"}`)}
390
- ${y(`known: ${Zt().map((a)=>a.name).join(", ")}`)}
390
+ ${y(`known: ${Lt().map((a)=>a.name).join(", ")}`)}
391
391
  ${Q("⌥⏎ works here regardless — nothing needs configuring for it")}
392
- `),d;if(process.stdout.write(`
392
+ `),u;if(process.stdout.write(`
393
393
  ${k(n.name)}
394
394
  `),n.how!=="write"){process.stdout.write(`${y(n.how==="unverified"?`no verified recipe for this one — ${n.reason??"nobody has checked it"}`:`this one has to be done by hand — ${n.reason??"its settings are not a text file"}`)}
395
395
 
@@ -398,25 +398,25 @@ ${k(n.name)}
398
398
  ${Q("⌥⏎ works here today — nothing has to be configured for it")}
399
399
  `:`
400
400
  ${Q("then restart the terminal and press shift+⏎ in a session to check it")}
401
- `),o}return await qd(n,{...e,env:s,home:r})}async function qd(e,s){let r=_o(s.home,e.configPath??""),i=Md(r)?Hd(r,"utf8"):"";if(es(i,e))return process.stdout.write(`${y("already configured — a binding for shift+enter is present")}
402
- ${y(tt(r,s.home),4)}
403
- `),o;let n=as(i,e);if(n===void 0)return process.stdout.write(`${y("this file is not in a shape this command can edit safely:")}
404
- ${y(tt(r,s.home),4)}
401
+ `),o}return await Kd(n,{...e,env:s,home:r})}async function Kd(e,s){let r=ko(s.home,e.configPath??""),i=Nd(r)?Fd(r,"utf8"):"";if(qt(i,e))return process.stdout.write(`${y("already configured — a binding for shift+enter is present")}
402
+ ${y(AA(r,s.home),4)}
403
+ `),o;let n=Bt(i,e);if(n===void 0)return process.stdout.write(`${y("this file is not in a shape this command can edit safely:")}
404
+ ${y(AA(r,s.home),4)}
405
405
  ${Q("add the line below by hand:")}
406
406
  ${y(e.line??"",4)}
407
- `),d;if(process.stdout.write(`${u([{label:"file",value:tt(r,s.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
407
+ `),u;if(process.stdout.write(`${d([{label:"file",value:AA(r,s.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
408
408
  `),s.dryRun===!0)return process.stdout.write(`
409
409
  ${Q("--dry-run: nothing was written")}
410
410
  `),o;if(s.yes!==!0){if(!(s.confirm===void 0?!1:await s.confirm("write this change?")))return process.stdout.write(`
411
411
  ${Q("nothing was written")}
412
- `),o}try{if(Dd(Gd(r),{recursive:!0}),i!=="")Kd(r,`${r}.${A.slug}-backup`);Wd(r,n,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
413
- `),d}return process.stdout.write(`
412
+ `),o}try{if(jd(Ud(r),{recursive:!0}),i!=="")Cd(r,`${r}.${t.slug}-backup`);Ld(r,n,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
413
+ `),u}return process.stdout.write(`
414
414
  ${k("done")}
415
- ${i===""?"":`${y(`a copy of the old file is at ${tt(`${r}.${A.slug}-backup`,s.home)}`)}
415
+ ${i===""?"":`${y(`a copy of the old file is at ${AA(`${r}.${t.slug}-backup`,s.home)}`)}
416
416
  `}${Q("restart the terminal, then press shift+⏎ in a session to check it")}
417
- `),o}async function jo(e){return e.warm===!0?await Bd(e):await Vd(e)}async function Bd(e){let s=q(e.manifestPath,{env:_([e.manifestPath])}),r=BA(s.manifest.tools).selections,i=s.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.
417
+ `),o}async function Po(e){return e.warm===!0?await Md(e):await Dd(e)}async function Md(e){let s=q(e.manifestPath,{env:_([e.manifestPath])}),r=ht(s.manifest.tools).selections,i=s.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.
418
418
  `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((c)=>c.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
419
- `),o;let n=[],a=new Set;for(let c of r){let p=oe[c.id];if(p===void 0)return d;let w;try{let m=p({dir:s.dir,env:s.env,config:c.config,agentId:s.manifest.id});if(m.refresh===void 0){for(let h of await m.resolve(i))a.add(h.spec.slug);if(e.json!==!0)process.stdout.write(`${c.id}: nothing to warm — it resolves without a cache.
419
+ `),o;let n=[],a=new Set;for(let c of r){let p=oe[c.id];if(p===void 0)return u;let w;try{let m=p({dir:s.dir,env:s.env,config:c.config,agentId:s.manifest.id});if(m.refresh===void 0){for(let h of await m.resolve(i))a.add(h.spec.slug);if(e.json!==!0)process.stdout.write(`${c.id}: nothing to warm — it resolves without a cache.
420
420
  `);continue}w=await m.refresh(i)}catch(m){let h=f(m)?`${m.message}
421
421
  hint: ${m.hint}`:m instanceof Error?m.message:String(m);process.stdout.write(`${c.id}: not warmed — ${h}
422
422
  `);continue}for(let m of i)if(!w.missing.includes(m))a.add(m);n.push({provider:c.id,fetched:w.fetched,changed:[...w.changed],missing:[...w.missing],cachePath:"cachePath"in w&&typeof w.cachePath==="string"?w.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(n,null,2)}
@@ -424,17 +424,17 @@ ${i===""?"":`${y(`a copy of the old file is at ${tt(`${r}.${A.slug}-backup`,s.ho
424
424
  `),c.changed.length>0)process.stdout.write(` changed: ${c.changed.join(", ")}
425
425
  `);if(c.cachePath!=="")process.stdout.write(` cache: ${c.cachePath}
426
426
  `)}let l=i.filter((c)=>!a.has(c));for(let c of l)process.stdout.write(` missing: ${c} — no configured provider has a tool with that slug
427
- `);return l.length>0?d:o}async function Vd(e){let s=await ue.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:he,pluginRoot:se(),scriptRunner:de(),channels:ce,env:_([e.manifestPath])});try{let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Zo(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
428
- `:`${St(i)}
429
- `),o}finally{await s.stop("cli-exit")}}import{dirname as Fo,isAbsolute as Jd,resolve as wn}from"node:path";async function Ko(e){try{let s=G(e.manifestPath),r=await So({refs:s.plugins??[],agentId:s.id??e.manifestPath,paths:{workspace:Fo(wn(e.manifestPath)),state:Fo(wn(e.manifestPath)),manifest:wn(e.manifestPath)},env:_([e.manifestPath]),bus:new DA({runtimeId:"validate"}),builtIn:he,pluginRoot:se(),base:{toolProviders:oe,modelTransports:Se,mediaProviders:Ie,channels:ce}}),i=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:n}=i,a=ye(n.model.main.id,n.model.main.capabilities),{workspace:l,warnings:c}=It(i,a.promptStyle),p=bo(Do(i,{channels:r.channels})),w=await pn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let v of w.providers)await v.stop?.();let m=fo(n,{env:i.env,transports:new Map([...at,...Object.entries(r.modelTransports)])});Ht(n,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let h=zA(l,n.context.rules);if(h!==void 0&&n.context.rules.onExceed==="fail")throw h;let g=[...c,...r.failed,...w.warnings,...w.registry.warnings,...p,...ho(n),...Bo(n),...h===void 0?[]:[h.toDetail()]],b=n.knowledge===void 0?void 0:wo({dir:Jd(n.knowledge.dir)?n.knowledge.dir:wn(i.dir,n.knowledge.dir),maxActive:n.knowledge.maxActive,budget:n.knowledge.budget,style:a.promptStyle}),P=["static","volatile","reminder"].map((v)=>{let x=l.files.filter((I)=>I.tier===v).map((I)=>I.name);if(x.length===0)return;return`${v}=${x.join(",")} (${l.tokens[v]}/${n.context.budgets[v]})`}).filter((v)=>v!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:n.id,model:n.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((v)=>({name:v.name,tier:v.tier,editable:v.editable,tokens:v.tokens,budget:v.budget})),tokens:l.tokens},knowledge:b===void 0?[]:b.entries.map((v)=>({name:v.name,keywords:v.keywords,tokens:v.tokens})),warnings:g},null,2)}
430
- `),o;let R=NA(n),S=R.map((v)=>v.role===v.configuredAs?`${v.role}=${v.modelId}`:`${v.role}=→main`).join(" "),L=R.filter((v)=>v.role===v.configuredAs),D=Ji({manifestPath:e.manifestPath,rawModelId:s.modelId,apiKeyEnv:n.model.main.apiKeyEnv}).flatMap((v)=>{let x=ji(v.origin);return x===void 0?[]:[` env ${v.variable} — ${x}
427
+ `);return l.length>0?u:o}async function Dd(e){let s=await de.create({agents:[e.manifestPath],toolProviders:oe,modelTransports:Se,mediaProviders:Ie,builtInPlugins:Be,pluginRoot:se(),scriptRunner:ue(),channels:ce,env:_([e.manifestPath])});try{let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Zo(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
428
+ `:`${SA(i)}
429
+ `),o}finally{await s.stop("cli-exit")}}import{dirname as xo,isAbsolute as Hd,resolve as gn}from"node:path";async function To(e){try{let s=G(e.manifestPath),r=await So({refs:s.plugins??[],agentId:s.id??e.manifestPath,paths:{workspace:xo(gn(e.manifestPath)),state:xo(gn(e.manifestPath)),manifest:gn(e.manifestPath)},env:_([e.manifestPath]),bus:new Dt({runtimeId:"validate"}),builtIn:Be,pluginRoot:se(),base:{toolProviders:oe,modelTransports:Se,mediaProviders:Ie,channels:ce}}),i=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:n}=i,a=ye(n.model.main.id,n.model.main.capabilities),{workspace:l,warnings:c}=IA(i,a.promptStyle),p=bo(Do(i,{channels:r.channels})),w=await pn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let v of w.providers)await v.stop?.();let m=fo(n,{env:i.env,transports:new Map([...aA,...Object.entries(r.modelTransports)])});HA(n,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let h=zt(l,n.context.rules);if(h!==void 0&&n.context.rules.onExceed==="fail")throw h;let g=[...c,...r.failed,...w.warnings,...w.registry.warnings,...p,...Bo(n),...ho(n),...h===void 0?[]:[h.toDetail()]],b=n.knowledge===void 0?void 0:wo({dir:Hd(n.knowledge.dir)?n.knowledge.dir:gn(i.dir,n.knowledge.dir),maxActive:n.knowledge.maxActive,budget:n.knowledge.budget,style:a.promptStyle}),P=["static","volatile","reminder"].map((v)=>{let x=l.files.filter((I)=>I.tier===v).map((I)=>I.name);if(x.length===0)return;return`${v}=${x.join(",")} (${l.tokens[v]}/${n.context.budgets[v]})`}).filter((v)=>v!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:n.id,model:n.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((v)=>({name:v.name,tier:v.tier,editable:v.editable,tokens:v.tokens,budget:v.budget})),tokens:l.tokens},knowledge:b===void 0?[]:b.entries.map((v)=>({name:v.name,keywords:v.keywords,tokens:v.tokens})),warnings:g},null,2)}
430
+ `),o;let R=Nt(n),S=R.map((v)=>v.role===v.configuredAs?`${v.role}=${v.modelId}`:`${v.role}=→main`).join(" "),L=R.filter((v)=>v.role===v.configuredAs),D=Ji({manifestPath:e.manifestPath,rawModelId:s.modelId,apiKeyEnv:n.model.main.apiKeyEnv}).flatMap((v)=>{let x=ji(v.origin);return x===void 0?[]:[` env ${v.variable} — ${x}
431
431
  `]}).join("");return process.stdout.write(`ok ${i.path}
432
432
  id ${n.id}${n.name===void 0?"":` (${n.name})`}
433
433
  models ${S}
434
- `+D+` window ${i.window} ${st(R[0]?.window)} (reserveOutput ${n.context.reserveOutput}, maxOutput ${a.maxOutput})
435
- `+(L.length<2?"":`${L.slice(1).map((v)=>` ${v.role.padEnd(12)} ${v.modelId} · window ${v.window.contextWindow} ${st(v.window)}
434
+ `+D+` window ${i.window} ${sA(R[0]?.window)} (reserveOutput ${n.context.reserveOutput}, maxOutput ${a.maxOutput})
435
+ `+(L.length<2?"":`${L.slice(1).map((v)=>` ${v.role.padEnd(12)} ${v.modelId} · window ${v.window.contextWindow} ${sA(v.window)}
436
436
  `).join("")}`)+` capabilities thinking=${m.main.capabilities.thinking} promptCache=${m.main.capabilities.promptCache} nativeTools=${m.main.capabilities.nativeTools} strictSchema=${m.main.capabilities.strictSchema}
437
- `+Xd(m.main.capabilities.promptCache,n.model.main.id)+` dialect ${n.tools.dialect}
437
+ `+Wd(m.main.capabilities.promptCache,n.model.main.id)+` dialect ${n.tools.dialect}
438
438
  workspace ${P===""?"(none)":P}
439
439
  `+(b===void 0?"":` knowledge ${b.entries.length} entries, maxActive=${b.maxActive}, budget=${b.budget}
440
440
  `)+` memory ${n.memory===void 0?"none — nothing is retrieved across sessions":`${n.memory.retriever} at ${n.memory.dir}, maxActive=${n.memory.maxActive}, threshold=${n.memory.threshold}, budget=${n.memory.budget}, history=${n.memory.includeHistory}`}
@@ -443,12 +443,12 @@ ${i===""?"":`${y(`a copy of the old file is at ${tt(`${r}.${A.slug}-backup`,s.ho
443
443
  limits maxSteps=${n.limits.maxSteps} turnTimeoutMs=${n.limits.turnTimeoutMs}
444
444
  `+g.map((v)=>` warning ${v.message}
445
445
  `).join("")),o}catch(s){if(e.json===!0&&f(s))return process.stdout.write(`${JSON.stringify({ok:!1,error:s.toDetail(),details:s.details},null,2)}
446
- `),d;throw s}}function Xd(e,s){if(e!=="none")return"";return/(^|\/)claude-/i.test(s)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
446
+ `),u;throw s}}function Wd(e,s){if(e!=="none")return"";return/(^|\/)claude-/i.test(s)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
447
447
  `+` caching at all, so no request field reaches it. Caching lives on the native
448
448
  Messages API, which this runtime does not speak.
449
449
  `:` promptCache none — this runtime sends no cache directives. Many endpoints cache
450
- `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function Mo(e){try{let s=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:r}=s,i=ye(r.model.main.id,r.model.main.capabilities),{workspace:n,warnings:a}=It(s,i.promptStyle),l=[...a,...di(n.files.map((w)=>({name:w.name,authored:w.authored,tier:w.tier,field:w.field})))],c=zA(n,r.context.rules);if(c!==void 0)l.push(c.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:l.length===0,path:s.path,promptStyle:i.promptStyle,files:n.files.map((w)=>({name:w.name,tier:w.tier,editable:w.editable,tokens:w.tokens,budget:w.budget})),tokens:n.tokens,findings:l},null,2)}
451
- `),e.strict===!0&&l.length>0?d:o;let p=i.promptStyle;process.stdout.write(`${s.path}
450
+ `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function Oo(e){try{let s=q(e.manifestPath,{env:_([e.manifestPath])}),{manifest:r}=s,i=ye(r.model.main.id,r.model.main.capabilities),{workspace:n,warnings:a}=IA(s,i.promptStyle),l=[...a,...ui(n.files.map((w)=>({name:w.name,authored:w.authored,tier:w.tier,field:w.field})))],c=zt(n,r.context.rules);if(c!==void 0)l.push(c.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:l.length===0,path:s.path,promptStyle:i.promptStyle,files:n.files.map((w)=>({name:w.name,tier:w.tier,editable:w.editable,tokens:w.tokens,budget:w.budget})),tokens:n.tokens,findings:l},null,2)}
451
+ `),e.strict===!0&&l.length>0?u:o;let p=i.promptStyle;process.stdout.write(`${s.path}
452
452
  rendering delimiters=${p.delimiters} intensity=${p.intensity} examplesIn=${p.examplesIn}
453
453
  total ${n.tokens.total} tokens (static ${n.tokens.static}, volatile ${n.tokens.volatile}, reminder ${n.tokens.reminder})
454
454
  `);for(let w of n.files)process.stdout.write(` ${w.name.padEnd(14)} ${w.tier.padEnd(9)} ${String(w.tokens).padStart(5)}/${w.budget} tokens, editable=${w.editable}
@@ -459,15 +459,15 @@ no findings
459
459
  `),process.stdout.write(` hint: ${w.hint}
460
460
  `);return process.stdout.write(`
461
461
  ${l.length} finding(s)
462
- `),e.strict===!0?d:o}catch(s){if(e.json===!0&&f(s))return process.stdout.write(`${JSON.stringify({ok:!1,error:s.toDetail(),details:s.details},null,2)}
463
- `),d;throw s}}function zd(e){let s=ms(e);if(s!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${s} is not installed.
464
- 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.
465
- `),d;if(f(e))process.stderr.write(`${e.format()}
462
+ `),e.strict===!0?u:o}catch(s){if(e.json===!0&&f(s))return process.stdout.write(`${JSON.stringify({ok:!1,error:s.toDetail(),details:s.details},null,2)}
463
+ `),u;throw s}}function Gd(e){let s=Zt(e);if(s!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${s} is not installed.
464
+ hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${t.slug}), or pass --plain where the command has it.
465
+ `),u;if(f(e))process.stderr.write(`${e.format()}
466
466
  `);else if(e instanceof Error){if(process.stderr.write(`${e.message}
467
- `),WA().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
467
+ `),Wt().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
468
468
  `)}else process.stderr.write(`${String(e)}
469
- `);return d}async function Yd(e){let s=$i(e);switch(s.kind){case"version":return process.stdout.write(`${J}
470
- `),o;case"help":return process.stdout.write(Mn(s.command)),o;case"usage":return process.stdout.write(Mn()),d;case"command":break}let{command:r,positionals:i,flags:n}=s.parsed,a=i[0],l=()=>Fe(a),c=r.flags.some((m)=>m.name==="store")?n.str("store"):void 0,p=await er({needsServer:r.needsServer,disabled:n.bool("no-bootstrap"),install:()=>Ar(),...c===void 0?{}:{store:c}}),w=wt(p);if(w!==void 0)process.stderr.write(w);switch(r.name){case"init":{let m=n.str("dir"),h=n.str("user"),g=n.str("name"),b=n.str("purpose"),P=n.str("preset"),R=n.str("model"),S=n.str("base-url"),L=n.str("api-key-env"),D=n.str("system"),v=n.str("web"),x=n.str("web-backend"),I=n.str("composio"),N=n.str("telegram"),K=n.str("telegram-allow"),O=n.str("whatsapp"),W=n.str("whatsapp-number"),ae=n.str("server"),ee=n.str("schedules"),B=n.str("skills"),Ee=n.str("daemon");return await Xt({...m===void 0?{}:{dir:m},...h===void 0?{}:{user:h},...g===void 0?{}:{name:g},...b===void 0?{}:{purpose:b},...P===void 0?{}:{preset:P},...R===void 0?{}:{model:R},...S===void 0?{}:{baseUrl:S},...L===void 0?{}:{apiKeyEnv:L},...D===void 0?{}:{system:D},...v===void 0?{}:{web:v},...x===void 0?{}:{webBackend:x},...I===void 0?{}:{composio:I},...N===void 0?{}:{telegram:N},...ee===void 0?{}:{schedules:ee},...K===void 0?{}:{telegramAllow:K},...O===void 0?{}:{whatsapp:O},...W===void 0?{}:{whatsappNumber:W},...ae===void 0?{}:{server:ae},...B===void 0?{}:{skills:B},...Ee===void 0?{}:{daemon:Ee},yes:n.bool("yes"),plain:n.bool("plain"),measureWindow:n.bool("measure-window"),installServer:Ar})}case"run":{let m=n.str("session"),h=n.str("input"),g=n.str("store");return await ot({...i[0]===void 0?{}:{manifestPath:l()},...m===void 0?{}:{sessionKey:m},continueSession:n.bool("continue"),...h===void 0?{}:{once:h},...g===void 0?{}:{store:g},ephemeral:n.bool("ephemeral"),quiet:n.bool("quiet"),showReasoning:n.bool("show-reasoning"),noReasoning:n.bool("no-reasoning"),...n.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:n.bool("plain")})}case"schedules":{let m=n.str("store"),h=n.str("id"),g=n.str("enable"),b=n.str("disable");return await no({manifestPath:l(),...m===void 0?{}:{store:m},...h===void 0?{}:{id:h},...g===void 0?{}:{enable:g},...b===void 0?{}:{disable:b},recipients:n.bool("recipients"),json:n.bool("json")})}case"sessions":{let m=n.str("session"),h=n.str("store"),g=n.num("limit");return await Po({manifestPath:l(),...m===void 0?{}:{sessionKey:m},...h===void 0?{}:{store:h},...g===void 0?{}:{limit:g},json:n.bool("json"),clear:n.bool("clear"),turns:n.bool("turns")})}case"memory":{let m=n.num("limit"),h=n.str("store");return await bs({action:a,manifestPath:Fe(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...m===void 0?{}:{limit:m},...h===void 0?{}:{store:h},all:n.bool("all"),json:n.bool("json")})}case"config":{let{configCommand:m,readAction:h}=await import("./config-z2cd0c5f.js"),g=h(a,i[1]);return await m({action:g.action,...g.ref===void 0?{}:{ref:g.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...n.str("channel")===void 0?{}:{channel:n.str("channel")},remove:n.bool("remove"),yes:n.bool("yes"),...n.str("store")===void 0?{}:{store:n.str("store")}})}case"validate":return await Ko({manifestPath:l(),json:n.bool("json")});case"workspace":return Mo({manifestPath:l(),json:n.bool("json"),strict:n.bool("strict")});case"soul":{let m=n.str("out");return xo({action:a,file:i[1],...m===void 0?{}:{out:m}})}case"skills":{if(i.length===0)return await ss({plain:n.bool("plain"),json:n.bool("json")});let m=i[2];return KA({action:a,manifestPath:Fe(i[1]??""),...m===void 0?{}:{name:m},json:n.bool("json"),strict:n.bool("strict")})}case"sources":{let m=n.str("path"),h=n.str("ref");return await To({action:a,rest:i.slice(1),...m===void 0?{}:{path:m},...h===void 0?{}:{ref:h},json:n.bool("json")})}case"channels":{let m=As("channels",a),h=m.ref??i[1]??"",{channelsCommand:g}=await import("./channels-gf31stv7.js");return await g({...m.action===void 0?{}:{action:m.action},manifestPath:Fe(h),...i[2]===void 0?{}:{channelId:i[2]},json:n.bool("json"),installServer:Ar})}case"plugins":{let m=n.str("ref"),h=n.str("name");return await Xs({action:a,manifestPath:Fe(i[1]??""),rest:i.slice(2),...m===void 0?{}:{ref:m},...h===void 0?{}:{name:h},json:n.bool("json")})}case"agents":{let m=n.str("store");return await $t({manifestPaths:i.map((h)=>Fe(h)),...m===void 0?{}:{store:m},json:n.bool("json")})}case"restart":{let m=n.str("store");return await Cr({...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{store:m},json:n.bool("json")})}case"status":{let m=n.str("store");return await Oo({...m===void 0?{}:{store:m},json:n.bool("json")})}case"logs":{let m=n.num("lines"),h=n.str("store");return await FA({action:"logs",...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),...h===void 0?{}:{store:h},json:n.bool("json")})}case"serve":{let m=n.num("port"),h=n.str("host"),g=n.str("store");return await Eo({manifestPaths:i.map((b)=>Fe(b)),...m===void 0?{}:{port:m},...h===void 0?{}:{host:h},...g===void 0?{}:{store:g},claim:n.bool("claim"),json:n.bool("json")})}case"keys":return await ds({noEnhancedKeys:n.bool("no-enhanced-keys")});case"terminal-setup":return await No({dryRun:n.bool("dry-run"),yes:n.bool("yes"),json:n.bool("json"),confirm:bt});case"remove":return await Rr({...a===void 0?{}:{ref:a},dryRun:n.bool("dry-run"),filesOnly:n.bool("files-only"),prune:n.bool("prune"),all:n.bool("all"),yes:n.bool("yes"),json:n.bool("json"),...n.str("store")===void 0?{}:{store:n.str("store")},confirm:Vi});case"stop":{let m=n.str("reason");return await en({...a===void 0?{}:{manifestPath:l()},dryRun:n.bool("dry-run"),...m===void 0?{}:{reason:m},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"start":return await Ao({manifestPath:l(),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")});case"web":{let{webCommand:m}=await import("./web-stkkwyka.js");return await m({action:a,...i[1]===void 0?{}:{manifestPath:Fe(i[1])},noOpen:n.bool("no-open"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"credential":{let{credentialCommand:m}=await import("./credential-h0wmsjsw.js");return await m({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...n.str("label")===void 0?{}:{label:n.str("label")},...n.str("agents")===void 0?{}:{agents:n.str("agents")},...n.str("sessions")===void 0?{}:{sessions:n.str("sessions")},...n.str("can")===void 0?{}:{can:n.str("can")},...n.str("expires")===void 0?{}:{expires:n.str("expires")},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"daemon":{let m=n.num("lines");return await FA({action:a,...i[1]===void 0?{}:{manifestPath:Fe(i[1])},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),dryRun:n.bool("dry-run"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"model":{let m=n.num("price");return await js({manifestPath:Fe(i[1]),window:n.bool("window"),...m===void 0?{}:{price:m},write:n.bool("write"),yes:n.bool("yes"),json:n.bool("json")})}case"tools":return await jo({manifestPath:l(),warm:n.bool("warm"),json:n.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}hs();Is();fs();await Yd(process.argv.slice(2)).catch(zd).then((e)=>gr(e));
469
+ `);return u}async function qd(e){let s=$i(e);switch(s.kind){case"version":return process.stdout.write(`${J}
470
+ `),o;case"help":return process.stdout.write(Ln(s.command)),o;case"usage":return process.stdout.write(Ln()),u;case"command":break}let{command:r,positionals:i,flags:n}=s.parsed,a=i[0],l=()=>Fe(a),c=r.flags.some((m)=>m.name==="store")?n.str("store"):void 0,p=await er({needsServer:r.needsServer,disabled:n.bool("no-bootstrap"),install:()=>tr(),...c===void 0?{}:{store:c}}),w=wA(p);if(w!==void 0)process.stderr.write(w);switch(r.name){case"init":{let m=n.str("dir"),h=n.str("user"),g=n.str("name"),b=n.str("purpose"),P=n.str("preset"),R=n.str("model"),S=n.str("base-url"),L=n.str("api-key-env"),D=n.str("system"),v=n.str("web"),x=n.str("web-backend"),I=n.str("composio"),N=n.str("telegram"),K=n.str("telegram-allow"),O=n.str("whatsapp"),W=n.str("whatsapp-number"),le=n.str("server"),ee=n.str("schedules"),B=n.str("skills"),Ee=n.str("daemon");return await _t({...m===void 0?{}:{dir:m},...h===void 0?{}:{user:h},...g===void 0?{}:{name:g},...b===void 0?{}:{purpose:b},...P===void 0?{}:{preset:P},...R===void 0?{}:{model:R},...S===void 0?{}:{baseUrl:S},...L===void 0?{}:{apiKeyEnv:L},...D===void 0?{}:{system:D},...v===void 0?{}:{web:v},...x===void 0?{}:{webBackend:x},...I===void 0?{}:{composio:I},...N===void 0?{}:{telegram:N},...ee===void 0?{}:{schedules:ee},...K===void 0?{}:{telegramAllow:K},...O===void 0?{}:{whatsapp:O},...W===void 0?{}:{whatsappNumber:W},...le===void 0?{}:{server:le},...B===void 0?{}:{skills:B},...Ee===void 0?{}:{daemon:Ee},yes:n.bool("yes"),plain:n.bool("plain"),measureWindow:n.bool("measure-window"),installServer:tr})}case"run":{let m=n.str("session"),h=n.str("input"),g=n.str("store");return await tt({...i[0]===void 0?{}:{manifestPath:l()},...m===void 0?{}:{sessionKey:m},continueSession:n.bool("continue"),...h===void 0?{}:{once:h},...g===void 0?{}:{store:g},ephemeral:n.bool("ephemeral"),quiet:n.bool("quiet"),showReasoning:n.bool("show-reasoning"),noReasoning:n.bool("no-reasoning"),...n.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:n.bool("plain")})}case"schedules":{let m=n.str("store"),h=n.str("id"),g=n.str("enable"),b=n.str("disable");return await Jr({manifestPath:l(),...m===void 0?{}:{store:m},...h===void 0?{}:{id:h},...g===void 0?{}:{enable:g},...b===void 0?{}:{disable:b},recipients:n.bool("recipients"),json:n.bool("json")})}case"sessions":{let m=n.str("session"),h=n.str("store"),g=n.num("limit");return await co({manifestPath:l(),...m===void 0?{}:{sessionKey:m},...h===void 0?{}:{store:h},...g===void 0?{}:{limit:g},json:n.bool("json"),clear:n.bool("clear"),turns:n.bool("turns")})}case"memory":{let m=n.num("limit"),h=n.str("store");return await ms({action:a,manifestPath:Fe(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...m===void 0?{}:{limit:m},...h===void 0?{}:{store:h},all:n.bool("all"),json:n.bool("json")})}case"config":{let{configCommand:m,readAction:h}=await import("./config-g0ybmm4t.js"),g=h(a,i[1]);return await m({action:g.action,...g.ref===void 0?{}:{ref:g.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...n.str("channel")===void 0?{}:{channel:n.str("channel")},remove:n.bool("remove"),yes:n.bool("yes"),...n.str("store")===void 0?{}:{store:n.str("store")}})}case"validate":return await To({manifestPath:l(),json:n.bool("json")});case"workspace":return Oo({manifestPath:l(),json:n.bool("json"),strict:n.bool("strict")});case"soul":{let m=n.str("out");return uo({action:a,file:i[1],...m===void 0?{}:{out:m}})}case"skills":{if(i.length===0)return await ss({plain:n.bool("plain"),json:n.bool("json")});let m=i[2];return Kt({action:a,manifestPath:Fe(i[1]??""),...m===void 0?{}:{name:m},json:n.bool("json"),strict:n.bool("strict")})}case"sources":{let m=n.str("path"),h=n.str("ref");return await go({action:a,rest:i.slice(1),...m===void 0?{}:{path:m},...h===void 0?{}:{ref:h},json:n.bool("json")})}case"channels":{let m=ts("channels",a),h=m.ref??i[1]??"",{channelsCommand:g}=await import("./channels-yhdvxxrb.js");return await g({...m.action===void 0?{}:{action:m.action},manifestPath:Fe(h),...i[2]===void 0?{}:{channelId:i[2]},json:n.bool("json"),installServer:tr})}case"plugins":{let m=n.str("ref"),h=n.str("name");return await Ds({action:a,manifestPath:Fe(i[1]??""),rest:i.slice(2),...m===void 0?{}:{ref:m},...h===void 0?{}:{name:h},json:n.bool("json")})}case"agents":{let m=n.str("store");return await yt({manifestPaths:i.map((h)=>Fe(h)),...m===void 0?{}:{store:m},json:n.bool("json")})}case"restart":{let m=n.str("store");return await Rr({...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{store:m},json:n.bool("json")})}case"status":{let m=n.str("store");return await vo({...m===void 0?{}:{store:m},json:n.bool("json")})}case"logs":{let m=n.num("lines"),h=n.str("store");return await Ft({action:"logs",...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),...h===void 0?{}:{store:h},json:n.bool("json")})}case"serve":{let m=n.num("port"),h=n.str("host"),g=n.str("store");return await ao({manifestPaths:i.map((b)=>Fe(b)),...m===void 0?{}:{port:m},...h===void 0?{}:{host:h},...g===void 0?{}:{store:g},claim:n.bool("claim"),json:n.bool("json")})}case"keys":return await Xt({noEnhancedKeys:n.bool("no-enhanced-keys")});case"terminal-setup":return await Eo({dryRun:n.bool("dry-run"),yes:n.bool("yes"),json:n.bool("json"),confirm:bA});case"remove":return await pr({...a===void 0?{}:{ref:a},dryRun:n.bool("dry-run"),filesOnly:n.bool("files-only"),prune:n.bool("prune"),all:n.bool("all"),yes:n.bool("yes"),json:n.bool("json"),...n.str("store")===void 0?{}:{store:n.str("store")},confirm:Vi});case"stop":{let m=n.str("reason");return await en({...a===void 0?{}:{manifestPath:l()},dryRun:n.bool("dry-run"),...m===void 0?{}:{reason:m},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"start":return await yo({manifestPath:l(),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")});case"web":{let{webCommand:m}=await import("./web-f6869dy2.js");return await m({action:a,...i[1]===void 0?{}:{manifestPath:Fe(i[1])},noOpen:n.bool("no-open"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"credential":{let{credentialCommand:m}=await import("./credential-pkme1sfe.js");return await m({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...n.str("label")===void 0?{}:{label:n.str("label")},...n.str("agents")===void 0?{}:{agents:n.str("agents")},...n.str("sessions")===void 0?{}:{sessions:n.str("sessions")},...n.str("can")===void 0?{}:{can:n.str("can")},...n.str("expires")===void 0?{}:{expires:n.str("expires")},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"daemon":{let m=n.num("lines");return await Ft({action:a,...i[1]===void 0?{}:{manifestPath:Fe(i[1])},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),dryRun:n.bool("dry-run"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"model":{let m=n.num("price");return await xs({manifestPath:Fe(i[1]),window:n.bool("window"),...m===void 0?{}:{price:m},write:n.bool("write"),yes:n.bool("yes"),json:n.bool("json")})}case"tools":return await Po({manifestPath:l(),warm:n.bool("warm"),json:n.bool("json")});default:throw new A({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}ds();Is();es();await qd(process.argv.slice(2)).catch(Gd).then((e)=>gr(e));
471
471
 
472
- //# debugId=E769924D486F7CBA64756E2164756E21
472
+ //# debugId=EF8E110B4258574D64756E2164756E21
473
473
  //# sourceMappingURL=index.js.map