dispach 0.2.2 → 0.2.4

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 (225) hide show
  1. package/README.md +34 -27
  2. package/dist/APEv2Parser-x13n424p.js +5 -0
  3. package/dist/{FlacParser-7t7da7qy.js.map → APEv2Parser-x13n424p.js.map} +1 -1
  4. package/dist/{AiffParser-y21k3fak.js → AiffParser-ns1y9f0g.js} +3 -3
  5. package/dist/{AiffParser-y21k3fak.js.map → AiffParser-ns1y9f0g.js.map} +1 -1
  6. package/dist/App-wkpkwgjt.js +11 -0
  7. package/dist/{App-4w3qkcs4.js.map → App-wkpkwgjt.js.map} +3 -3
  8. package/dist/AsfParser-bae2a1yf.js +5 -0
  9. package/dist/{AsfParser-wd98k2h4.js.map → AsfParser-bae2a1yf.js.map} +1 -1
  10. package/dist/ConfigEditor-hy9jtas3.js +6 -0
  11. package/dist/{ConfigEditor-vk7vxaa6.js.map → ConfigEditor-hy9jtas3.js.map} +1 -1
  12. package/dist/DsdiffParser-s0zvxnfa.js +5 -0
  13. package/dist/{DsdiffParser-cbfaj500.js.map → DsdiffParser-s0zvxnfa.js.map} +1 -1
  14. package/dist/{DsfParser-tybrja4x.js → DsfParser-90mvzt4v.js} +3 -3
  15. package/dist/{DsfParser-tybrja4x.js.map → DsfParser-90mvzt4v.js.map} +1 -1
  16. package/dist/FlacParser-8xprykrh.js +5 -0
  17. package/dist/{APEv2Parser-etzjd528.js.map → FlacParser-8xprykrh.js.map} +1 -1
  18. package/dist/{KeyProbe-5anphmb7.js → KeyProbe-fk5krzks.js} +3 -3
  19. package/dist/{KeyProbe-5anphmb7.js.map → KeyProbe-fk5krzks.js.map} +1 -1
  20. package/dist/MP4Parser-nmvbkq21.js +5 -0
  21. package/dist/{MP4Parser-gc94h1n9.js.map → MP4Parser-nmvbkq21.js.map} +2 -2
  22. package/dist/{MatroskaParser-cy2k4fac.js → MatroskaParser-tsmz2qfq.js} +3 -3
  23. package/dist/{MatroskaParser-cy2k4fac.js.map → MatroskaParser-tsmz2qfq.js.map} +1 -1
  24. package/dist/{MpegParser-c460fwf0.js → MpegParser-y5fjpaz9.js} +3 -3
  25. package/dist/{MpegParser-c460fwf0.js.map → MpegParser-y5fjpaz9.js.map} +1 -1
  26. package/dist/MusepackParser-544q0byg.js +5 -0
  27. package/dist/{MusepackParser-8mq2eabg.js.map → MusepackParser-544q0byg.js.map} +2 -2
  28. package/dist/OggParser-v77rbjnt.js +5 -0
  29. package/dist/{OggParser-7dnc6apg.js.map → OggParser-v77rbjnt.js.map} +1 -1
  30. package/dist/Picker-32m79nmp.js +5 -0
  31. package/dist/{Picker-j7txnm7w.js.map → Picker-32m79nmp.js.map} +1 -1
  32. package/dist/SessionPicker-9p06npt5.js +5 -0
  33. package/dist/{SessionPicker-hpv2ncsb.js.map → SessionPicker-9p06npt5.js.map} +1 -1
  34. package/dist/SkillBrowser-ezdx3xsh.js +5 -0
  35. package/dist/{SkillBrowser-qc542n71.js.map → SkillBrowser-ezdx3xsh.js.map} +1 -1
  36. package/dist/WavPackParser-k623m0hk.js +5 -0
  37. package/dist/{WavPackParser-kt7cds9c.js.map → WavPackParser-k623m0hk.js.map} +1 -1
  38. package/dist/WaveParser-nj4p1vx8.js +5 -0
  39. package/dist/{WaveParser-g47ja0vy.js.map → WaveParser-nj4p1vx8.js.map} +1 -1
  40. package/dist/WizardApp-p350qspw.js +5 -0
  41. package/dist/{WizardApp-q4p979d1.js.map → WizardApp-p350qspw.js.map} +1 -1
  42. package/dist/channels-a9zx9yba.js +31 -0
  43. package/dist/{channels-4t89qpdt.js.map → channels-a9zx9yba.js.map} +1 -1
  44. package/dist/client.d.ts +43 -0
  45. package/dist/client.js +9 -9
  46. package/dist/client.js.map +5 -5
  47. package/dist/components/App.d.ts.map +1 -1
  48. package/dist/config-3mz4zwsf.js +24 -0
  49. package/dist/{config-35r6n1gh.js.map → config-3mz4zwsf.js.map} +2 -2
  50. package/dist/credential-ja7zmd4c.js +19 -0
  51. package/dist/{credential-dpdgg4j6.js.map → credential-ja7zmd4c.js.map} +1 -1
  52. package/dist/index-039ew35r.js +6 -0
  53. package/dist/index-039ew35r.js.map +10 -0
  54. package/dist/index-0dvs3a06.js +6 -0
  55. package/dist/{index-jc4kmfwa.js.map → index-0dvs3a06.js.map} +1 -1
  56. package/dist/{index-pszmnhgq.js → index-1cagdzqe.js} +9 -9
  57. package/dist/{index-pszmnhgq.js.map → index-1cagdzqe.js.map} +1 -1
  58. package/dist/index-2fw9e5gg.js +6 -0
  59. package/dist/{index-0444sh6x.js.map → index-2fw9e5gg.js.map} +1 -1
  60. package/dist/{index-a2eh8dnk.js → index-2td5h856.js} +12 -12
  61. package/dist/{index-a2eh8dnk.js.map → index-2td5h856.js.map} +1 -1
  62. package/dist/{index-m6fqx0ch.js → index-446exxcb.js} +7 -7
  63. package/dist/{index-m6fqx0ch.js.map → index-446exxcb.js.map} +1 -1
  64. package/dist/{index-snz49ndn.js → index-4fajxhdv.js} +4 -4
  65. package/dist/{index-snz49ndn.js.map → index-4fajxhdv.js.map} +1 -1
  66. package/dist/index-4j65jp20.js +9 -0
  67. package/dist/{index-38gs9anh.js.map → index-4j65jp20.js.map} +1 -1
  68. package/dist/index-5gn74n56.js +10 -0
  69. package/dist/{index-ew997be5.js.map → index-5gn74n56.js.map} +2 -2
  70. package/dist/index-5zpfz4kb.js +9 -0
  71. package/dist/{index-8h6kewy1.js.map → index-5zpfz4kb.js.map} +1 -1
  72. package/dist/index-60h4knj6.js +126 -0
  73. package/dist/{index-zce9gy22.js.map → index-60h4knj6.js.map} +2 -2
  74. package/dist/index-635wcsh1.js +5 -0
  75. package/dist/{index-2bsardvh.js.map → index-635wcsh1.js.map} +1 -1
  76. package/dist/index-67sfck4d.js +110 -0
  77. package/dist/index-67sfck4d.js.map +13 -0
  78. package/dist/index-7p8d1gf0.js +63 -0
  79. package/dist/{index-ytxbw8py.js.map → index-7p8d1gf0.js.map} +1 -1
  80. package/dist/index-7zgjkbb0.js +5 -0
  81. package/dist/{index-qgsdgbk8.js.map → index-7zgjkbb0.js.map} +1 -1
  82. package/dist/{index-zw6wyas6.js → index-86rb86nr.js} +4 -4
  83. package/dist/{index-zw6wyas6.js.map → index-86rb86nr.js.map} +1 -1
  84. package/dist/{index-fbsrhcga.js → index-8jejze0z.js} +4 -4
  85. package/dist/{index-fbsrhcga.js.map → index-8jejze0z.js.map} +1 -1
  86. package/dist/index-8k8y7edx.js +7 -0
  87. package/dist/{index-3826kf9t.js.map → index-8k8y7edx.js.map} +1 -1
  88. package/dist/index-8mkatm20.js +6 -0
  89. package/dist/{index-42e29zs4.js.map → index-8mkatm20.js.map} +1 -1
  90. package/dist/{index-3vzf253k.js → index-9k6qa50r.js} +7 -7
  91. package/dist/{index-3vzf253k.js.map → index-9k6qa50r.js.map} +1 -1
  92. package/dist/{index-yw3fby4n.js → index-a1axc952.js} +4 -4
  93. package/dist/{index-yw3fby4n.js.map → index-a1axc952.js.map} +1 -1
  94. package/dist/index-ayhdn87b.js +6 -0
  95. package/dist/{index-dzy19wtf.js.map → index-ayhdn87b.js.map} +1 -1
  96. package/dist/index-b8bfzbfe.js +6 -0
  97. package/dist/{index-7mn8ack9.js.map → index-b8bfzbfe.js.map} +2 -2
  98. package/dist/index-brh25jhq.js +6 -0
  99. package/dist/{index-fa9wvpyw.js.map → index-brh25jhq.js.map} +2 -2
  100. package/dist/index-c6qrcweh.js +6 -0
  101. package/dist/{index-nxhqf597.js.map → index-c6qrcweh.js.map} +1 -1
  102. package/dist/index-cb45233h.js +6 -0
  103. package/dist/{index-nvc24414.js.map → index-cb45233h.js.map} +1 -1
  104. package/dist/{index-51x0n5z0.js → index-dcy14zdn.js} +5 -5
  105. package/dist/{index-51x0n5z0.js.map → index-dcy14zdn.js.map} +1 -1
  106. package/dist/index-f6r3h2yh.js +8 -0
  107. package/dist/{index-twn9bfm2.js.map → index-f6r3h2yh.js.map} +1 -1
  108. package/dist/index-gezqawvw.js +11 -0
  109. package/dist/{index-fcsg95m5.js.map → index-gezqawvw.js.map} +1 -1
  110. package/dist/index-h787rq0h.js +12 -0
  111. package/dist/{index-wc4entme.js.map → index-h787rq0h.js.map} +3 -3
  112. package/dist/index-hd5nkwd7.js +74 -0
  113. package/dist/index-hd5nkwd7.js.map +13 -0
  114. package/dist/index-k6wq0j4q.js +6 -0
  115. package/dist/{index-gq1npngp.js.map → index-k6wq0j4q.js.map} +1 -1
  116. package/dist/index-kz01jz58.js +6 -0
  117. package/dist/{index-323jvr1g.js.map → index-kz01jz58.js.map} +1 -1
  118. package/dist/{index-kjqksgch.js → index-mgef1n4e.js} +10 -10
  119. package/dist/{index-kjqksgch.js.map → index-mgef1n4e.js.map} +1 -1
  120. package/dist/{index-haypwvzd.js → index-n197qdw1.js} +188 -188
  121. package/dist/{index-haypwvzd.js.map → index-n197qdw1.js.map} +3 -3
  122. package/dist/index-nndwx2wp.js +153 -0
  123. package/dist/{index-z157at3s.js.map → index-nndwx2wp.js.map} +2 -2
  124. package/dist/index-pz92ksp8.js +5 -0
  125. package/dist/{index-3c5jt6by.js.map → index-pz92ksp8.js.map} +1 -1
  126. package/dist/index-qj4adnfe.js +14 -0
  127. package/dist/{index-eqqd4k4f.js.map → index-qj4adnfe.js.map} +2 -2
  128. package/dist/index-r83jpct7.js +6 -0
  129. package/dist/{index-gbkma7ds.js.map → index-r83jpct7.js.map} +2 -2
  130. package/dist/{index-2zjh5zd5.js → index-rqfwd7j5.js} +4 -4
  131. package/dist/{index-2zjh5zd5.js.map → index-rqfwd7j5.js.map} +1 -1
  132. package/dist/index-s0f0s6n5.js +6 -0
  133. package/dist/{index-p1zy871m.js.map → index-s0f0s6n5.js.map} +1 -1
  134. package/dist/index-s0t15ndj.js +6 -0
  135. package/dist/{index-8edck2pr.js.map → index-s0t15ndj.js.map} +1 -1
  136. package/dist/index-tc054tcb.js +6 -0
  137. package/dist/{index-8tmv33mr.js.map → index-tc054tcb.js.map} +1 -1
  138. package/dist/{index-095hrkyr.js → index-ts8a1sdn.js} +6 -6
  139. package/dist/{index-095hrkyr.js.map → index-ts8a1sdn.js.map} +1 -1
  140. package/dist/index-tv52jhac.js +1252 -0
  141. package/dist/{index-qg9bn980.js.map → index-tv52jhac.js.map} +15 -14
  142. package/dist/index-x9nn57kk.js +6 -0
  143. package/dist/{index-1x8mzvz7.js.map → index-x9nn57kk.js.map} +1 -1
  144. package/dist/{index-ynsvkqgb.js → index-xyh98x7p.js} +4 -4
  145. package/dist/{index-ynsvkqgb.js.map → index-xyh98x7p.js.map} +1 -1
  146. package/dist/{index-ma6p7bt4.js → index-yy4v9kca.js} +4 -4
  147. package/dist/{index-ma6p7bt4.js.map → index-yy4v9kca.js.map} +1 -1
  148. package/dist/{index-bqdkm3de.js → index-yz0fcxky.js} +4 -4
  149. package/dist/{index-bqdkm3de.js.map → index-yz0fcxky.js.map} +1 -1
  150. package/dist/{index-p6ya59m6.js → index-z4adxmzm.js} +5 -5
  151. package/dist/{index-p6ya59m6.js.map → index-z4adxmzm.js.map} +1 -1
  152. package/dist/{index-4fj1k64j.js → index-zzpgsbn3.js} +4 -4
  153. package/dist/{index-4fj1k64j.js.map → index-zzpgsbn3.js.map} +1 -1
  154. package/dist/index.js +343 -343
  155. package/dist/index.js.map +7 -7
  156. package/dist/lib/source.d.ts +8 -0
  157. package/dist/lib/source.d.ts.map +1 -1
  158. package/dist/lib/types.d.ts +8 -2
  159. package/dist/lib/types.d.ts.map +1 -1
  160. package/dist/run.d.ts.map +1 -1
  161. package/dist/transcript.d.ts.map +1 -1
  162. package/dist/web-7mdrcb8a.js +14 -0
  163. package/dist/{web-zph4h3p9.js.map → web-7mdrcb8a.js.map} +1 -1
  164. package/dist/wire.d.ts +19 -0
  165. package/dist/wire.js +5 -5
  166. package/dist/wire.js.map +4 -4
  167. package/dist/wrapper-4hdmdwft.js +5 -0
  168. package/dist/{wrapper-f662ny3r.js.map → wrapper-4hdmdwft.js.map} +1 -1
  169. package/package.json +1 -1
  170. package/dist/APEv2Parser-etzjd528.js +0 -5
  171. package/dist/App-4w3qkcs4.js +0 -11
  172. package/dist/AsfParser-wd98k2h4.js +0 -5
  173. package/dist/ConfigEditor-vk7vxaa6.js +0 -6
  174. package/dist/DsdiffParser-cbfaj500.js +0 -5
  175. package/dist/FlacParser-7t7da7qy.js +0 -5
  176. package/dist/MP4Parser-gc94h1n9.js +0 -5
  177. package/dist/MusepackParser-8mq2eabg.js +0 -5
  178. package/dist/OggParser-7dnc6apg.js +0 -5
  179. package/dist/Picker-j7txnm7w.js +0 -5
  180. package/dist/SessionPicker-hpv2ncsb.js +0 -5
  181. package/dist/SkillBrowser-qc542n71.js +0 -5
  182. package/dist/WavPackParser-kt7cds9c.js +0 -5
  183. package/dist/WaveParser-g47ja0vy.js +0 -5
  184. package/dist/WizardApp-q4p979d1.js +0 -5
  185. package/dist/channels-4t89qpdt.js +0 -31
  186. package/dist/config-35r6n1gh.js +0 -24
  187. package/dist/credential-dpdgg4j6.js +0 -19
  188. package/dist/index-0444sh6x.js +0 -6
  189. package/dist/index-1x8mzvz7.js +0 -6
  190. package/dist/index-2bsardvh.js +0 -5
  191. package/dist/index-323jvr1g.js +0 -6
  192. package/dist/index-3826kf9t.js +0 -7
  193. package/dist/index-38gs9anh.js +0 -9
  194. package/dist/index-3c5jt6by.js +0 -5
  195. package/dist/index-42e29zs4.js +0 -6
  196. package/dist/index-664xcamy.js +0 -110
  197. package/dist/index-664xcamy.js.map +0 -13
  198. package/dist/index-7mn8ack9.js +0 -6
  199. package/dist/index-8edck2pr.js +0 -6
  200. package/dist/index-8h6kewy1.js +0 -9
  201. package/dist/index-8tmv33mr.js +0 -6
  202. package/dist/index-9914wh1d.js +0 -6
  203. package/dist/index-9914wh1d.js.map +0 -10
  204. package/dist/index-dzy19wtf.js +0 -6
  205. package/dist/index-eqqd4k4f.js +0 -14
  206. package/dist/index-ew997be5.js +0 -10
  207. package/dist/index-fa9wvpyw.js +0 -6
  208. package/dist/index-fcsg95m5.js +0 -11
  209. package/dist/index-gbkma7ds.js +0 -6
  210. package/dist/index-gq1npngp.js +0 -6
  211. package/dist/index-jc4kmfwa.js +0 -6
  212. package/dist/index-nvc24414.js +0 -6
  213. package/dist/index-nxhqf597.js +0 -6
  214. package/dist/index-p1zy871m.js +0 -6
  215. package/dist/index-qg9bn980.js +0 -1213
  216. package/dist/index-qgsdgbk8.js +0 -5
  217. package/dist/index-r4ax3x4d.js +0 -74
  218. package/dist/index-r4ax3x4d.js.map +0 -13
  219. package/dist/index-twn9bfm2.js +0 -8
  220. package/dist/index-wc4entme.js +0 -12
  221. package/dist/index-ytxbw8py.js +0 -63
  222. package/dist/index-z157at3s.js +0 -153
  223. package/dist/index-zce9gy22.js +0 -126
  224. package/dist/web-zph4h3p9.js +0 -14
  225. package/dist/wrapper-f662ny3r.js +0 -5
package/dist/index.js CHANGED
@@ -1,489 +1,489 @@
1
1
  #!/usr/bin/env node
2
- import{t,j,p,A,Co,ii,Dt,HA,$t,KA,gA,ye,fo,gi,ci,cA,ho,Nt,Bo,Mt,YA,ht,yo,Qo,Le,Ne,F,V,di,Or,jA,J,wo,Do,dA,JA,bo,uA,Z,ne,pi,Ee,yn,Oo,No,fi,hi,Bi,k,Js}from"./index-qg9bn980.js";import{Ir,xe,dr,ur,Jt,Er,Cr,pr}from"./index-r4ax3x4d.js";import{ie,Se,de,ue,le,Be,Jr}from"./index-haypwvzd.js";import{oa}from"./index-dzy19wtf.js";import{mn}from"./index-2zjh5zd5.js";import{_A,kA,to,Fe,ls,Is,sr,jr,ar,Et,gr,vA,Ht,cr,Kt,LA,ds,us}from"./index-zce9gy22.js";import{tr,rn,Ft,xr,Ar,bA,nr,jn,OA,NA,sn,Jn,qn,es,Vn,Wn,zn}from"./index-z157at3s.js";import{Vt,FA,Io,En,uo,UA,Sr,Cn,at,aA,Wt,xA,wr}from"./index-kjqksgch.js";import{Yr,As,an,ns,os,rs,AA}from"./index-664xcamy.js";import{gn,rt,cn,as}from"./index-9914wh1d.js";import{Hn,Kn,nn,Xo,DA,ji,Yn,Vi,Wi}from"./index-wc4entme.js";import"./index-p6ya59m6.js";import{$o}from"./index-bqdkm3de.js";import{Gt,on,$i,Xi}from"./index-gq1npngp.js";import{MA,ts}from"./index-095hrkyr.js";import{Je}from"./index-fcsg95m5.js";import{is}from"./index-ma6p7bt4.js";import{gs,rr,ir,qe,Ve,Ut,cs,xt,me,RA,ut,eo}from"./index-7mn8ack9.js";import{Ue,it}from"./index-ynsvkqgb.js";import{oo,St,Cs,U,fs,We,Ct,lr,hs}from"./index-38gs9anh.js";import{u,v,Q,y,nA,dn,oA,rA}from"./index-3vzf253k.js";import{zt,we,q,Dr,G,ae,br,pn,fn,ri,xs,Zt,Hs,Ae,ve}from"./index-twn9bfm2.js";import{Pe}from"./index-jc4kmfwa.js";import{Xs,ta}from"./index-4fj1k64j.js";import{ko,Ia,Rt,be,Po,Ho,o,d,Sn}from"./index-8tmv33mr.js";async function Tn(e){let n=await xt(e),r=[];for(let i of Ae()){let s=i.id??i.ref,a=await ir(s,e)??{enabled:!0},l=n.find((m)=>m.agentId===s),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 ${dn(c)}`:""}`}})}return r}function In(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((n)=>({label:n.ref,value:n.problem!==void 0?"broken":n.enabled?"on":"off",note:n.problem??n.serving??(n.enabled?`not hosted${n.modelId===void 0?"":` · ${n.modelId}`}`:`switched off${n.reason===void 0?"":` — ${n.reason}`}`)}))}async function vt(e){if(e.manifestPaths.length===0){let a=await Tn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
- `);else process.stdout.write(`${u(In(a))}
4
- `);return o}let n=await Ee.create({agents:[...e.manifestPaths],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k(e.manifestPaths),store:e.store??G(),lease:!1});U(()=>n.stop("cli-exit"));let r=n.list().map((a)=>a.describe()),i=new Map;for(let a of await n.store.leases.all()){if(a.runtimeId===n.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 ${dn(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 s=r.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${u(s)}
6
- `),o}import{basename as en,dirname as Ni,join as fe,resolve as Fi}from"node:path";import{rmSync as ai}from"node:fs";import{isAbsolute as kt,join as li,resolve as Pt}from"node:path";var ui=3;async function Tt(e){if(e.answers.skills!=="find")return;let n=e.answers.skillsSearch?.trim()??"";if(n===""){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=Fe(e.env);if(r.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
- searching ${r.length} skill source(s) for ${JSON.stringify(n)}
8
- `);let i=[],s=[];for(let f of r){if(!Et(f.name,e.env))try{await vA(f,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(h){s.push(`${f.name} — ${p(h)?h.message:String(h)}`);continue}i.push(...Ht(f,e.env))}for(let f of s)process.stdout.write(y(`could not fetch ${f}
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
- ${y("`sources update` reports why; `sources search <words>` when it works",4)}
11
- `);return}let a=mi(n,i);if(a.length===0){process.stdout.write(`${y(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
- ${y("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
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+ui).map((f)=>`${f.source}/${f.skill}`).join(", ")}`,4)}
2
+ import{A,J,h,n,Co,si,bt,KA,eA,YA,cA,Se,ho,ci,li,lA,Bo,Mt,yo,Tt,jA,Bt,Qo,mo,Fe,Re,U,z,ui,Nr,JA,q,Do,bo,uA,qA,Oo,EA,ee,re,fi,Ce,Qn,No,Mo,hi,Bi,yi,v,qs}from"./index-tv52jhac.js";import{dr,Ye,ur,Er,qt,pr,Cr,fr}from"./index-hd5nkwd7.js";import{ae,be,Ee,pe,Ie,Qe,qr}from"./index-n197qdw1.js";import{ra}from"./index-ayhdn87b.js";import{Sn}from"./index-rqfwd7j5.js";import{kA,vA,Ao,He,Is,ds,ar,Jr,gr,ft,cr,LA,Kt,lr,Yt,PA,us,Es}from"./index-60h4knj6.js";import{Ar,sn,Ut,Hr,nr,OA,or,Jn,NA,MA,an,qn,Vn,ts,Wn,zn,Zn}from"./index-nndwx2wp.js";import{zt,UA,uo,pn,Eo,xA,wr,Cn,lt,gA,Zt,HA,Dr}from"./index-mgef1n4e.js";import{jr,ns,gn,os,rs,is,oA}from"./index-67sfck4d.js";import{cn,at,ln,gs}from"./index-039ew35r.js";import{Kn,Yn,on,er,bA,Ji,jn,Wi,zi}from"./index-h787rq0h.js";import"./index-z4adxmzm.js";import{Xo}from"./index-yz0fcxky.js";import{Ft,rn,Xi,es}from"./index-k6wq0j4q.js";import{TA,As}from"./index-ts8a1sdn.js";import{Ve}from"./index-gezqawvw.js";import{ss}from"./index-yy4v9kca.js";import{cs,ir,sr,We,ze,xt,ls,Ht,De,_A,Ct,to}from"./index-b8bfzbfe.js";import{Ke,gt}from"./index-xyh98x7p.js";import{ro,wt,Cs,H,hs,Ze,ht,Ir,Bs}from"./index-4j65jp20.js";import{C,L,w,S,rA,un,iA,sA}from"./index-9k6qa50r.js";import{$t,Oe,W,br,G,ge,Or,fn,hn,ii,Hs,Xt,Ks,oe,Ge}from"./index-f6r3h2yh.js";import{Ue}from"./index-0dvs3a06.js";import{ea,Aa}from"./index-zzpgsbn3.js";import{vo,da,_t,Me,Go,Ko,o,E,wn}from"./index-tc054tcb.js";async function xn(e){let t=await Ht(e),r=[];for(let i of oe()){let s=i.id??i.ref,a=await sr(s,e)??{enabled:!0},d=t.find((u)=>u.agentId===s),l=d===void 0?Number.NaN:Date.now()-Date.parse(d.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...d===void 0?{}:{pid:d.pid,serving:`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(l)?` · up ${un(l)}`:""}`}})}return r}function Tn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((t)=>({label:t.ref,value:t.problem!==void 0?"broken":t.enabled?"on":"off",note:t.problem??t.serving??(t.enabled?`not hosted${t.modelId===void 0?"":` · ${t.modelId}`}`:`switched off${t.reason===void 0?"":` — ${t.reason}`}`)}))}async function kt(e){if(e.manifestPaths.length===0){let a=await xn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
+ `);else process.stdout.write(`${C(Tn(a))}
4
+ `);return o}let t=await Ce.create({agents:[...e.manifestPaths],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v(e.manifestPaths),store:e.store??G(),lease:!1});H(()=>t.stop("cli-exit"));let r=t.list().map((a)=>a.describe()),i=new Map;for(let a of await t.store.leases.all()){if(a.runtimeId===t.runtimeId||!ee(a.pid))continue;let d=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(d)?` · up ${un(d)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:r.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
5
+ `),o;let s=r.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${C(s)}
6
+ `),o}import{basename as en,dirname as Ci,join as le,resolve as Ni}from"node:path";import{rmSync as ai}from"node:fs";import{isAbsolute as Pt,join as di,resolve as Et}from"node:path";var mi=3;async function Rt(e){if(e.answers.skills!=="find")return;let t=e.answers.skillsSearch?.trim()??"";if(t===""){process.stdout.write("\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\n");return}let r=He(e.env);if(r.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
+ searching ${r.length} skill source(s) for ${JSON.stringify(t)}
8
+ `);let i=[],s=[];for(let c of r){if(!ft(c.name,e.env))try{await LA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(f){s.push(`${c.name} — ${h(f)?f.message:String(f)}`);continue}i.push(...Kt(c,e.env))}for(let c of s)process.stdout.write(S(`could not fetch ${c}
9
+ `));if(i.length===0){process.stdout.write(`${S("no source could be read, so no skill was installed — the directory is there and empty")}
10
+ ${S("`sources update` reports why; `sources search <words>` when it works",4)}
11
+ `);return}let a=pi(t,i);if(a.length===0){process.stdout.write(`${S(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
+ ${S("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
13
+ `);return}let d=a[0],l=`${d.source}/${d.skill}`;if(process.stdout.write(`${S(`best of ${i.length}: ${l}`)}
14
+ `),a.length>1)process.stdout.write(`${S(`also matched: ${a.slice(1,1+mi).map((c)=>`${c.source}/${c.skill}`).join(", ")}`,4)}
15
15
  `);if(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=yi(e.manifestPath,e.envOverlay);if(w!==void 0)wi(e.manifestPath,l.skill,e.envOverlay),process.stdout.write(`
17
- ${Q(`${c} was removed again: it does not load on this machine`)}
18
- ${y(w,4)}
19
- ${y("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
- `)}function mi(e,n){let r=new Map,i=n.filter((s)=>s.problem===void 0).map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return JA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}function yi(e,n){try{let r=V(e,{...n===void 0?{}:{env:{...process.env,...n}}}),i=r.manifest.skills;if(i===void 0)return;let s=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities);dA({dir:kt(i.dir)?i.dir:Pt(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:s.promptStyle,agentDir:r.dir,runner:ue()});return}catch(r){return p(r)?r.message:String(r)}}function wi(e,n,r){try{let i=V(e,{...r===void 0?{}:{env:{...process.env,...r}}}),s=i.manifest.skills;if(s===void 0)return;let a=kt(s.dir)?s.dir:Pt(i.dir,s.dir);ai(li(a,n),{recursive:!0,force:!0}),cr(a,n)}catch{}}var On=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function It(e,n,r={}){let i=r.fetch??fetch,s=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},l=async(b)=>{try{let x=await i(b,{headers:a,signal:AbortSignal.timeout(3000)});if(!x.ok)return;let R=await x.json();return R!==null&&typeof R==="object"?R:void 0}catch{return}},w=((await l(`${s}/models/${n}/endpoints`))?.data?.endpoints??[]).map((b)=>On(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 ${s}`};let h=((await l(`${s}/models`))?.data??[]).find((b)=>b.id===n),g=On(h?.context_length)??On(h?.max_model_len);return g===void 0?void 0:{tokens:g,source:`${s}/models`}}import{randomBytes as bi}from"node:crypto";import{mkdirSync as vi,readFileSync as Ot,writeFileSync as Si}from"node:fs";import{join as ki}from"node:path";function Ye(e){return ki(e,".owner")}function Pi(e,n=bi){try{let i=Ot(Ye(e),"utf8").trim();if(i!=="")return i}catch{}let r=`me:${Co(n(6))}`;return vi(e,{recursive:!0}),Si(Ye(e),`${r}
21
- `,{encoding:"utf8",mode:384}),r}function Ei(e){return e.flatMap((n)=>(n.allowFrom??[]).filter((r)=>r!=="*").map((r)=>`${n.type}:${r}`))}async function Ri(e,n){let r=e.conversations,i=(n.now??new Date).toISOString(),s=await r.assignment(n.agentId);if(s!==void 0&&s.participantId!==n.owner)throw new A({code:"owner_assigned_elsewhere",message:`Agent "${n.agentId}" is assigned to ${s.participantId}, not to ${n.owner}.`,hint:`Somebody else is this agent's owner, and taking it over would make it answer the wrong person as its owner. If it really is yours, unassign it first (DELETE /v1/agents/${n.agentId}/assignee) and run \`${t.slug} owner adopt ${n.agentId}\` again.`});if(await r.participant(n.owner)===void 0)await r.upsertParticipant({id:n.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...s?.channelIds??[],...n.channelIds])];return await r.assign({agentId:n.agentId,participantId:n.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function Te(e,n,r){let i=Ot(n,"utf8"),s=String(Ne(i,["id"])??""),a=Ne(i,["channels"]),l=Pi(r),{channelIds:c}=await Ri(e,{agentId:s,owner:l,channelIds:Ei(Array.isArray(a)?a.filter((m)=>typeof m?.type==="string"):[])});return{agentId:s,owner:l,channelIds:c}}import{existsSync as xi,mkdirSync as Ti,writeFileSync as Ii}from"node:fs";import{dirname as Oi,join as An,resolve as _n,sep as Ai}from"node:path";var Qe={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",region:"--region",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function Nn(e,n,r,i){let s=[];for(;;){let a=aA(e,r);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){s.push(a.step),e[a.step]="(missing)";continue}let l=Wt(a.step,a.fallback);if(l.ok)e[a.step]=l.value}if(s.length>0){if(i?.naming==="answers"){let l=s.map((c)=>`answers.${c}`).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${n}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Provide ${l} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=s.map((l)=>Qe[l]).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${n}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Pass ${a} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Fn(e,n){let r=e,i=Vt(r.preset),s=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??FA(r.dirChoice,r.name,n);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??"",...r.region===void 0?{}:{region:r.region},system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:_i(l,n.agentDirBase)?xs(n.agentDirBase,At):At()}:{},...s===void 0?{}:{apiKeyEnv:s},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function _i(e,n){let r=_n(e),i=_n(n);return r===i||r.startsWith(i+Ai)}function At(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((n)=>n.toString(16).padStart(2,"0")).join("")}function _e(e,n){let r=n.map((i)=>An(e,i.relPath)).filter((i)=>xi(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 n){let s=An(e,i.relPath);Ti(Oi(s),{recursive:!0}),Ii(s,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function Ze(e,n){let r=V(e,{...n===void 0?{}:{env:{...process.env,...n}}}),i=ye(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:s,warnings:a}=uA(r,i.promptStyle),l=$t(s,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 jt=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Un=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Lt(e){let n=Wt(e.step,e.fallback);return n.ok?n.value:e.fallback}function Ci(e,n){let r=Un.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Lt(e),optional:e.optional===!0,secret:Cn.has(e.step),...n===void 0?{}:{requires:n},...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 _t=64;function Bt(e){let n=new Map,r=new Set,i=(a,l)=>{let c={...a},m=[];for(let w=0;w<_t;w+=1){let f=aA(c,e);if(f===void 0)break;let h=Lt(f);if(!jt.has(f.step)&&!n.has(f.step))n.set(f.step,Ci(f,l));for(let g of f.options??[]){if(g.value===h)continue;if(Un.get(f.step)?.has(g.value)===!0)continue;m.push({seed:{...c,[f.step]:g.value},opened:{step:f.step,value:g.value}})}c[f.step]=h}return m},s=[...i({})];for(let a=0;a<_t&&s.length>0;a+=1){let l=s.splice(0,s.length);for(let c of l){let m=`${c.opened.step}=${c.opened.value}`;if(r.has(m))continue;r.add(m),s.push(...i(c.seed,c.opened))}}return[...n.values()].sort((a,l)=>Sr.indexOf(a.step)-Sr.indexOf(l.step))}function qt(e){let n={};for(let[c,m]of Object.entries(e.answers)){let w=c;if(!(w in Qe))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 f=jt.get(w);if(f!==void 0)throw new A({code:f.code,message:`"${c}" cannot be set over the API.`,hint:f.hint,field:c});let h=Un.get(w)?.get(m.trim().toLowerCase());if(h!==void 0)throw new A({code:h.code,message:`${c} is ${JSON.stringify(m)}, which this runtime cannot do over the API.`,hint:h.hint,field:c});let g=Wt(w,m);if(!g.ok)throw new A({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(m)}, 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});n[w]=g.value}Nn(n,"this is the provisioning API",e.defaults,{naming:"answers"});let r=Fn(n,e.defaults),i=at(r.name),s=FA("sandbox",r.name,e.defaults);if(s===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=_n(s),l=wr({...r,dir:a});return _e(a,l),{agentId:i,dir:a,manifestPath:An(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function Ui(e){if(e.web!=="search")return;return Io(e.webBackend??"tavily")?.apiKeyEnv}async function Xt(e){let n=await Yt(e);if(n.kind==="aborted")return process.stdout.write(`nothing written
22
- `),o;return n.kind==="failed"?n.code:o}async function Ln(e){return Yt(e)}async function Yt(e){let n=Mi(e),r=it({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,s={agentDirBase:q()};if(i){let P=await Di(n,s);if(P===void 0)return{kind:"aborted"};Object.assign(n,P)}else Nn(n,e.yes===!0?"--yes was passed":r.because,s);let a=Fn(n,s),l=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),c=(i||e.measureWindow===!0)&&a.baseUrl!==""?await It(a.baseUrl,a.model,{...l===void 0||l===""?{}:{apiKey:l}}):void 0,m=a,w=Fi(process.cwd(),m.dir),f=Hs(w);if(f!==void 0)process.stderr.write(`${f}
23
- `);let h=fe(w,"agent.yaml"),g=wr(m,c);_e(w,g);let b=m.apiKeyEnv,R=b!==void 0&&m.apiKey===void 0&&(process.env[b]===void 0||process.env[b]==="")&&b!==void 0?{[b]:"(pending)"}:void 0,S=!1;try{S=Ze(fe(w,"agent.yaml"),R).distilled}catch(P){if(p(P))return process.stderr.write(`init wrote ${g.length} files to ${w}, but the result does not load:
24
- ${P.format()}
25
- `),{kind:"failed",code:d};throw P}if(process.stdout.write(`wrote ${g.length} files to ${w} — validated ok
26
- `),m.skills==="find"){let P=(m.skillsPick??"").split(",").map((T)=>T.trim()).filter((T)=>T!=="");if(P.length>0)ds(P,h,{...R===void 0?{}:{envOverlay:R}});else if(!i)await Tt({answers:m,manifestPath:h,...R===void 0?{}:{envOverlay:R}})}await Li(h,w,s.agentDirBase);let N;if(m.daemon==="service"){process.stdout.write(`
27
- `);let{outcome:P,host:T}=await jn({...e.installServer===void 0?{}:{install:e.installServer}}),O=bA(P);if(O!==void 0)process.stderr.write(O);if(T?.baseUrl!==void 0){let C=await OA(T,h);if(C.ok)N=T.baseUrl;else process.stderr.write(`pid ${T.pid} did not adopt ${at(m.name)}${C.detail===void 0?"":`: ${C.detail}`}
28
- `)}}let H;if(m.whatsapp==="connected"&&(m.whatsappNumber??"")!==""&&i)H=N!==void 0?await Jn({manifestPath:h,channelId:"wa"}):await qn({manifestPath:h,dir:w,number:m.whatsappNumber??"",channelId:"wa"});if(m.whatsapp==="connected"&&H!=="paired")process.stdout.write(`
29
- ${es(at(m.name))}`);return process.stdout.write(Hi(m,w,S,N)),{kind:"ok",manifestPath:fe(w,"agent.yaml")}}async function Li(e,n,r){let i=en(n);if(!Zt(n)){process.stdout.write(`
30
- To make it yours across every surface: ${t.slug} owner adopt ${e}
31
- `);return}let s;try{s=await ne.open({path:G()}),await Te(s,e,r)}catch(a){let l=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${l}
32
- hint: run \`${t.slug} owner adopt ${i}\` once the store is reachable.
33
- `)}finally{await s?.close()}}function Ki(e){if(e===void 0)return[];if(UA.some((n)=>n.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Mi(e){let n={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["region",e.region],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...Ki(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,s]of r){if(s===void 0)continue;let a=Wt(i,s);if(!a.ok)throw new A({code:"cli_init_flag_invalid",message:`${Qe[i]} is ${JSON.stringify(s)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});n[i]=a.value}return n}async function Di(e,n){let[{render:r},{createElement:i},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-q4p979d1.js")]),a;oo();let l=r(i(s,{title:`${t.name} ${J}`,given:e,defaults:n,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Ue()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function Hi(e,n,r,i){let s=i!==void 0,l=Ni(n)===q()?en(n):fe(n,"agent.yaml"),c=fe(n,"agent.yaml"),m=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)m.push(`Add your key: edit ${fe(n,".env")} and set ${e.apiKeyEnv}=`);let w=Ui(e);if(w!==void 0&&e.webKey===void 0)m.push(`Add your search key: edit ${fe(n,".env")} and set ${w}= — web_fetch works without it, web_search does not`);if(xA(e)&&e.composioKey===void 0)m.push(`Add your Composio key: edit ${fe(n,".env")} and set ${En}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)m.push(`Add your bot token: message @BotFather with /newbot, then edit ${fe(n,".env")} and set ${uo}=`);let f=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],h=f.length>0||e.server==="local",g=[...f,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)m.push(`open ${AA(i,en(n))} — the web UI. The service is serving `+`${en(n)} now; ${g} ${f.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),m.push(`${t.slug} run ${l} — talks to it here, attached to that same service.`);else m.push(`${t.slug} run ${l}`);if(h&&!s){if(m.push(`${t.slug} serve ${l} — starts ${g}; \`run\` starts neither`),e.daemon==="service")m.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)m.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(xA(e))m.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.");m.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.`),m.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=s?`
34
- it is running in the background now — \`${t.slug} status\` at any time,
35
- \`${t.slug} restart ${l}\` after editing it, and \`${t.slug} stop\` turns everything off.
16
+ `),Yt({action:"install",manifestPath:e.manifestPath,name:l,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let p=gi(e.manifestPath,e.envOverlay);if(p!==void 0)wi(e.manifestPath,d.skill,e.envOverlay),process.stdout.write(`
17
+ ${w(`${l} was removed again: it does not load on this machine`)}
18
+ ${S(p,4)}
19
+ ${S("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
+ `)}function pi(e,t){let r=new Map,i=t.filter((s)=>s.problem===void 0).map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return qA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}function gi(e,t){try{let r=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=r.manifest.skills;if(i===void 0)return;let s=Se(r.manifest.model.main.id,r.manifest.model.main.capabilities);uA({dir:Pt(i.dir)?i.dir:Et(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:s.promptStyle,agentDir:r.dir,runner:pe()});return}catch(r){return h(r)?r.message:String(r)}}function wi(e,t,r){try{let i=z(e,{...r===void 0?{}:{env:{...process.env,...r}}}),s=i.manifest.skills;if(s===void 0)return;let a=Pt(s.dir)?s.dir:Et(i.dir,s.dir);ai(di(a,t),{recursive:!0,force:!0}),lr(a,t)}catch{}}var In=(e)=>typeof e==="number"&&Number.isInteger(e)&&e>0?e:void 0;async function It(e,t,r={}){let i=r.fetch??fetch,s=e.replace(/\/+$/,""),a=r.apiKey===void 0?{}:{authorization:`Bearer ${r.apiKey}`},d=async(g)=>{try{let R=await i(g,{headers:a,signal:AbortSignal.timeout(3000)});if(!R.ok)return;let P=await R.json();return P!==null&&typeof P==="object"?P:void 0}catch{return}},p=((await d(`${s}/models/${t}/endpoints`))?.data?.endpoints??[]).map((g)=>In(g.context_length)).filter((g)=>g!==void 0);if(p.length>0)return{tokens:Math.min(...p),source:`the smallest of ${p.length} published endpoint${p.length===1?"":"s"} at ${s}`};let f=((await d(`${s}/models`))?.data??[]).find((g)=>g.id===t),m=In(f?.context_length)??In(f?.max_model_len);return m===void 0?void 0:{tokens:m,source:`${s}/models`}}import{randomBytes as bi}from"node:crypto";import{mkdirSync as $i,readFileSync as Ot,writeFileSync as vi}from"node:fs";import{join as Si}from"node:path";function qe(e){return Si(e,".owner")}function ki(e,t=bi){try{let i=Ot(qe(e),"utf8").trim();if(i!=="")return i}catch{}let r=`me:${Co(t(6))}`;return $i(e,{recursive:!0}),vi(qe(e),`${r}
21
+ `,{encoding:"utf8",mode:384}),r}function Pi(e){return e.flatMap((t)=>(t.allowFrom??[]).filter((r)=>r!=="*").map((r)=>`${t.type}:${r}`))}async function Ei(e,t){let r=e.conversations,i=(t.now??new Date).toISOString(),s=await r.assignment(t.agentId);if(s!==void 0&&s.participantId!==t.owner)throw new n({code:"owner_assigned_elsewhere",message:`Agent "${t.agentId}" is assigned to ${s.participantId}, not to ${t.owner}.`,hint:`Somebody else is this agent's owner, and taking it over would make it answer the wrong person as its owner. If it really is yours, unassign it first (DELETE /v1/agents/${t.agentId}/assignee) and run \`${A.slug} owner adopt ${t.agentId}\` again.`});if(await r.participant(t.owner)===void 0)await r.upsertParticipant({id:t.owner,kind:"human",role:"admin",createdAt:i});let a=[...new Set([...s?.channelIds??[],...t.channelIds])];return await r.assign({agentId:t.agentId,participantId:t.owner,...a.length===0?{}:{channelIds:a},assignedAt:i}),{channelIds:a}}async function we(e,t,r){let i=Ot(t,"utf8"),s=String(Re(i,["id"])??""),a=Re(i,["channels"]),d=ki(r),{channelIds:l}=await Ei(e,{agentId:s,owner:d,channelIds:Pi(Array.isArray(a)?a.filter((u)=>typeof u?.type==="string"):[])});return{agentId:s,owner:d,channelIds:l}}import{existsSync as Ri,mkdirSync as xi,writeFileSync as Ti}from"node:fs";import{dirname as Ii,join as On,resolve as An,sep as Oi}from"node:path";var Je={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",region:"--region",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function _n(e,t,r,i){let s=[];for(;;){let a=gA(e,r);if(a===void 0)break;if(a.optional===!0){e[a.step]="";continue}if(a.fallback===""){s.push(a.step),e[a.step]="(missing)";continue}let d=Zt(a.step,a.fallback);if(d.ok)e[a.step]=d.value}if(s.length>0){if(i?.naming==="answers"){let d=s.map((l)=>`answers.${l}`).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Provide ${d} in the request body. GET /v1/provision lists every question with its prompt, its default and its choices.`})}let a=s.map((d)=>Je[d]).join(", ");throw new n({code:"cli_init_missing_answers",message:`Not interactive (${t}), and ${s.join(", ")} ${s.length===1?"has":"have"} no default.`,hint:`Pass ${a} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Nn(e,t){let r=e,i=zt(r.preset),s=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",d=r.dir??UA(r.dirChoice,r.name,t);if(d===void 0)throw new n({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(r.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:r.user,name:r.name,purpose:r.purpose,preset:r.preset,model:r.model,baseUrl:r.baseUrl??"",...r.region===void 0?{}:{region:r.region},system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:Ai(d,t.agentDirBase)?Hs(t.agentDirBase,At):At()}:{},...s===void 0?{}:{apiKeyEnv:s},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:d}}function Ai(e,t){let r=An(e),i=An(t);return r===i||r.startsWith(i+Oi)}function At(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((t)=>t.toString(16).padStart(2,"0")).join("")}function ke(e,t){let r=t.map((i)=>On(e,i.relPath)).filter((i)=>Ri(i));if(r.length>0)throw new n({code:"cli_init_target_exists",message:`${r.length} of the files init would write already exist: ${r.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of t){let s=On(e,i.relPath);xi(Ii(s),{recursive:!0}),Ti(s,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function Xe(e,t){let r=z(e,{...t===void 0?{}:{env:{...process.env,...t}}}),i=Se(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:s,warnings:a}=EA(r,i.promptStyle),d=eA(s,r.manifest.context.rules);if(d!==void 0&&r.manifest.context.rules.onExceed==="fail")throw d;return{distilled:a.some((l)=>l.code==="soul_distilled")}}var jt=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Fn=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function Lt(e){let t=Zt(e.step,e.fallback);return t.ok?t.value:e.fallback}function _i(e,t){let r=Fn.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Lt(e),optional:e.optional===!0,secret:Cn.has(e.step),...t===void 0?{}:{requires:t},...e.options===void 0?{}:{choices:e.options.filter((i)=>r?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var Nt=64;function Dt(e){let t=new Map,r=new Set,i=(a,d)=>{let l={...a},u=[];for(let p=0;p<Nt;p+=1){let c=gA(l,e);if(c===void 0)break;let f=Lt(c);if(!jt.has(c.step)&&!t.has(c.step))t.set(c.step,_i(c,d));for(let m of c.options??[]){if(m.value===f)continue;if(Fn.get(c.step)?.has(m.value)===!0)continue;u.push({seed:{...l,[c.step]:m.value},opened:{step:c.step,value:m.value}})}l[c.step]=f}return u},s=[...i({})];for(let a=0;a<Nt&&s.length>0;a+=1){let d=s.splice(0,s.length);for(let l of d){let u=`${l.opened.step}=${l.opened.value}`;if(r.has(u))continue;r.add(u),s.push(...i(l.seed,l.opened))}}return[...t.values()].sort((a,d)=>wr.indexOf(a.step)-wr.indexOf(d.step))}function Gt(e){let t={};for(let[l,u]of Object.entries(e.answers)){let p=l;if(!(p in Je))throw new n({code:"provision_unknown_answer",message:`"${l}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:l});let c=jt.get(p);if(c!==void 0)throw new n({code:c.code,message:`"${l}" cannot be set over the API.`,hint:c.hint,field:l});let f=Fn.get(p)?.get(u.trim().toLowerCase());if(f!==void 0)throw new n({code:f.code,message:`${l} is ${JSON.stringify(u)}, which this runtime cannot do over the API.`,hint:f.hint,field:l});let m=Zt(p,u);if(!m.ok)throw new n({code:"provision_answer_invalid",message:`${l} is ${JSON.stringify(u)}, which ${m.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:l});t[p]=m.value}_n(t,"this is the provisioning API",e.defaults,{naming:"answers"});let r=Nn(t,e.defaults),i=lt(r.name),s=UA("sandbox",r.name,e.defaults);if(s===void 0)throw new n({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(r.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=An(s),d=Dr({...r,dir:a});return ke(a,d),{agentId:i,dir:a,manifestPath:On(a,"agent.yaml"),files:d.map((l)=>l.relPath)}}function ji(e){if(e.web!=="search")return;return uo(e.webBackend??"tavily")?.apiKeyEnv}async function Wt(e){let t=await Vt(e);if(t.kind==="aborted")return process.stdout.write(`nothing written
22
+ `),o;return t.kind==="failed"?t.code:o}async function Un(e){return Vt(e)}async function Vt(e){let t=Ui(e),r=gt({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,s={agentDirBase:W()};if(i){let b=await Li(t,s);if(b===void 0)return{kind:"aborted"};Object.assign(t,b)}else _n(t,e.yes===!0?"--yes was passed":r.because,s);let a=Nn(t,s),d=a.apiKey??(a.apiKeyEnv===void 0?void 0:process.env[a.apiKeyEnv]),l=(i||e.measureWindow===!0)&&a.baseUrl!==""?await It(a.baseUrl,a.model,{...d===void 0||d===""?{}:{apiKey:d}}):void 0,u=a,p=Ni(process.cwd(),u.dir),c=Ks(p);if(c!==void 0)process.stderr.write(`${c}
23
+ `);let f=le(p,"agent.yaml"),m=Dr(u,l);ke(p,m);let g=u.apiKeyEnv,P=g!==void 0&&u.apiKey===void 0&&(process.env[g]===void 0||process.env[g]==="")&&g!==void 0?{[g]:"(pending)"}:void 0,y=!1;try{y=Xe(le(p,"agent.yaml"),P).distilled}catch(b){if(h(b))return process.stderr.write(`init wrote ${m.length} files to ${p}, but the result does not load:
24
+ ${b.format()}
25
+ `),{kind:"failed",code:E};throw b}if(process.stdout.write(`wrote ${m.length} files to ${p} — validated ok
26
+ `),u.skills==="find"){let b=(u.skillsPick??"").split(",").map((x)=>x.trim()).filter((x)=>x!=="");if(b.length>0)us(b,f,{...P===void 0?{}:{envOverlay:P}});else if(!i)await Rt({answers:u,manifestPath:f,...P===void 0?{}:{envOverlay:P}})}await Fi(f,p,s.agentDirBase);let j;if(u.daemon==="service"){process.stdout.write(`
27
+ `);let{outcome:b,host:x}=await Jn({...e.installServer===void 0?{}:{install:e.installServer}}),I=OA(b);if(I!==void 0)process.stderr.write(I);if(x?.baseUrl!==void 0){let _=await NA(x,f);if(_.ok)j=x.baseUrl;else process.stderr.write(`pid ${x.pid} did not adopt ${lt(u.name)}${_.detail===void 0?"":`: ${_.detail}`}
28
+ `)}}let D;if(u.whatsapp==="connected"&&(u.whatsappNumber??"")!==""&&i)D=j!==void 0?await qn({manifestPath:f,channelId:"wa"}):await Vn({manifestPath:f,dir:p,number:u.whatsappNumber??"",channelId:"wa"});if(u.whatsapp==="connected"&&D!=="paired")process.stdout.write(`
29
+ ${ts(lt(u.name))}`);return process.stdout.write(Mi(u,p,y,j)),{kind:"ok",manifestPath:le(p,"agent.yaml")}}async function Fi(e,t,r){let i=en(t);if(!Xt(t)){process.stdout.write(`
30
+ To make it yours across every surface: ${A.slug} owner adopt ${e}
31
+ `);return}let s;try{s=await re.open({path:G()}),await we(s,e,r)}catch(a){let d=a instanceof Error?a.message:String(a);process.stderr.write(`could not record you as ${i}'s owner: ${d}
32
+ hint: run \`${A.slug} owner adopt ${i}\` once the store is reachable.
33
+ `)}finally{await s?.close()}}function Ki(e){if(e===void 0)return[];if(xA.some((t)=>t.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function Ui(e){let t={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["region",e.region],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...Ki(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,s]of r){if(s===void 0)continue;let a=Zt(i,s);if(!a.ok)throw new n({code:"cli_init_flag_invalid",message:`${Je[i]} is ${JSON.stringify(s)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});t[i]=a.value}return t}async function Li(e,t){let[{render:r},{createElement:i},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-p350qspw.js")]),a;ro();let d=r(i(s,{title:`${A.name} ${q}`,given:e,defaults:t,onDone:(l)=>{a=l}}),{exitOnCtrlC:!1,...Ke()});return H(()=>d.unmount()),await d.waitUntilExit(),d.unmount(),a}function Mi(e,t,r,i){let s=i!==void 0,d=Ci(t)===W()?en(t):le(t,"agent.yaml"),l=le(t,"agent.yaml"),u=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)u.push(`Add your key: edit ${le(t,".env")} and set ${e.apiKeyEnv}=`);let p=ji(e);if(p!==void 0&&e.webKey===void 0)u.push(`Add your search key: edit ${le(t,".env")} and set ${p}= — web_fetch works without it, web_search does not`);if(HA(e)&&e.composioKey===void 0)u.push(`Add your Composio key: edit ${le(t,".env")} and set ${pn}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)u.push(`Add your bot token: message @BotFather with /newbot, then edit ${le(t,".env")} and set ${Eo}=`);let c=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],f=c.length>0||e.server==="local",m=[...c,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)u.push(`open ${oA(i,en(t))} — the web UI. The service is serving `+`${en(t)} now; ${m} ${c.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),u.push(`${A.slug} run ${d} — talks to it here, attached to that same service.`);else u.push(`${A.slug} run ${d}`);if(f&&!s){if(u.push(`${A.slug} serve ${d} — starts ${m}; \`run\` starts neither`),e.daemon==="service")u.push(`${A.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(e.telegram==="connected"&&e.telegramAllow===void 0)u.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(HA(e))u.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");u.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${d} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches the configured catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${d} <name>\` writes one.`),u.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${l}\` shows exactly what still reads as a template.`);let g=s?`
34
+ it is running in the background now — \`${A.slug} status\` at any time,
35
+ \`${A.slug} restart ${d}\` after editing it, and \`${A.slug} stop\` turns everything off.
36
36
  `:"";return`${r?`
37
37
  this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
38
38
  frontier-class model, and activates automatically if you upgrade.
39
- `:""}${b}
40
- `+m.map((R,S)=>` ${S+1}. ${R}
41
- `).join("")}var tn=16;function ln(e=process.stdin){let n=[],r=[],i=(s)=>{let a=typeof s==="string"?s:s.toString("utf8");if(r.push(a),r.length>tn)r.splice(0,r.length-tn);if(n.push(...Xs(a)),n.length>tn)n.splice(0,n.length-tn)};return e.on("data",i),{correct:(s,a)=>ta(s,a,n),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 — \`${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 un(e){let n=e.TERM_PROGRAM??"";if(n==="vscode")return"vscode";if(n==="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(n==="WarpTerminal")return"warp";if(n==="iTerm.app")return"iterm2";if(n==="Apple_Terminal")return"apple";return"unknown"}function hn(e){return Qt.find((n)=>n.id===e)}function ss(){return Qt}function ms(e,n){return n.marker!==void 0&&e.includes(n.marker)}function ps(e,n){let r=n.line;if(r===void 0)return;if(n.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
42
- `:`${c}
39
+ `:""}${g}
40
+ `+u.map((P,y)=>` ${y+1}. ${P}
41
+ `).join("")}var nn=16;function tn(e=process.stdin){let t=[],r=[],i=(s)=>{let a=typeof s==="string"?s:s.toString("utf8");if(r.push(a),r.length>nn)r.splice(0,r.length-nn);if(t.push(...ea(a)),t.length>nn)t.splice(0,t.length-nn)};return e.on("data",i),{correct:(s,a)=>Aa(s,a,t),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Jt=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${A.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function dn(e){let t=e.TERM_PROGRAM??"";if(t==="vscode")return"vscode";if(t==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(t==="WarpTerminal")return"warp";if(t==="iTerm.app")return"iterm2";if(t==="Apple_Terminal")return"apple";return"unknown"}function mn(e){return Jt.find((t)=>t.id===e)}function Qt(){return Jt}function as(e,t){return t.marker!==void 0&&e.includes(t.marker)}function fs(e,t){let r=t.line;if(r===void 0)return;if(t.id!=="vscode"){let l=e.trimEnd();return l===""?`${r}
42
+ `:`${l}
43
43
  ${r}
44
44
  `}let i=e.trim();if(i===""||i==="[]")return`[
45
45
  ${r}
46
46
  ]
47
- `;let s=i.indexOf("[");if(s===-1)return;let l=i.slice(s+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,s+1)}
48
- ${r}${l}
49
- ${i.slice(s+1)}`}async function ys(e={}){let n=it({plain:!1,json:!1,oneShot:!1});if(n.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 (${n.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=Ue(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,s=un(process.env),a=hn(s)?.name??s,[{render:l},{createElement:c},{KeyProbe:m}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-5anphmb7.js")]),w=()=>{},f=new Promise((b)=>{w=b}),h=ln();U(()=>{h.close()}),St(),process.stdout.write(Rt);let g=l(c(m,{columns:Pe(process.stdout.columns,be),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:w}),{exitOnCtrlC:!1,...r});return U(()=>g.unmount()),await f,g.unmount(),h.close(),We(),await Ct(),o}var Gi=24,Mn=22;function Dn(e){let n=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${t.slug} ${e.name}${n===""?"":` ${n}`}`}function ws(e){let n=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?n:`-${e.short}, ${n}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(Gi-1)} ${e.help}${i}`}var bs=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
50
- delivery reads the channel back out of the key.`;function qi(e){let n=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((s)=>s.value.length))+2;n.push("",`${r.name}:`);for(let s of r.choices)n.push(` ${s.value.padEnd(i)}${s.help}`)}return n}function Gn(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Dn(e)} [flags]`,...qi(e),"","flags:",...cn(e).map(ws)];if(e.flags.some((i)=>i.name==="session"))r.push("",bs);return`${r.join(`
47
+ `;let s=i.indexOf("[");if(s===-1)return;let d=i.slice(s+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,s+1)}
48
+ ${r}${d}
49
+ ${i.slice(s+1)}`}async function ms(e={}){let t=gt({plain:!1,json:!1,oneShot:!1});if(t.mode!=="rich")throw new n({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${t.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let r=Ke(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,s=dn(process.env),a=mn(s)?.name??s,[{render:d},{createElement:l},{KeyProbe:u}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-fk5krzks.js")]),p=()=>{},c=new Promise((g)=>{p=g}),f=tn();H(()=>{f.close()}),wt(),process.stdout.write(_t);let m=d(l(u,{columns:Ue(process.stdout.columns,Me),asked:i,terminal:a,takeRaw:f.takeRaw,correctKeys:f.correct,onDone:p}),{exitOnCtrlC:!1,...r});return H(()=>m.unmount()),await c,m.unmount(),f.close(),Ze(),await ht(),o}var Di=24,Ln=22;function Mn(e){let t=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${t===""?"":` ${t}`}`}function ps(e){let t=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?t:`-${e.short}, ${t}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(Di-1)} ${e.help}${i}`}var ys=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
50
+ delivery reads the channel back out of the key.`;function Hi(e){let t=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((s)=>s.value.length))+2;t.push("",`${r.name}:`);for(let s of r.choices)t.push(` ${s.value.padEnd(i)}${s.help}`)}return t}function Dn(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${Mn(e)} [flags]`,...Hi(e),"","flags:",...ln(e).map(ps)];if(e.flags.some((i)=>i.name==="session"))r.push("",ys);return`${r.join(`
51
51
  `)}
52
- `}let n=Math.max(...rt.map((r)=>Dn(r).length))+2;return`${[`${t.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...rt.map((r)=>` ${Dn(r).padEnd(n)}${r.summary}`),` ${t.slug} --version`,` ${t.slug} --help`,"",`Per-command flags: ${t.slug} <command> --help`,"","global flags:",...gn.map(ws),"",bs,"","environment:",` ${`${t.envPrefix}BRAND`.padEnd(Mn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Mn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Mn)}print stack traces on failure`].join(`
52
+ `}let t=Math.max(...at.map((r)=>Mn(r).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...at.map((r)=>` ${Mn(r).padEnd(t)}${r.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...cn.map(ps),"",ys,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(Ln)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Ln)}set to anything to force plain output`,` ${"DEBUG".padEnd(Ln)}print stack traces on failure`].join(`
53
53
  `)}
54
- `}function $s(e){if(!(e instanceof Error))return;let n=e.code;if(n!=="ERR_MODULE_NOT_FOUND"&&n!=="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 Ji,statSync as zi}from"node:fs";var Yi=65536;function vs(e=process.env,n=(r)=>process.stderr.write(`${r}
55
- `)){let r=[];for(let[i,s]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||s===void 0||s==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(zi(s).size>Yi)continue;e[a]=Ji(s,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(l){n(`${i} names ${s}, which could not be read (${l instanceof Error?l.message:String(l)}); ${a} is not set from it.`)}}return r}var Qi=[{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 Zi(e,n){return Qi.some((r)=>r.name===e&&n.includes(r.contains))}function ea(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var Ss;function ks(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(Ss)return;if(ea(e))return;let n=process.emitWarning;Ss=n,process.emitWarning=(r,...i)=>{let s=typeof r==="string"?na(i):r.name,a=typeof r==="string"?r:r.message;if(Zi(s,a))return;Reflect.apply(n,process,[r,...i])}}function na(e){let n=e[0];return typeof n==="string"?n:"Warning"}var Ps=96;async function Rs(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});try{let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let m=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(m,null,2)}
56
- `),o;return process.stdout.write(u([{label:"passages",value:String(m.passages)},{label:"files read",value:String(m.indexed.length)},{label:"conversations",value:m.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(m.sessions.length)},{label:"shared scopes",value:m.scopes.length===0?"none":m.scopes.join(", ")},{label:"dropped",value:m.dropped.length===0?"":m.dropped.join(", ")}])),process.stdout.write(m.indexed.length===0&&m.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
57
- Read: ${[...m.indexed,...m.sessions].join(", ")}
54
+ `}function ws(e){if(!(e instanceof Error))return;let t=e.code;if(t!=="ERR_MODULE_NOT_FOUND"&&t!=="MODULE_NOT_FOUND")return;let r=/['"](ink|react)(?:\/[^'"]*)?['"]/.exec(e.message);return r?.[1]==="ink"||r?.[1]==="react"?r[1]:void 0}import{readFileSync as Gi,statSync as qi}from"node:fs";var Vi=65536;function bs(e=process.env,t=(r)=>process.stderr.write(`${r}
55
+ `)){let r=[];for(let[i,s]of Object.entries(e)){if(!i.endsWith("_FILE")||i.startsWith("AWS_")||s===void 0||s==="")continue;let a=i.slice(0,-5);if(a===""||e[a]!==void 0&&e[a]!=="")continue;try{if(qi(s).size>Vi)continue;e[a]=Gi(s,"utf8").replace(/\r?\n$/,""),r.push(a)}catch(d){t(`${i} names ${s}, which could not be read (${d instanceof Error?d.message:String(d)}); ${a} is not set from it.`)}}return r}var Yi=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function Qi(e,t){return Yi.some((r)=>r.name===e&&t.includes(r.contains))}function Zi(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var $s;function vs(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if($s)return;if(Zi(e))return;let t=process.emitWarning;$s=t,process.emitWarning=(r,...i)=>{let s=typeof r==="string"?na(i):r.name,a=typeof r==="string"?r:r.message;if(Qi(s,a))return;Reflect.apply(t,process,[r,...i])}}function na(e){let t=e[0];return typeof t==="string"?t:"Warning"}var Ss=96;async function Ps(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});try{let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let u=await r.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(u,null,2)}
56
+ `),o;return process.stdout.write(C([{label:"passages",value:String(u.passages)},{label:"files read",value:String(u.indexed.length)},{label:"conversations",value:u.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(u.sessions.length)},{label:"shared scopes",value:u.scopes.length===0?"none":u.scopes.join(", ")},{label:"dropped",value:u.dropped.length===0?"":u.dropped.join(", ")}])),process.stdout.write(u.indexed.length===0&&u.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
57
+ Read: ${[...u.indexed,...u.sessions].join(", ")}
58
58
  `),o}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
59
- `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),d;let s=await r.searchMemory({query:i,limit:e.limit??10}),a=s.hits.filter((m)=>m.score>=s.threshold),l=e.all===!0?s.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:s.corpus,threshold:s.threshold,carried:s.carried??null,hits:l.map((m)=>({source:m.passage.source,at:m.passage.at,score:m.score,lexical:m.lexical,coverage:m.coverage,tokens:m.tokens,wouldInject:m.score>=s.threshold,carried:m.passage.source===s.carried,text:m.passage.text}))},null,2)}
60
- `),o;if(process.stdout.write(u([{label:"corpus",value:`${s.corpus} passage${s.corpus===1?"":"s"}`},{label:"threshold",value:s.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),s.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),o;if(l.length===0)return process.stdout.write(`
59
+ `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),E;let s=await r.searchMemory({query:i,limit:e.limit??10}),a=s.hits.filter((u)=>u.score>=s.threshold),d=e.all===!0?s.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:s.corpus,threshold:s.threshold,carried:s.carried??null,hits:d.map((u)=>({source:u.passage.source,at:u.passage.at,score:u.score,lexical:u.lexical,coverage:u.coverage,tokens:u.tokens,wouldInject:u.score>=s.threshold,carried:u.passage.source===s.carried,text:u.passage.text}))},null,2)}
60
+ `),o;if(process.stdout.write(C([{label:"corpus",value:`${s.corpus} passage${s.corpus===1?"":"s"}`},{label:"threshold",value:s.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),s.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),o;if(d.length===0)return process.stdout.write(`
61
61
  Nothing ${e.all===!0?"matched":`scored above ${s.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
62
- `),o;let c=Math.max(6,...l.map((m)=>Es(m,s.carried).length));process.stdout.write(`
63
- ${oe("SCORE",6)} ${oe("LEXICAL",7)} ${oe("COVER",5)} ${oe("SOURCE",c)} ${oe("LEARNED",10)} PASSAGE
64
- `);for(let m of l){let w=m.score>=s.threshold?" ":"·";process.stdout.write(`${oe(m.score.toFixed(3),6)} ${oe(m.lexical.toFixed(3),7)} ${oe(m.coverage.toFixed(2),5)} ${oe(Es(m,s.carried),c)} ${oe(m.passage.at.slice(0,10),10)} ${w}${sa(m.passage.text)}
65
- `)}if(e.all===!0&&a.length<l.length)process.stdout.write(`
66
- ${l.length-a.length} shown below the threshold; a turn would not inject those.
67
- `);if(s.carried!==void 0&&l.some((m)=>m.passage.source===s.carried))process.stdout.write(`
62
+ `),o;let l=Math.max(6,...d.map((u)=>ks(u,s.carried).length));process.stdout.write(`
63
+ ${ie("SCORE",6)} ${ie("LEXICAL",7)} ${ie("COVER",5)} ${ie("SOURCE",l)} ${ie("LEARNED",10)} PASSAGE
64
+ `);for(let u of d){let p=u.score>=s.threshold?" ":"·";process.stdout.write(`${ie(u.score.toFixed(3),6)} ${ie(u.lexical.toFixed(3),7)} ${ie(u.coverage.toFixed(2),5)} ${ie(ks(u,s.carried),l)} ${ie(u.passage.at.slice(0,10),10)} ${p}${ta(u.passage.text)}
65
+ `)}if(e.all===!0&&a.length<d.length)process.stdout.write(`
66
+ ${d.length-a.length} shown below the threshold; a turn would not inject those.
67
+ `);if(s.carried!==void 0&&d.some((u)=>u.passage.source===s.carried))process.stdout.write(`
68
68
  ${s.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
69
- `);return o}finally{await n.stop("cli-exit")}}function sa(e){let n=e.replace(/\s+/g," ").trim();return n.length<=Ps?n:`${n.slice(0,Ps-1)}…`}function oe(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function Es(e,n){return e.passage.source===n?`${e.passage.source} *`:e.passage.source}var ra=["context_length","context_window","max_context_length","max_model_len"],ia=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let n=e.prompt_tokens_details;return wn(n)?n.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function wn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Bn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Ts(e,n){let r=wn(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let s=n.toLowerCase();for(let a of i){if(!wn(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===s||l.endsWith(`/${s}`)||s.endsWith(`/${l}`)))continue;for(let m of ra){let w=Bn(a[m]);if(w!==void 0)return{technique:"metadata",tokens:w,bound:"ceiling",detail:`GET /models published ${m}: ${w}`}}return}return}function Xn(e){let n=[/(?: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 n){let s=i.exec(e);if(s?.[1]===void 0)continue;let a=Bn(Number(s[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function Os(e){if(!wn(e))return;let n=Bn(e.prompt_tokens)??0;for(let[r,i]of ia){let s=i(e);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:n,field:r}}return{cached:void 0,promptTokens:n,field:void 0}}function _s(e,n,r){if(e===void 0||n===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(n.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=n.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${n.promptTokens} prompt tokens, via ${n.field}`};return{supported:!1,detail:`${n.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 Ce(e){let n=e.filter((i)=>i.bound==="ceiling");return(n.length>0?n:e).reduce((i,s)=>i===void 0||s.tokens>i.tokens?s:i,void 0)}function Ns(e,n,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${n.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
70
- `)}function js(e,n,r){return`measured ${n} against ${e} — ${r}`}function Fs(e,n){let r=Math.max(1,e),i=0,s=0;while(r<n)i+=r,s+=1,r*=2;return i+=n,s+=1,{requests:s,tokens:i}}var aa=2000000000,Us=1024,Ks=8192,Ms=2097152;function Ds(e){return"context ".repeat(Math.max(1,e))}async function je(e){let n=await e.text();try{return{text:n,json:JSON.parse(n)}}catch{return{text:n,json:void 0}}}function Gs(e,n){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let s=i.message;if(typeof s==="string")return s}if(typeof r.message==="string")return r.message}return n}async function da(e,n,r){try{let i=await n(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:s}=await je(i),a=Ts(s,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function la(e,n,r){try{let i=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:aa})}),{text:s,json:a}=await je(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=Gs(a,s.slice(0,400)),c=Xn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let m=/max_?tokens/i.test(l);return{window:m?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:m?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 Ls(e,n,r){let i=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:s}=await je(i),a=typeof s==="object"&&s!==null?s.usage:void 0;return Os(a)}async function ca(e,n,r){let i=`${Ds(Us)}
71
- Reply with the single character x.`;try{let s=await Ls(e,n,i),a=await Ls(e,n,i);return _s(s,a,Us)}catch(s){return r.push(`the caching probe failed: ${s instanceof Error?s.message:String(s)}`),{supported:void 0,detail:"the probe did not complete"}}}async function ua(e,n,r){let i=Ks,s=0;while(i<=Ms){let a;try{a=await n(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ds(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 je(a),f=typeof w==="object"&&w!==null?w.usage:void 0,h=typeof f==="object"&&f!==null?f.prompt_tokens:void 0;s=typeof h==="number"&&Number.isFinite(h)?h:s,i*=2;continue}let{text:l,json:c}=await je(a),m=Xn(Gs(c,l.slice(0,400)));if(m!==void 0)return{technique:"search",tokens:m,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${m}`};break}if(s===0)return;return{technique:"search",tokens:s,bound:"floor",detail:`accepted a prompt the endpoint counted at ${s} tokens; nothing above it named a number`}}function fa(e,n){let r=Ce(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,s=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[v(` ${e.role} · ${e.modelId}`),u([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:s},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...n===void 0?[]:[{label:"price",value:`$${n}/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:",Ns(e.modelId,r.tokens,e.outputCeiling).split(`
72
- `).map((l)=>` ${l}`).join(`
69
+ `);return o}finally{await t.stop("cli-exit")}}function ta(e){let t=e.replace(/\s+/g," ").trim();return t.length<=Ss?t:`${t.slice(0,Ss-1)}…`}function ie(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ks(e,t){return e.passage.source===t?`${e.passage.source} *`:e.passage.source}var sa=["context_length","context_window","max_context_length","max_model_len"],oa=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let t=e.prompt_tokens_details;return yn(t)?t.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function yn(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Hn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Rs(e,t){let r=yn(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let s=t.toLowerCase();for(let a of i){if(!yn(a))continue;let d=typeof a.id==="string"?a.id.toLowerCase():void 0;if(d===void 0)continue;if(!(d===s||d.endsWith(`/${s}`)||s.endsWith(`/${d}`)))continue;for(let u of sa){let p=Hn(a[u]);if(p!==void 0)return{technique:"metadata",tokens:p,bound:"ceiling",detail:`GET /models published ${u}: ${p}`}}return}return}function Gn(e){let t=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],r=[];for(let i of t){let s=i.exec(e);if(s?.[1]===void 0)continue;let a=Hn(Number(s[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function xs(e){if(!yn(e))return;let t=Hn(e.prompt_tokens)??0;for(let[r,i]of oa){let s=i(e);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:t,field:r}}return{cached:void 0,promptTokens:t,field:void 0}}function Ts(e,t,r){if(e===void 0||t===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(t.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=t.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${t.promptTokens} prompt tokens, via ${t.field}`};return{supported:!1,detail:`${t.field} came back 0 on an identical repeat of a ${r}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function Pe(e){let t=e.filter((i)=>i.bound==="ceiling");return(t.length>0?t:e).reduce((i,s)=>i===void 0||s.tokens>i.tokens?s:i,void 0)}function Os(e,t,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${t.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
70
+ `)}function _s(e,t,r){return`measured ${t} against ${e} — ${r}`}function Ns(e,t){let r=Math.max(1,e),i=0,s=0;while(r<t)i+=r,s+=1,r*=2;return i+=t,s+=1,{requests:s,tokens:i}}var ia=2000000000,js=1024,Us=8192,Ls=2097152;function Ms(e){return"context ".repeat(Math.max(1,e))}async function xe(e){let t=await e.text();try{return{text:t,json:JSON.parse(t)}}catch{return{text:t,json:void 0}}}function Ds(e,t){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let s=i.message;if(typeof s==="string")return s}if(typeof r.message==="string")return r.message}return t}async function aa(e,t,r){try{let i=await t(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:s}=await xe(i),a=Rs(s,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function la(e,t,r){try{let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:ia})}),{text:s,json:a}=await xe(i);if(i.ok)return r.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let d=Ds(a,s.slice(0,400)),l=Gn(d);if(l===void 0)return r.push(`the refusal named no number: ${d.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let u=/max_?tokens/i.test(d);return{window:u?void 0:{technique:"refusal",tokens:l,bound:"ceiling",detail:`refused an over-range request naming ${l}`},outputCeiling:u?l:void 0}}catch(i){return r.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function Fs(e,t,r){let i=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:s}=await xe(i),a=typeof s==="object"&&s!==null?s.usage:void 0;return xs(a)}async function ca(e,t,r){let i=`${Ms(js)}
71
+ Reply with the single character x.`;try{let s=await Fs(e,t,i),a=await Fs(e,t,i);return Ts(s,a,js)}catch(s){return r.push(`the caching probe failed: ${s instanceof Error?s.message:String(s)}`),{supported:void 0,detail:"the probe did not complete"}}}async function ua(e,t,r){let i=Us,s=0;while(i<=Ls){let a;try{a=await t(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ms(i)}],max_tokens:1})})}catch(p){r.push(`the search stopped at ${i}: ${p instanceof Error?p.message:String(p)}`);break}if(a.ok){let{json:p}=await xe(a),c=typeof p==="object"&&p!==null?p.usage:void 0,f=typeof c==="object"&&c!==null?c.prompt_tokens:void 0;s=typeof f==="number"&&Number.isFinite(f)?f:s,i*=2;continue}let{text:d,json:l}=await xe(a),u=Gn(Ds(l,d.slice(0,400)));if(u!==void 0)return{technique:"search",tokens:u,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${u}`};break}if(s===0)return;return{technique:"search",tokens:s,bound:"floor",detail:`accepted a prompt the endpoint counted at ${s} tokens; nothing above it named a number`}}function fa(e,t){let r=Pe(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,s=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[L(` ${e.role} · ${e.modelId}`),C([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:s},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...t===void 0?[]:[{label:"price",value:`$${t}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((d)=>` · ${d}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",Os(e.modelId,r.tokens,e.outputCeiling).split(`
72
+ `).map((d)=>` ${d}`).join(`
73
73
  `)]].join(`
74
- `)}async function Ws(e){let n=e.fetch??globalThis.fetch;try{let r=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:i}=r,s=Nt(i).filter((m)=>m.role===m.configuredAs),a=!1;if(e.window){let m=Fs(Ks,Ms),w=m.tokens*s.length,f=e.price===void 0?"":` ≈ $${(w/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${m.requests} requests per role, about ${w.toLocaleString("en-US")} input tokens in total${f}.
74
+ `)}async function Gs(e){let t=e.fetch??globalThis.fetch;try{let r=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:i}=r,s=Mt(i).filter((u)=>u.role===u.configuredAs),a=!1;if(e.window){let u=Ns(Us,Ls),p=u.tokens*s.length,c=e.price===void 0?"":` ≈ $${(p/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${u.requests} requests per role, about ${p.toLocaleString("en-US")} input tokens in total${c}.
75
75
  That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
76
76
  Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
77
- `),a=e.yes||await MA("spend it?"),process.stdout.write(a?`
77
+ `),a=e.yes||await TA("spend it?"),process.stdout.write(a?`
78
78
  `:`
79
79
  Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
80
80
 
81
- `)}let l=[];for(let m of s){let w=i.model[m.role]??i.model.main;if(w.baseUrl===void 0){process.stdout.write(`model.${m.role} uses the ${w.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${m.window.contextWindow.toLocaleString("en-US")} tokens (${m.window.source}).
82
- `);continue}let f={chat:fo(w.baseUrl),models:gi(w.baseUrl),headers:ci(w.apiKeyEnv,r.env,`model.${m.role}`),modelId:w.id},h=[],g=[],b=await da(f,n,h);if(b!==void 0)g.push(b);let x=await la(f,n,h);if(x.window!==void 0)g.push(x.window);let R=await ca(f,n,h);if(a){let S=await ua(f,n,h);if(S!==void 0)g.push(S)}l.push({role:m.role,modelId:w.id,baseUrl:w.baseUrl,declared:m.window.contextWindow,declaredSource:m.window.source,findings:g,cache:R,outputCeiling:x.outputCeiling,failures:h})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:l},null,2)}
83
- `),o;let c=e.write?await ma(r.path,l):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${l.length} role${l.length===1?"":"s"}`,...l.map((m)=>fa(m,e.price)),"",...e.write?[...c.written.length===0?[]:[" written to the manifest:",...c.written.map((m)=>` ${m}`)],...c.refused.length===0?[]:[" not written:",...c.refused.map((m)=>` ${m}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[pa(l)],""].join(`
84
- `)),o}catch(r){if(p(r))return process.stderr.write(`${r.format()}
85
- `),d;throw r}}async function ma(e,n){let r=[],i=[];for(let s of n){let a=Ce(s.findings);if(a===void 0){i.push(`${s.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${s.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===s.declared){i.push(`${s.role}: already ${a.tokens}, nothing to change`);continue}await Le({file:e,path:["model",s.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${s.role}: ${s.declared} → ${a.tokens}`)}return{written:r,refused:i}}function pa(e){let n=e.filter((a)=>Ce(a.findings)?.bound==="ceiling");if(n.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=n[0],i=r===void 0?void 0:Ce(r.findings);if(r===void 0||i===void 0)return"";let s=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${js(s,new Date().toISOString().slice(0,10),i.detail)}`].join(`
86
- `)}import{readFileSync as ha}from"node:fs";async function Bs(e){let n=q();if(e.action==="show"){let w;try{w=ha(Ye(n),"utf8").trim()||void 0}catch{w=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:w??null})}
87
- `);else process.stdout.write(w===void 0?`No owner yet. \`${t.slug} init\` or \`${t.slug} owner adopt <agent>\` makes you one.
88
- `:`${w}
89
- `);return o}let r=e.manifestPath;if(r===void 0||r==="")throw new A({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${t.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=F(r).id??"",s=await ne.open({path:e.store??G()}),a;try{a=await Te(s,r,n)}finally{await s.close()}let l=await Le({file:r,path:["sessions","scope"],value:"owner",fallback:(w)=>/^sessions:/m.test(w)?void 0:`${w.replace(/\n*$/,`
81
+ `)}let d=[];for(let u of s){let p=i.model[u.role]??i.model.main;if(p.baseUrl===void 0){process.stdout.write(`model.${u.role} uses the ${p.api??"chat-completions"} transport, which this probe does not speak. Its window comes from the capability registry: ${u.window.contextWindow.toLocaleString("en-US")} tokens (${u.window.source}).
82
+ `);continue}let c={chat:ho(p.baseUrl),models:ci(p.baseUrl),headers:li(p.apiKeyEnv,r.env,`model.${u.role}`),modelId:p.id},f=[],m=[],g=await aa(c,t,f);if(g!==void 0)m.push(g);let R=await la(c,t,f);if(R.window!==void 0)m.push(R.window);let P=await ca(c,t,f);if(a){let y=await ua(c,t,f);if(y!==void 0)m.push(y)}d.push({role:u.role,modelId:p.id,baseUrl:p.baseUrl,declared:u.window.contextWindow,declaredSource:u.window.source,findings:m,cache:P,outputCeiling:R.outputCeiling,failures:f})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:d},null,2)}
83
+ `),o;let l=e.write?await ma(r.path,d):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${d.length} role${d.length===1?"":"s"}`,...d.map((u)=>fa(u,e.price)),"",...e.write?[...l.written.length===0?[]:[" written to the manifest:",...l.written.map((u)=>` ${u}`)],...l.refused.length===0?[]:[" not written:",...l.refused.map((u)=>` ${u}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[pa(d)],""].join(`
84
+ `)),o}catch(r){if(h(r))return process.stderr.write(`${r.format()}
85
+ `),E;throw r}}async function ma(e,t){let r=[],i=[];for(let s of t){let a=Pe(s.findings);if(a===void 0){i.push(`${s.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${s.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===s.declared){i.push(`${s.role}: already ${a.tokens}, nothing to change`);continue}await Fe({file:e,path:["model",s.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${s.role}: ${s.declared} → ${a.tokens}`)}return{written:r,refused:i}}function pa(e){let t=e.filter((a)=>Pe(a.findings)?.bound==="ceiling");if(t.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=t[0],i=r===void 0?void 0:Pe(r.findings);if(r===void 0||i===void 0)return"";let s=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${_s(s,new Date().toISOString().slice(0,10),i.detail)}`].join(`
86
+ `)}import{readFileSync as ha}from"node:fs";async function Ws(e){let t=W();if(e.action==="show"){let p;try{p=ha(qe(t),"utf8").trim()||void 0}catch{p=void 0}if(e.json)process.stdout.write(`${JSON.stringify({owner:p??null})}
87
+ `);else process.stdout.write(p===void 0?`No owner yet. \`${A.slug} init\` or \`${A.slug} owner adopt <agent>\` makes you one.
88
+ `:`${p}
89
+ `);return o}let r=e.manifestPath;if(r===void 0||r==="")throw new n({code:"owner_agent_required",message:"owner adopt needs an agent.",hint:`Name one: \`${A.slug} owner adopt milo\`, or a path to its agent.yaml.`});let i=U(r).id??"",s=await re.open({path:e.store??G()}),a;try{a=await we(s,r,t)}finally{await s.close()}let d=await Fe({file:r,path:["sessions","scope"],value:"owner",fallback:(p)=>/^sessions:/m.test(p)?void 0:`${p.replace(/\n*$/,`
90
90
  `)}
91
91
  # One conversation with you across the web, the terminal and every channel.
92
92
  sessions:
93
93
  scope: owner
94
- `}),c=await NA(r,e.store),m=c.kind==="reloaded"||c.kind==="pending"?`reloaded by pid ${c.pid}`:c.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${c.pid} did not reload it (${c.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:l.changed,reload:c.kind})}
95
- `),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${l.changed?"":" (already)"}`,`you on ${a.channelIds.length===0?"the web and the terminal only — no allowFrom entries to recognise you by on a channel":a.channelIds.join(", ")}`,`host ${m}`,""].join(`
96
- `)),o}import{existsSync as fr,rmSync as Sa}from"node:fs";import{resolve as ka}from"node:path";var ga={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function qs(e){if(e===null||typeof e!=="object")return!1;let n=e.kind;return n==="network"||n==="env"||n==="fs"||n==="exec"||n==="store"}async function Vs(e,n={}){let r=[],i=[],s=n.hostVersion??xe,a=(g,b,x)=>{r.push({level:"error",check:g,message:b,hint:x})},l=(g,b,x)=>{r.push({level:"warning",check:g,message:b,hint:x})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(dr(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let c=dr(s,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 (${s}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")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(!qs(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 m=n.config??{};if(e.configSchema!==void 0){let g=e.configSchema.safeParse(m);if(g.success)m=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:m,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:ga,events:new Ir({runtimeId:"conformance"})},f=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()-f)*100)/100;if(h>ur)a("setup budget",`\`setup\` took ${h} ms against a ${ur} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)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(qs)}}}import{existsSync as he,mkdirSync as ya,readdirSync as wa,readFileSync as Qn,renameSync as zs,rmSync as pe,writeFileSync as ba}from"node:fs";import{join as Y}from"node:path";var Ys=".origin.json";function $a(e){let n=Y(e,Ys);if(!he(n))return;try{return JSON.parse(Qn(n,"utf8"))}catch{return}}function Zn(e){let n=ae(e),r;try{r=wa(n)}catch{return[]}let i=[];for(let s of r.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let a=Y(n,s);if(!he(Y(a,"package.json"))&&!he(Y(a,"index.js")))continue;let l=$a(a);i.push({name:s,dir:a,...l===void 0?{}:{origin:l}})}return i}function Qs(e){let n=Y(e,"package.json");if(!he(n))return Y(e,"index.js");try{let r=JSON.parse(Qn(n,"utf8"));if(typeof r.main==="string"&&r.main!=="")return Y(e,r.main)}catch{}return Y(e,"index.js")}function Zs(e){let n=Y(e,"package.json");if(!he(n))return;let r;try{r=JSON.parse(Qn(n,"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(Y(e,"node_modules")))return;let s=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${s}${i.length>4?", …":""}) and ships no node_modules`}function er(e,n){let i=((n??e).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!kA(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 or(e,n={}){let r=n.git??jr,i=br(e.name,n.env),s=`${i}.partial`;ya(ae(n.env),{recursive:!0}),pe(s,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,s]);if(a.code!==0)throw pe(s,{recursive:!0,force:!0}),va(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],s),c=l.code===0?l.stdout.trim():"unknown",m=e.path===void 0?s:Y(s,e.path);if(!he(m))throw pe(s,{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(Y(m,".git"),{recursive:!0,force:!0});try{await n.inspect?.(m)}catch(f){throw pe(s,{recursive:!0,force:!0}),f}if(pe(i,{recursive:!0,force:!0}),m===s)zs(s,i);else zs(m,i),pe(s,{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 ba(Y(i,Ys),`${JSON.stringify(w,null,4)}
97
- `),{dir:i,commit:c}}function va(e,n,r){let i=n.trim().split(`
98
- `).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 mr(e){switch(e.action){case"list":return await Pa(e);case"add":return await Ra(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 Pa(e){let n=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(e.env),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),store:G(e.env),lease:!1});U(()=>n.stop("cli-exit"));let r=[...n.plugins.values()].flat(),i=Zn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:Jr},null,2)}
94
+ `}),l=await MA(r,e.store),u=l.kind==="reloaded"||l.kind==="pending"?`reloaded by pid ${l.pid}`:l.kind==="no-host"?"not running here; takes effect when it next starts":`pid ${l.pid} did not reload it (${l.kind}); restart it to take effect`;if(e.json)return process.stdout.write(`${JSON.stringify({agent:i,owner:a.owner,channelIds:a.channelIds,scopeChanged:d.changed,reload:l.kind})}
95
+ `),o;return process.stdout.write([`owner ${a.owner}`,`agent ${i} sessions.scope: owner${d.changed?"":" (already)"}`,`you on ${a.channelIds.length===0?"the web and the terminal only — no allowFrom entries to recognise you by on a channel":a.channelIds.join(", ")}`,`host ${u}`,""].join(`
96
+ `)),o}import{existsSync as rr,rmSync as Sa}from"node:fs";import{resolve as ka}from"node:path";var ga={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function Vs(e){if(e===null||typeof e!=="object")return!1;let t=e.kind;return t==="network"||t==="env"||t==="fs"||t==="exec"||t==="store"}async function Js(e,t={}){let r=[],i=[],s=t.hostVersion??Ye,a=(m,g,R)=>{r.push({level:"error",check:m,message:g,hint:R})},d=(m,g,R)=>{r.push({level:"warning",check:m,message:g,hint:R})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(ur(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let l=ur(s,e.dispachApi);if(l===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!l)d("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${s}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")d("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[m,g]of(e.permissions??[]).entries())if(!Vs(g))a("permissions",`\`permissions[${m}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let u=t.config??{};if(e.configSchema!==void 0){let m=e.configSchema.safeParse(u);if(m.success)u=m.data;else d("configSchema","The schema refused the config this suite passed.","Pass a valid `config` through `conformance(plugin, { config })`. The default is `{}`, which a schema with required fields correctly rejects.")}let p={defineChannel:(m)=>i.push(`channel:${m}`),defineToolProvider:(m)=>i.push(`toolProvider:${m}`),defineModelTransport:(m)=>i.push(`modelTransport:${m}`),defineMediaProvider:(m)=>i.push(`mediaProvider:${m}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(m)=>i.push(`middleware:${m.name}`),defineRoute:(m)=>i.push(`route:${m.method} ${m.path}`),config:u,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:ga,events:new dr({runtimeId:"conformance"})},c=performance.now();try{await e.setup(p)}catch(m){a("setup",`\`setup\` threw: ${m instanceof Error?m.message:String(m)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let f=Math.round((performance.now()-c)*100)/100;if(f>Er)a("setup budget",`\`setup\` took ${f} ms against a ${Er} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)d("setup","`setup` registered nothing.","A plugin that registers no channel, tool provider, script runner or middleware extends nothing. Every `define*` and `use` call is recorded, so registering something and still seeing this means the registration did not run — check for a branch in `setup` that skipped it.");return{ok:r.every((m)=>m.level!=="error"),findings:r,registered:i,setupMs:f,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(Vs)}}}import{existsSync as ue,mkdirSync as ya,readdirSync as wa,readFileSync as Bn,renameSync as Xs,rmSync as ce,writeFileSync as ba}from"node:fs";import{join as Q}from"node:path";var zs=".origin.json";function $a(e){let t=Q(e,zs);if(!ue(t))return;try{return JSON.parse(Bn(t,"utf8"))}catch{return}}function Xn(e){let t=ge(e),r;try{r=wa(t)}catch{return[]}let i=[];for(let s of r.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let a=Q(t,s);if(!ue(Q(a,"package.json"))&&!ue(Q(a,"index.js")))continue;let d=$a(a);i.push({name:s,dir:a,...d===void 0?{}:{origin:d}})}return i}function Ys(e){let t=Q(e,"package.json");if(!ue(t))return Q(e,"index.js");try{let r=JSON.parse(Bn(t,"utf8"));if(typeof r.main==="string"&&r.main!=="")return Q(e,r.main)}catch{}return Q(e,"index.js")}function Qs(e){let t=Q(e,"package.json");if(!ue(t))return;let r;try{r=JSON.parse(Bn(t,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(r.dependencies??{});if(i.length===0)return;if(ue(Q(e,"node_modules")))return;let s=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${s}${i.length>4?", …":""}) and ships no node_modules`}function Zs(e,t){let i=((t??e).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!vA(i))throw new n({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function tr(e,t={}){let r=t.git??Jr,i=Or(e.name,t.env),s=`${i}.partial`;ya(ge(t.env),{recursive:!0}),ce(s,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,s]);if(a.code!==0)throw ce(s,{recursive:!0,force:!0}),va(e,a.stderr,a.timedOut===!0);let d=await r(["rev-parse","--short","HEAD"],s),l=d.code===0?d.stdout.trim():"unknown",u=e.path===void 0?s:Q(s,e.path);if(!ue(u))throw ce(s,{recursive:!0,force:!0}),new n({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${l}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ce(Q(u,".git"),{recursive:!0,force:!0});try{await t.inspect?.(u)}catch(c){throw ce(s,{recursive:!0,force:!0}),c}if(ce(i,{recursive:!0,force:!0}),u===s)Xs(s,i);else Xs(u,i),ce(s,{recursive:!0,force:!0});let p={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:l,fetchedAt:new Date().toISOString()};return ba(Q(i,zs),`${JSON.stringify(p,null,4)}
97
+ `),{dir:i,commit:l}}function va(e,t,r){let i=t.trim().split(`
98
+ `).slice(-3).join(" ");if(r)return new n({code:"plugin_fetch_timeout",message:`${e.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${e.name} is untouched.`});return new n({code:"plugin_fetch_failed",message:`${e.name}: could not clone ${e.url}${i.length===0?"":` — ${i}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function mr(e){switch(e.action){case"list":return await Pa(e);case"add":return await Ra(e);case"remove":return await Oa(e);default:throw new n({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${A.slug} plugins list <agent>\`.`})}}async function Pa(e){let t=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(e.env),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),store:G(e.env),lease:!1});H(()=>t.stop("cli-exit"));let r=[...t.plugins.values()].flat(),i=Xn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:qr},null,2)}
99
99
  `),o;if(r.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
100
100
 
101
- ${Jr.map((c)=>` - "${c}"`).join(`
101
+ ${qr.map((l)=>` - "${l}"`).join(`
102
102
  `)}
103
103
 
104
- Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${t.slug} plugins add <agent> <repo>\`.
104
+ Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${A.slug} plugins add <agent> <repo>\`.
105
105
  `),i.length>0)process.stdout.write(`
106
- Installed in ${ae(e.env)} and named by no agent:
107
- ${i.map((c)=>` - "${c.name}"`).join(`
106
+ Installed in ${ge(e.env)} and named by no agent:
107
+ ${i.map((l)=>` - "${l.name}"`).join(`
108
108
  `)}
109
- `);return o}let s=r.map((c)=>({label:c.name,value:`${c.version} ${`${c.setupMs} ms`.padStart(9)}`,note:`${Ea(c.spec,c.lookup,i)} — ${c.registered.length===0?"registered nothing":c.registered.join(", ")}`}));process.stdout.write(`${u(s)}
110
- `);let a=r.filter((c)=>c.permissions.length>0);if(a.length>0){process.stdout.write(`
109
+ `);return o}let s=r.map((l)=>({label:l.name,value:`${l.version} ${`${l.setupMs} ms`.padStart(9)}`,note:`${Ea(l.spec,l.lookup,i)} — ${l.registered.length===0?"registered nothing":l.registered.join(", ")}`}));process.stdout.write(`${C(s)}
110
+ `);let a=r.filter((l)=>l.permissions.length>0);if(a.length>0){process.stdout.write(`
111
111
  Declared access — advisory in v1, recorded and not enforced:
112
- `);for(let c of a)for(let m of c.permissions)process.stdout.write(` ${c.name} ${m.kind} ${hr(m)}
113
- `)}let l=i.filter((c)=>!r.some((m)=>m.spec===c.name));if(l.length>0)process.stdout.write(`
114
- Also installed, named by no agent: ${l.map((c)=>c.name).join(", ")}
115
- `);return o}function Ea(e,n,r){if(n!=="installed")return n==="registry"?"built in":"imported";let i=r.find((s)=>s.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function hr(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function Ra(e){let n=e.rest?.[0];if(n===void 0||n==="")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=gr(n)?{url:ka(n.replace(/^file:\/\//,""))}:sr(n),i=e.ref??r.ref,s=e.name===void 0?er(r.url,r.path):xa(e.name),a=Zn(e.env).find((h)=>h.name===s);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 "${s}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${t.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${s}"…
116
- `);let l,c=await or({name:s,url:r.url,...i===void 0?{}:{ref:i},...r.path===void 0?{}:{path:r.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(h)=>{let g=Zs(h);if(g!==void 0)throw new A({code:"plugin_not_self_contained",message:`${s} 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=Qs(h);if(!fr(b))throw new A({code:"plugin_entry_missing",message:`${s} 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 x=await Ta(s,b);if(l=await Vs(x),!l.ok)throw new A({code:"plugin_not_conformant",message:`${l.declared.name} does not meet the plugin contract:
117
- ${l.findings.filter((R)=>R.level==="error").map((R)=>` ${R.check}: ${R.message}`).join(`
118
- `)}`,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(wo(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."})}}),m=l?.declared;if(process.stdout.write(`
119
- ${m?.name??s} ${m?.version??"?"} (${c.commit})
112
+ `);for(let l of a)for(let u of l.permissions)process.stdout.write(` ${l.name} ${u.kind} ${hr(u)}
113
+ `)}let d=i.filter((l)=>!r.some((u)=>u.spec===l.name));if(d.length>0)process.stdout.write(`
114
+ Also installed, named by no agent: ${d.map((l)=>l.name).join(", ")}
115
+ `);return o}function Ea(e,t,r){if(t!=="installed")return t==="registry"?"built in":"imported";let i=r.find((s)=>s.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function hr(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function Ra(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${A.slug} plugins add <agent> <owner/repo> [--ref v1.0.0]\`. A plugin is fetched with git — an owner/repo shorthand, a clone URL, the page URL you were reading (whose .../tree/<branch>/<subdir> is understood), or a local repository while you are writing one.`});let r=cr(t)?{url:ka(t.replace(/^file:\/\//,""))}:ar(t),i=e.ref??r.ref,s=e.name===void 0?Zs(r.url,r.path):xa(e.name),a=Xn(e.env).find((f)=>f.name===s);if(a?.origin!==void 0&&a.origin.url!==r.url)throw new n({code:"plugin_name_taken",message:`A different plugin is already installed as "${s}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${A.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${r.url}${i===void 0?"":` at ${i}`} as "${s}"…
116
+ `);let d,l=await tr({name:s,url:r.url,...i===void 0?{}:{ref:i},...r.path===void 0?{}:{path:r.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(f)=>{let m=Qs(f);if(m!==void 0)throw new n({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${m}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let g=Ys(f);if(!rr(g))throw new n({code:"plugin_entry_missing",message:`${s} has no entry file — ${g.slice(f.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let R=await Ta(s,g);if(d=await Js(R),!d.ok)throw new n({code:"plugin_not_conformant",message:`${d.declared.name} does not meet the plugin contract:
117
+ ${d.findings.filter((P)=>P.level==="error").map((P)=>` ${P.check}: ${P.message}`).join(`
118
+ `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${A.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(Do(q,d.declared.apiRange)!==!0)throw new n({code:"plugin_api_mismatch",message:`${d.declared.name} ${d.declared.version} supports host ${d.declared.apiRange}, and this host is ${q}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),u=d?.declared;if(process.stdout.write(`
119
+ ${u?.name??s} ${u?.version??"?"} (${l.commit})
120
120
  from ${r.url}${i===void 0?"":` at ${i}`}
121
- installed ${c.dir}
122
- host range ${m?.apiRange??"?"} — this host is ${J}
123
- registers ${l===void 0||l.registered.length===0?"nothing":l.registered.join(", ")}
124
- `),m!==void 0&&m.permissions.length>0)process.stdout.write(`
121
+ installed ${l.dir}
122
+ host range ${u?.apiRange??"?"} — this host is ${q}
123
+ registers ${d===void 0||d.registered.length===0?"nothing":d.registered.join(", ")}
124
+ `),u!==void 0&&u.permissions.length>0)process.stdout.write(`
125
125
  It declares access to:
126
- ${m.permissions.map((h)=>` ${h.kind} ${hr(h)}`).join(`
126
+ ${u.permissions.map((f)=>` ${f.kind} ${hr(f)}`).join(`
127
127
  `)}
128
128
  `+"\nAdvisory only. `permissions` is recorded and enforced by nothing in v1 (decision 7.5) —\n"+`a plugin is trusted in-process code, so this list is what the author says it needs, not a
129
129
  boundary. Install plugins you trust.
130
130
  `);else process.stdout.write(`
131
131
  It declares no access. That is not a guarantee: \`permissions\` is advisory in v1, so a
132
132
  plugin that declares nothing can still do anything this process can. Install plugins you trust.
133
- `);let w=l?.findings.filter((h)=>h.level==="warning")??[];for(let h of w)process.stdout.write(`
134
- note: ${h.check} — ${h.message}
135
- `);if(m!==void 0&&m.name!==s)process.stdout.write(`
136
- note: it calls itself "${m.name}"; the \`plugins:\` entry is the directory, "${s}".
137
- `);let f=await Oa(e.manifestPath,s);return process.stdout.write(f==="already"?`
133
+ `);let p=d?.findings.filter((f)=>f.level==="warning")??[];for(let f of p)process.stdout.write(`
134
+ note: ${f.check} — ${f.message}
135
+ `);if(u!==void 0&&u.name!==s)process.stdout.write(`
136
+ note: it calls itself "${u.name}"; the \`plugins:\` entry is the directory, "${s}".
137
+ `);let c=await Ia(e.manifestPath,s);return process.stdout.write(c==="already"?`
138
138
  ${e.manifestPath} already names "${s}".
139
139
  `:`
140
140
  Added "${s}" to the plugins: block in ${e.manifestPath}.
141
141
  It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
142
- `),o}function xa(e){if(kA(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 Ta(e,n){let r;try{r=await import(n)}catch(s){throw new A({code:"plugin_import_failed",message:`${e}: ${n} could not be imported — ${s instanceof Error?s.message:String(s)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:s})}let i=r.default;if(i===null||typeof i!=="object")throw new A({code:"plugin_malformed",message:`${e}: ${n} 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 ${n} 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 Oa(e,n){let i=F(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===n))return"already";return await Le({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),n]}),"written"}async function Aa(e){let n=e.rest?.[0];if(n===void 0||n==="")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=(F(e.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec);if(i.includes(n))await Le({file:e.manifestPath,path:["plugins"],value:i.filter((l)=>l!==n)}),process.stdout.write(`Dropped "${n}" from ${e.manifestPath}.
143
- Run \`${t.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
144
- `);else process.stdout.write(`${e.manifestPath} does not name "${n}".
145
- `);let s=br(n,e.env);if(!fr(s))return process.stdout.write(`Nothing installed at ${s}.
146
- `),o;let a=_a(n,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${s} — still named by ${a.join(", ")}.
142
+ `),o}function xa(e){if(vA(e))return e;throw new n({code:"plugin_name_invalid",message:`--name ${JSON.stringify(e)} is not a usable plugin directory name`,hint:"Lowercase letters, digits and single hyphens. That segment is what the manifest's `plugins:` entry names, so it has to be a directory name and a YAML scalar at once."})}async function Ta(e,t){let r;try{r=await import(t)}catch(s){throw new n({code:"plugin_import_failed",message:`${e}: ${t} could not be imported — ${s instanceof Error?s.message:String(s)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:s})}let i=r.default;if(i===null||typeof i!=="object")throw new n({code:"plugin_malformed",message:`${e}: ${t} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${A.slug}Api\` host range and \`setup\`. A named export is not searched for and a factory function is not called, because a wrong guess produces a plugin that registers nothing and reports success.`});if(typeof i.setup!=="function")throw new n({code:"plugin_malformed",message:`${e}: the default export of ${t} has no \`setup\` function`,hint:"`setup(context)` is the whole extension surface — it registers channels, tool providers, a script runner or middleware, and does no work."});return i}async function Ia(e,t){let i=U(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===t))return"already";return await Fe({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),t]}),"written"}async function Oa(e){let t=e.rest?.[0];if(t===void 0||t==="")throw new n({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${A.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(U(e.manifestPath).plugins??[]).map((d)=>typeof d==="string"?d:d.spec);if(i.includes(t))await Fe({file:e.manifestPath,path:["plugins"],value:i.filter((d)=>d!==t)}),process.stdout.write(`Dropped "${t}" from ${e.manifestPath}.
143
+ Run \`${A.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
144
+ `);else process.stdout.write(`${e.manifestPath} does not name "${t}".
145
+ `);let s=Or(t,e.env);if(!rr(s))return process.stdout.write(`Nothing installed at ${s}.
146
+ `),o;let a=_a(t,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${s} — still named by ${a.join(", ")}.
147
147
  Remove it from those agents first, or delete the directory by hand.
148
148
  `),o;return Sa(s,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${s}.
149
- `),o}function _a(e,n,r){let i=[];for(let s of Ae(r)){if(s.manifestPath===n)continue;try{if((F(s.manifestPath).plugins??[]).map((c)=>typeof c==="string"?c:c.spec).includes(e))i.push(s.ref)}catch{}}return i}import{existsSync as Da,readdirSync as Tr,rmSync as et,statSync as _r}from"node:fs";import{homedir as Ha}from"node:os";import{join as Nr}from"node:path";function yr(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let n=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${n} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function $r(e){let n=[];if(e.running!==void 0)n.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)n.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(n.push({kind:"store",detail:`delete ${D(r.sessions,"conversation")}, ${D(r.messages,"message")}, ${D(r.passages,"memory passage")}`}),e.logs.length>0)n.push({kind:"logs",detail:`delete ${D(e.logs.length,"log file")}`})}return n.push({kind:"directory",detail:`delete ${e.dir}`}),n}function vr(e){let n=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${D(e.files.count,"file")}, ${nA(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:`${D(n.sessions,"conversation")}, ${D(n.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${D(n.sessions,"conversation")}, ${D(n.messages,"message")}, ${D(n.turns,"turn")}`},{label:"memory",value:`${D(n.passages,"passage")} from ${D(n.memorySources,"source")}`},{label:"outbox",value:n.outbox===0?"nothing queued":`${D(n.outbox,"delivery")}${n.outboxPending===0?"":`, ${n.outboxPending} not yet sent`}`,...n.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:n.schedules===0?"none":D(n.schedules,"schedule"),...n.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${D(e.logs.length,"file")}, ${nA(e.logs.reduce((i,s)=>i+s.bytes,0))}`},{label:"service",value:e.service??"not installed"});return r.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),u(r)}function kr(e){if(e.length===0)return"";return e.map((n)=>{let r=n.footprint,i=[];if(r.sessions>0)i.push(`${D(r.sessions,"conversation")}, ${D(r.messages,"message")}`);if(r.passages>0)i.push(`${D(r.passages,"memory passage")}`);if(r.outbox>0)i.push(`${D(r.outbox,"queued delivery")}`);if(r.schedules>0)i.push(`${D(r.schedules,"schedule")}`);if(r.lease)i.push("a stale lease");if(n.logs.length>0)i.push(`${D(n.logs.length,"log file")}, ${nA(n.logs.reduce((s,a)=>s+a.bytes,0))}`);return` ${n.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
150
- `)}function D(e,n){return`${e} ${n}${e===1?"":"s"}`}import{homedir as Ca}from"node:os";var Pr=12000,Na=250;async function $n(e){if(e.manifestPath!==void 0)return await ja(e,e.manifestPath);return await Fa(e)}async function ja(e,n){let r=Ma(n),i=[];if(e.dryRun===!0){let c=await qe(r,e.store);return process.stdout.write(`would stop 1 agent:
151
- ${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`}`)}
152
- `),o}await rr(r,!1,e.reason,e.store),i.push("switched off for the next start");let s=await qe(r,e.store),a=!0;if(s===void 0)i.push("nothing was running");else if(s.baseUrl===void 0){let c=await bn(s.pid,"SIGTERM");a=c||await bn(s.pid,"SIGKILL",!0),i.push(c?`pid ${s.pid} stopped cleanly`:a?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let c=await ut(s,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},n);if(c.ok)i.push(`pid ${s.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 ${s.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${c.detail===void 0?"":`: ${c.detail}`}`)}let l={agentId:r,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[l]},null,2)}
153
- `);else process.stdout.write(`${u([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:l.note}])}
149
+ `),o}function _a(e,t,r){let i=[];for(let s of oe(r)){if(s.manifestPath===t)continue;try{if((U(s.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec).includes(e))i.push(s.ref)}catch{}}return i}import{existsSync as Da,readdirSync as Rr,rmSync as et,statSync as xr}from"node:fs";import{homedir as Ha}from"node:os";import{join as Tr}from"node:path";function yr(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let t=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${t} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function $r(e){let t=[];if(e.running!==void 0)t.push({kind:"stop",detail:`stop pid ${e.running.pid} (${e.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!e.filesOnly&&e.service!==void 0)t.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(t.push({kind:"store",detail:`delete ${M(r.sessions,"conversation")}, ${M(r.messages,"message")}, ${M(r.passages,"memory passage")}`}),e.logs.length>0)t.push({kind:"logs",detail:`delete ${M(e.logs.length,"log file")}`})}return t.push({kind:"directory",detail:`delete ${e.dir}`}),t}function vr(e){let t=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${M(e.files.count,"file")}, ${rA(e.files.bytes)}`}];if(e.agentId!==e.ref)r.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)r.push({label:"keeping",value:`${M(t.sessions,"conversation")}, ${M(t.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${M(t.sessions,"conversation")}, ${M(t.messages,"message")}, ${M(t.turns,"turn")}`},{label:"memory",value:`${M(t.passages,"passage")} from ${M(t.memorySources,"source")}`},{label:"outbox",value:t.outbox===0?"nothing queued":`${M(t.outbox,"delivery")}${t.outboxPending===0?"":`, ${t.outboxPending} not yet sent`}`,...t.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:t.schedules===0?"none":M(t.schedules,"schedule"),...t.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${M(e.logs.length,"file")}, ${rA(e.logs.reduce((i,s)=>i+s.bytes,0))}`},{label:"service",value:e.service??"not installed"});return r.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),C(r)}function Sr(e){if(e.length===0)return"";return e.map((t)=>{let r=t.footprint,i=[];if(r.sessions>0)i.push(`${M(r.sessions,"conversation")}, ${M(r.messages,"message")}`);if(r.passages>0)i.push(`${M(r.passages,"memory passage")}`);if(r.outbox>0)i.push(`${M(r.outbox,"queued delivery")}`);if(r.schedules>0)i.push(`${M(r.schedules,"schedule")}`);if(r.lease)i.push("a stale lease");if(t.logs.length>0)i.push(`${M(t.logs.length,"log file")}, ${rA(t.logs.reduce((s,a)=>s+a.bytes,0))}`);return` ${t.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
150
+ `)}function M(e,t){return`${e} ${t}${e===1?"":"s"}`}import{homedir as Ca}from"node:os";var kr=12000,Na=250;async function $n(e){if(e.manifestPath!==void 0)return await ja(e,e.manifestPath);return await Fa(e)}async function ja(e,t){let r=Ma(t),i=[];if(e.dryRun===!0){let l=await We(r,e.store);return process.stdout.write(`would stop 1 agent:
151
+ ${w(`${r} — ${l===void 0?"not running; would be switched off for the next start":l.baseUrl===void 0?`pid ${l.pid} (${l.mode}), which serves no HTTP — would be signalled`:`pid ${l.pid} (${l.mode}) at ${l.baseUrl}, which would drop it and keep serving`}`)}
152
+ `),o}await ir(r,!1,e.reason,e.store),i.push("switched off for the next start");let s=await We(r,e.store),a=!0;if(s===void 0)i.push("nothing was running");else if(s.baseUrl===void 0){let l=await bn(s.pid,"SIGTERM");a=l||await bn(s.pid,"SIGKILL",!0),i.push(l?`pid ${s.pid} stopped cleanly`:a?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let l=await Ct(s,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},t);if(l.ok)i.push(`pid ${s.pid} dropped it and kept serving`);else if(l.status===409)a=!1,i.push(l.detail??"a turn is running");else if(l.status===401)a=!1,i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${l.detail===void 0?"":`: ${l.detail}`}`)}let d={agentId:r,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[d]},null,2)}
153
+ `);else process.stdout.write(`${C([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:d.note}])}
154
154
  `),process.stdout.write(`
155
- Stays off across restarts. \`${t.slug} start ${r}\` switches it back on.
156
- `);return a?o:d}async function Fa(e){let n=e.platform??process.platform,r=n==="darwin"?rn(n,{home:Ca(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Ua(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
155
+ Stays off across restarts. \`${A.slug} start ${r}\` switches it back on.
156
+ `);return a?o:E}async function Fa(e){let t=e.platform??process.platform,r=t==="darwin"?sn(t,{home:Ca(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Ka(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
157
157
  `:`Nothing is running — no service is installed and no process holds an agent.
158
158
  `),o;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
159
- ${i.map((a)=>Q(Ka(a))).join(`
159
+ ${i.map((a)=>w(La(a))).join(`
160
160
  `)}
161
- `),o;let s=[];for(let a of i)s.push(await La(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
162
- `);else{let a=s.map((l)=>({label:Rr(l.agentId),value:l.stopped?"stopped":"STILL RUNNING",note:l.note}));if(process.stdout.write(`${u(a)}
163
- `),s.some((l)=>l.service&&l.stopped))process.stdout.write(`
161
+ `),o;let s=[];for(let a of i)s.push(await Ua(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
162
+ `);else{let a=s.map((d)=>({label:Pr(d.agentId),value:d.stopped?"stopped":"STILL RUNNING",note:d.note}));if(process.stdout.write(`${C(a)}
163
+ `),s.some((d)=>d.service&&d.stopped))process.stdout.write(`
164
164
  Services are disabled as well as unloaded, so they stay stopped across a reboot.
165
- Start one again with \`${t.slug} daemon start <agent>\`.
166
- `);if(s.some((l)=>l.forced===!0))process.stdout.write(`
165
+ Start one again with \`${A.slug} daemon start <agent>\`.
166
+ `);if(s.some((d)=>d.forced===!0))process.stdout.write(`
167
167
  Something had to be killed rather than asked. A forced stop skips the runtime's own
168
168
  cleanup, so a command the agent had left running in the background may still be alive —
169
169
  \`ps\` will show it if so.
170
- `)}return s.every((a)=>a.stopped)?o:d}async function Ua(e,n){let r=`${t.slug}.agent.`,i=new Map;for(let s of e?.labels(r)??[]){let a=s.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let s=await ne.open({path:n??G()});for(let a of await s.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 s.close()}catch{}return[...i.values()].sort((s,a)=>s.agentId.localeCompare(a.agentId))}async function La(e,n){let r=[];if(e.service&&n!==void 0)try{n.stop(tr(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 bn(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let s=await bn(e.pid,"SIGKILL",!0);return r.push(s?`pid ${e.pid} did not stop in ${Math.round(Pr/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:s,forced:!0,note:r.join(" · ")}}async function bn(e,n,r=!1){try{process.kill(r?-e:e,n)}catch(s){if(s.code==="ESRCH")return!0;if(r)try{process.kill(e,n)}catch{return!Z(e)}}let i=Date.now()+(n==="SIGKILL"?3000:Pr);while(Date.now()<i){if(!Z(e))return!0;await new Promise((s)=>setTimeout(s,Na))}return!Z(e)}function Ka(e){let n=[];if(e.service)n.push("background service");if(e.pid!==void 0)n.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${Rr(e.agentId)} — ${n.join(", ")}`}function Rr(e){return e===Ut?"(host, no agents)":e}function Ma(e){let n=F(e);if(n.id===void 0||n.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 n.id}async function Fr(e){let n=await ne.open({path:e.store??G()});try{if(e.prune===!0)return await Ba(e,n);if(e.all===!0)return await Wa(e,n);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 Ga(e.ref,e,n)}finally{await n.close()}}async function Ga(e,n,r){let i=await Lr(e,n,r),s=yr(i);if(s.length>0){let c=s[0];throw new A({code:c.code,message:c.message,hint:c.hint})}let a=$r(i),l=`${v(`removing ${e} will:`,!0)}
170
+ `)}return s.every((a)=>a.stopped)?o:E}async function Ka(e,t){let r=`${A.slug}.agent.`,i=new Map;for(let s of e?.labels(r)??[]){let a=s.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let s=await re.open({path:t??G()});for(let a of await s.leases.all()){if(a.pid===process.pid||!ee(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await s.close()}catch{}return[...i.values()].sort((s,a)=>s.agentId.localeCompare(a.agentId))}async function Ua(e,t){let r=[];if(e.service&&t!==void 0)try{t.stop(Ar(A.slug,e.agentId)),r.push("service disabled and unloaded")}catch(a){r.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:r.join(" · ")||"no process was running"};if(!ee(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await bn(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let s=await bn(e.pid,"SIGKILL",!0);return r.push(s?`pid ${e.pid} did not stop in ${Math.round(kr/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:s,forced:!0,note:r.join(" · ")}}async function bn(e,t,r=!1){try{process.kill(r?-e:e,t)}catch(s){if(s.code==="ESRCH")return!0;if(r)try{process.kill(e,t)}catch{return!ee(e)}}let i=Date.now()+(t==="SIGKILL"?3000:kr);while(Date.now()<i){if(!ee(e))return!0;await new Promise((s)=>setTimeout(s,Na))}return!ee(e)}function La(e){let t=[];if(e.service)t.push("background service");if(e.pid!==void 0)t.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${Pr(e.agentId)} — ${t.join(", ")}`}function Pr(e){return e===xt?"(host, no agents)":e}function Ma(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_stop_agent_id_missing",message:`${e} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${A.slug} stop\` with no argument to stop everything.`});return t.id}async function _r(e){let t=await re.open({path:e.store??G()});try{if(e.prune===!0)return await Ba(e,t);if(e.all===!0)return await Wa(e,t);if(e.ref===void 0)throw new n({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${A.slug} remove <name>\` takes a sandbox agent's name — the ones \`${A.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await Ga(e.ref,e,t)}finally{await t.close()}}async function Ga(e,t,r){let i=await Kr(e,t,r),s=yr(i);if(s.length>0){let l=s[0];throw new n({code:l.code,message:l.message,hint:l.hint})}let a=$r(i),d=`${L(`removing ${e} will:`,!0)}
171
171
  ${vr(i)}
172
172
 
173
- ${a.map((c)=>Q(c.detail)).join(`
173
+ ${a.map((l)=>w(l.detail)).join(`
174
174
  `)}
175
- `;if(n.dryRun===!0)return process.stdout.write(n.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
176
- `:`${l}
175
+ `;if(t.dryRun===!0)return process.stdout.write(t.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
176
+ `:`${d}
177
177
  Nothing was deleted — this was --dry-run.
178
- `),o;if(process.stdout.write(l),!await nt(n,e,"type the agent's name to confirm:"))return process.stdout.write(`
178
+ `),o;if(process.stdout.write(d),!await nt(t,e,"type the agent's name to confirm:"))return process.stdout.write(`
179
179
  Nothing was deleted.
180
- `),o;return await Ur(i,n,r)}async function Ur(e,n,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await $n({manifestPath:e.manifestPath,...n.exec===void 0?{}:{exec:n.exec},...n.platform===void 0?{}:{platform:n.platform}})!==o)return process.stderr.write(`
180
+ `),o;return await Fr(i,t,r)}async function Fr(e,t,r){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await $n({manifestPath:e.manifestPath,...t.exec===void 0?{}:{exec:t.exec},...t.platform===void 0?{}:{platform:t.platform}})!==o)return process.stderr.write(`
181
181
  Stopping ${e.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
182
- hint: check what is still running with \`${t.slug} stop --dry-run\`, then run remove again.
183
- `),d;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=Kr(n);try{s?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let s=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let a of e.logs)et(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(et(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),n.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
182
+ hint: check what is still running with \`${A.slug} stop --dry-run\`, then run remove again.
183
+ `),E;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=Ur(t);try{s?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let s=await r.purgeAgent(e.agentId);i.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let a of e.logs)et(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(et(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),t.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
184
184
  `),o;if(process.stdout.write(`
185
185
  ${e.ref} removed.
186
- ${u(i)}
186
+ ${C(i)}
187
187
  `),e.filesOnly)process.stdout.write(`
188
188
  Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
189
- `);return o}async function Wa(e,n){let r=Ae();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
190
- `),o;if(process.stdout.write(`${v(`removing every agent in ${q()}:`,!0)}
191
- ${r.map((s)=>Q(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).join(`
189
+ `);return o}async function Wa(e,t){let r=oe();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
190
+ `),o;if(process.stdout.write(`${L(`removing every agent in ${W()}:`,!0)}
191
+ ${r.map((s)=>w(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).join(`
192
192
  `)}
193
193
  `),e.dryRun===!0)return process.stdout.write(`
194
194
  Nothing was deleted — this was --dry-run.
195
195
  `),o;if(!await nt(e,"all",`type \`all\` to remove all ${r.length}:`))return process.stdout.write(`
196
196
  Nothing was deleted.
197
- `),o;let i=o;for(let s of r){let a=await Lr(s.ref,e,n),l=await Ur({...a,sharesIdWith:[]},e,n);if(l!==o)i=l}return i}async function Ba(e,n){let r=new Set(Ae().map((l)=>l.id??l.ref).filter((l)=>l!=="")),i=new Set((await n.agentIds()).filter((l)=>!r.has(l)));for(let l of Va())if(!r.has(l))i.add(l);let s=[];for(let l of[...i].sort())s.push({agentId:l,footprint:await n.agentFootprint(l),logs:Mr(l)});if(s.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
198
- `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${q()}.
199
- `),o;if(process.stdout.write(`${v("no sandbox directory claims these:",!0)}
200
- ${kr(s)}
197
+ `),o;let i=o;for(let s of r){let a=await Kr(s.ref,e,t),d=await Fr({...a,sharesIdWith:[]},e,t);if(d!==o)i=d}return i}async function Ba(e,t){let r=new Set(oe().map((d)=>d.id??d.ref).filter((d)=>d!=="")),i=new Set((await t.agentIds()).filter((d)=>!r.has(d)));for(let d of Va())if(!r.has(d))i.add(d);let s=[];for(let d of[...i].sort())s.push({agentId:d,footprint:await t.agentFootprint(d),logs:Lr(d)});if(s.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
198
+ `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${W()}.
199
+ `),o;if(process.stdout.write(`${L("no sandbox directory claims these:",!0)}
200
+ ${Sr(s)}
201
201
  `),e.dryRun===!0)return process.stdout.write(`
202
202
  Nothing was deleted — this was --dry-run.
203
203
  `),o;if(!await nt(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
204
204
  Nothing was deleted.
205
- `),o;let a=[];for(let l of s){let c=await n.purgeAgent(l.agentId);for(let m of l.logs)et(m.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:s.map((l)=>l.agentId)},null,2)}
205
+ `),o;let a=[];for(let d of s){let l=await t.purgeAgent(d.agentId);for(let u of d.logs)et(u.path,{force:!0});a.push({label:d.agentId,value:`${l.sessions} conversation(s), ${l.passages} passage(s), ${d.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:s.map((d)=>d.agentId)},null,2)}
206
206
  `:`
207
207
  pruned ${s.length} agent id(s).
208
- ${u(a)}
209
- `),o}async function Lr(e,n,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 ${q()} 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=Ae(),s=i.find((g)=>g.ref===e);if(s===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=s.id;if(a===void 0)try{a=F(s.manifestPath).id}catch{}let l=n.filesOnly===!0||a===void 0,c=a??e,m=await r.agentFootprint(c),w=m.lease?await r.leases.get(c):void 0,f=Kr(n),h=tr(t.slug,c);return{ref:e,agentId:c,manifestPath:s.manifestPath,dir:s.dir,files:qa(s.dir),footprint:m,logs:Mr(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}}:{},...f?.state(h).installed===!0?{service:h}:{},filesOnly:l}}function Kr(e){let n=e.platform??process.platform;if(n!=="darwin")return;return rn(n,{home:Ha(),uid:process.getuid?.()??0,envPrefix:t.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function qa(e){let n=0,r=0,i=(s)=>{let a;try{a=Tr(s)}catch{return}for(let l of a){let c=Nr(s,l);try{let m=_r(c);if(m.isDirectory()){i(c);continue}n+=1,r+=m.size}catch{}}};return i(e),{count:n,bytes:r}}function Mr(e){let n=pn(e),r=[];for(let i of[n.out,n.err])try{if(!Da(i))continue;r.push({path:i,bytes:_r(i).size})}catch{}return r}function Va(){let e;try{e=Tr(Nr(we(),"logs"))}catch{return[]}let n=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))n.add(r.slice(0,-i.length));return[...n]}async function nt(e,n,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,n)}async function Hr(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 n=me(e.manifestPath),r=await NA(e.manifestPath,e.store),i,s,a=o;switch(r.kind){case"reloaded":i="reloaded",s=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",s=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",s=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=d;break;case"failed":i="not reloaded",s=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=d;break;case"no-host":{let l=await Ve(e.store);if(l===void 0)throw new A({code:"cli_restart_nothing_running",message:`Nothing is hosting ${n}, and no server is running to adopt it.`,hint:`\`${t.slug} serve ${n}\` runs it in this terminal; \`${t.slug} daemon install\` keeps a server running that hosts every agent. Then \`${t.slug} restart ${n}\` reloads it in place.`});let c=await OA(l,e.manifestPath,e.store);if(c.ok)i="started",s=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",s=`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:n,result:r,ok:a===o},null,2)}
210
- `);else process.stdout.write(`${u([{label:n,value:i,note:s}])}
211
- `);return a}import{randomBytes as st}from"node:crypto";import{existsSync as nd}from"node:fs";import{createInterface as Zr}from"node:readline";class ge extends Error{code;hint;field;details;status;request;constructor(e,n={}){super([e.message,...(e.details??[]).map((r)=>` - ${r.field===void 0?"":`${r.field}: `}${r.message}`),...e.hint===void 0?[]:[` hint: ${e.hint}`]].join(`
212
- `));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=n.status,this.request=n.method===void 0||n.path===void 0?void 0:{method:n.method,path:n.path},n.cause!==void 0)this.cause=n.cause}}function Ja(e,n){let r=e instanceof Error?e.message:String(e);return new ge({code:"transport_failed",message:`${n.method} ${n.path} did not reach ${n.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."},{...n,cause:e})}async function Xa(e,n){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:`${n.method} ${n.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,...n})}var Wr=new Set(Jt);async function*Br(e){for await(let n of Er(za(e))){if(n.event===void 0||n.data==="")continue;let r;try{r=JSON.parse(n.data)}catch{continue}yield{name:n.event,data:r}}}async function*za(e){let n=e.getReader();try{while(!0){let{done:r,value:i}=await n.read();if(r)return;if(i!==void 0)yield i}}finally{n.releaseLock()}}async function*Ya(e){for await(let{name:n,data:r}of Br(e)){if(Wr.has(n)){yield{kind:"event",event:r};continue}let i=r??{};switch(n){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Qa(e){for await(let{name:n,data:r}of Br(e)){if(Wr.has(n)){yield{kind:"event",event:r};continue}if(n==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*Za(e,n={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&n.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 qr(e){let n=e.baseUrl.length;while(n>0&&e.baseUrl[n-1]==="/")n-=1;let r=e.baseUrl.slice(0,n),i=e.fetch??fetch,s=(f={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...f});async function a(f,h,g={}){let b;try{b=await i(`${r}${h}`,{method:f,headers:s({...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(x){throw Ja(x,{method:f,path:h,baseUrl:r})}if(!b.ok)throw await Xa(b,{method:f,path:h});return b}async function l(f,h,g){return await(await a(f,h,g??{})).json()}async function c(f,h){let g=await a("GET",f,{accept:"text/event-stream",...h===void 0?{}:{signal:h}});if(g.body===null)throw new ge({code:"no_response_body",message:`GET ${f} 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:f});return g.body}function m(f,h,g,b={}){let x=(S)=>{let N=new URLSearchParams;if(S?.chunks===!0)N.set("chunks","true");if(S?.children===!0)N.set("children","true");let H=N.toString();return H===""?"":`?${H}`},R={turnId:h,sessionKey:g,replayed:b.replayed===!0,async*stream(S){let N=await c(`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}/stream${x(S)}`,S?.signal);yield*Ya(N)},async*tokens(S){yield*Za(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(f)}/turns/${encodeURIComponent(h)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(f)}/turns/${encodeURIComponent(h)}/stop`)}};return R}function w(f){let h=(g)=>`/v1/agents/${encodeURIComponent(f)}${g}`;return{id:f,async send(g,b){let x=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 m(f,x.turnId,x.sessionKey,{replayed:x.replayed===!0})},turn:(g)=>m(f,g,""),describe:()=>l("GET",h("")),tools:()=>l("GET",h("/tools")),skills:()=>l("GET",h("/skills")),sessions:()=>l("GET",h("/sessions")),messages:(g,b)=>{let x=new URLSearchParams;if(b?.before!==void 0)x.set("before",String(b.before));if(b?.limit!==void 0)x.set("limit",String(b.limit));let R=x.size===0?"":`?${x.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${Gr(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 x=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/turns${x}`))},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)}`))},refreshTools:(g)=>l("POST",h("/tools/refresh"),{body:g?.providers===void 0?{}:{providers:g.providers}}),previewSchedule:(g)=>{let b=new URLSearchParams({kind:g.kind,expr:g.expr});if(g.timezone!==void 0)b.set("timezone",g.timezone);if(g.count!==void 0)b.set("count",String(g.count));return l("GET",h(`/schedules/preview?${b.toString()}`))},runSchedule:(g)=>l("POST",h(`/schedules/${encodeURIComponent(g)}/run`),{body:{}}),config:()=>l("GET",h("/config")),setConfig:(g,b,x)=>l("PATCH",h("/config"),{body:{path:g,value:b,...x?.confirm===void 0?{}:{confirm:x.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}}),rotateSession:(g)=>l("POST",h("/sessions/rotate"),{body:g?.from===void 0?{}:{from:g.from}}),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")),assignment:()=>l("GET",h("/assignee")),workspaceFiles:()=>l("GET",h("/workspace")),workspaceFile:(g)=>l("GET",h(`/workspace/${encodeURIComponent(g)}`)),putWorkspaceFile:(g,b)=>l("PUT",h(`/workspace/${encodeURIComponent(g)}`),{body:{content:b}}),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}}}),setVars:(g)=>l("PATCH",h("/vars"),{body:{vars:g}}),vars:()=>l("GET",h("/vars")),deliver:(g)=>l("POST",h("/deliveries"),{body:g}),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 x=b.size===0?"":`?${b.toString()}`;return l("GET",h(`/context${x}`))}}}return{agent:w,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(f){if(f instanceof ge&&f.status===503)return!1;throw f}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(f)=>l("POST","/v1/keys",{body:f}),revokeKey:(f)=>l("DELETE",`/v1/keys/${encodeURIComponent(f)}`),deleteAgent:(f,h)=>l("DELETE",`/v1/agents/${encodeURIComponent(f)}?confirm=${encodeURIComponent(h)}`),backup:async(f)=>(await a("GET",`/v1/backup${f===void 0||f.length===0?"":`?include=${f.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(f)=>l("DELETE",`/v1/participants/${encodeURIComponent(f)}`),createAgent:(f)=>l("POST","/v1/agents",{body:{answers:f}}),usage:(f)=>l("GET",`/v1/usage${Gr(f)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(f)=>l("POST","/v1/participants",{body:f}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(f)=>l("POST","/v1/conversations",{body:f}),conversation:(f)=>l("GET",`/v1/conversations/${encodeURIComponent(f)}`),setMembers:(f,h)=>l("PATCH",`/v1/conversations/${encodeURIComponent(f)}/members`,{body:h}),postMessage:(f,h)=>l("POST",`/v1/conversations/${encodeURIComponent(f)}/messages`,{body:h}),conversationMessages:(f,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(f)}/messages${b}`)},setPresence:(f,h)=>l("PUT",`/v1/participants/${encodeURIComponent(f)}/presence`,{body:{presence:h}}),actions:async(f={})=>(await l("GET",`/v1/actions${f.status===void 0?"":`?status=${f.status}`}`)).actions,decideAction:(f,h)=>l("POST",`/v1/actions/${encodeURIComponent(f)}`,{body:{approve:h}}),addNote:(f)=>l("POST","/v1/memory/notes",{body:f}),notes:async(f)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(f)}`)).notes,deleteNote:(f)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(f)}`),memoryReads:async(f)=>(await l("GET",`/v1/participants/${encodeURIComponent(f)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(f,h)=>l("PUT",`/v1/projects/${encodeURIComponent(f)}`,{body:h}),deleteProject:(f)=>l("DELETE",`/v1/projects/${encodeURIComponent(f)}`),setSpaceWriter:(f)=>l("PUT","/v1/memory/space/writer",{body:{writer:f}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(f)=>l("POST","/v1/webhooks",{body:f}),deleteWebhook:(f)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(f)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(f)=>l("POST","/v1/agents",{body:f}),async*events(f){let h=new URLSearchParams;if(f?.agentId!==void 0)h.set("agentId",f.agentId);if(f?.types!==void 0&&f.types.length>0)h.set("types",f.types.join(","));if(f?.chunks===!0)h.set("chunks","true");let g=h.size===0?"":`?${h.toString()}`,b=await c(`/v1/events${g}`,f?.signal);yield*Qa(b)}}}function Gr(e){let n=new URLSearchParams;if(e?.by!==void 0)n.set("by",e.by.join(","));if(e?.from!==void 0)n.set("from",e.from);if(e?.to!==void 0)n.set("to",e.to);return n.size===0?"":`?${n.toString()}`}function Ke(e,n){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let s=hi(i,n);if(s==="")continue;r.push({role:i.role,text:s})}return r}function Vr(e){let n=e.ref??"<your agent>",r=`${t.slug} run ${n} --session ${e.sessionKey}`;return`
213
- ${Ia}Resume this session with:
214
- ${r}${ko}
215
- `}function tt(e,n){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 n===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${n}, still in the store. /sessions goes back to it.`}}function ed(e){return e==="nlt"?pr():Cr()}function Xr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(n)=>e.bus.on("*",n,{chunks:!0}),send:(n,r)=>e.send(n,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,ownConversation:e.ownConversation,rotateSession:e.rotateSession,tools:async()=>Xo(e.agent),context:e.context,close:async()=>{}}}function zr(e){let n=e.client.agent(e.agentId),r=new Set,i=new AbortController,s,a=()=>{if(s!==void 0)return;s=(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 m=!1,w,f=()=>{if(m=!0,w!==void 0)n.turn(w).stop().catch(()=>{})};c.signal.addEventListener("abort",f,{once:!0});let h,g=new Promise((b)=>{let x=(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(x),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(x),a()});try{if(w=(await n.send(l,{sessionKey:c.sessionKey})).turnId,m)n.turn(w).stop().catch(()=>{});return await g}finally{c.signal.removeEventListener("abort",f)}},streamFilter:()=>ed(e.description.dialect),history:async(l)=>{let c=await n.messages(l);return Ke([...c.messages].reverse().map((m)=>({role:m.role,content:m.content,...m.origin===void 0?{}:{origin:m.origin}})),e.description.dialect)},sessions:()=>n.sessions(),clearSession:async(l)=>{await n.clearSession(l)},ownConversation:async()=>(await n.sessions()).find((l)=>l.head!==!1&&l.sessionKey.startsWith("owner:"))?.sessionKey,rotateSession:async()=>{try{return(await n.rotateSession()).sessionKey}catch{return}},tools:async()=>{let l=await n.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 n.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 n.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Qr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function td(e,n,r,i,s,a=[],l){let c=e.describe(),[m,w]=await Promise.all([e.turns(n,1),e.store.messages.count(e.id,n)]),f=[`${t.name} ${J} · ${c.id} · ${c.model}`,`session ${n} · ${w} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],h=tt(s,l);if(h!==void 0)f.push(h);if(m[0]?.errorCode==="turn_abandoned")f.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])f.push(`note: ${g.message}
216
- ${g.hint}`);if(a.length>0)f.push(`note: ${a.join(", ")} in the .env here ${a.length===1?"was":"were"} ignored — this agent's own .env sets ${a.length===1?"it":"them"}.
217
- A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return f}async function ot(e){let n=e.once!==void 0,r=it({json:!1,plain:e.plain===!0,oneShot:n}),{mode:i}=r;if(e.manifestPath===void 0){let R=await rd(i,r.because,e);if(typeof R==="number")return R;return ot({...e,manifestPath:R})}let s=pi();if(e.store===void 0&&e.ephemeral!==!0&&nd(s))process.stdout.write(`note: a session store exists at ${s} from an earlier version — pass --store ${s} to keep using it; the default is now ${G()}
218
- `);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},m={current:e.sessionKey},w={current:!1},f={current:void 0},h=e.quiet===!0,g="first",b={current:void 0},x=e.ephemeral===!0?void 0:Qr(await qe(me(e.manifestPath),e.store));if(x!==void 0)return await dd({...e,host:x,mode:i==="rich"?"rich":"plain",quiet:h,oneShot:n,reader:l,draft:c,session:m,random:st});for(;;){let R=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=R;let S=R.list()[0];if(S===void 0)throw Error("The manifest produced no agent.");if(m.current===void 0||m.current===""){let K=await so({list:async()=>lo(await S.store.sessions.list(S.id)),mode:i,asked:m.current,wantsContinue:e.continueSession===!0,random:st});if(typeof K==="number")return await R.stop("cli-exit"),K;if(m.current=K.sessionKey,w.current=K.fresh,K.fresh)m.current=await no(S)??K.sessionKey}if(g==="new"){let K=await S.rotateSession({source:"repl"});if(K!==void 0)m.current=K.sessionKey}let N=m.current,H=S.roles.main.capabilities.thinking!=="none",P=e.noReasoning===!0?!1:H,T=h||n?[]:await td(S,N,R.store.location,g==="first"?R.boot.processMs:R.boot.bootMs,g,Js([e.manifestPath]),f.current),O=i==="rich"&&!h&&!n?Ke(await S.history(N),S.describe().dialect):[],C=Xr({agent:S,bus:R.bus,send:(K,ee)=>S.send(K,ee),history:async(K)=>Ke(await S.history(K),S.describe().dialect),sessions:async()=>{let K=await S.store.sessions.heads(S.id);return(await S.store.sessions.list(S.id)).map((ee)=>({...ee,head:ii(ee.sessionKey,K)}))},clearSession:async(K)=>{await S.clearSession(K)},ownConversation:()=>no(S),rotateSession:async()=>(await S.rotateSession({source:"repl"}))?.sessionKey,context:async(K)=>ld(S,K),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]}}),L={...e,source:C,embedded:{agent:S,runtime:R},sessionKey:N,banner:T,prior:O,quiet:h,reader:l,draft:c,showReasoning:P,freshSession:w.current,switchTo:b,random:st},B=i==="rich"?await ro(L):await io(L);if(await R.stop(B===$e?"restart":"cli-exit"),B!==$e)return B;if(b.current===void 0)g="restart";else g=b.current.reason,f.current=N,m.current=b.current.key,b.current=void 0;w.current=!1}}function sd(e,n){let r=[];for(let i of e)Kt({action:"install",manifestPath:n,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var $e=Symbol("restart");async function rd(e,n,r){let i=Ae();if(i.length===0){if(e==="rich"){let f=await Ln({plain:r.plain===!0});if(f.kind==="aborted")return process.stdout.write(`nothing to run
219
- `),o;if(f.kind==="failed")return f.code;return f.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
220
- `),i[0].manifestPath;if(e!=="rich"){for(let f of i)process.stdout.write(`${f.ref} ${f.problem??f.modelId??"?"} ${f.dir}
221
- `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${n})
222
- `),d}let[{render:s},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-j7txnm7w.js")]),c={kind:"quit"};oo();let m=s(a(l,{title:`${t.name} ${J}`,agents:i,onDone:(f)=>{c=f}}),{exitOnCtrlC:!1,...Ue(r.noEnhancedKeys)});U(()=>m.unmount()),await m.waitUntilExit(),m.unmount();let w=c;if(w.kind==="quit")return process.stdout.write(`nothing run
223
- `),o;if(w.kind==="create"){let f=await Ln({plain:r.plain===!0});if(f.kind==="aborted")return process.stdout.write(`nothing to run
224
- `),o;if(f.kind==="failed")return f.code;return f.manifestPath}return w.manifestPath}async function no(e){let r=await e.resolveSessionKey("local:-",{source:"repl"});return r==="local:-"?void 0:r}async function so(e){let n=()=>({sessionKey:$o(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=od(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
225
- `),n();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let r=await e.list();if(r.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
226
- `),n();if(e.mode!=="rich"){for(let s of[...r].sort(vn))process.stdout.write(`${s.sessionKey} ${s.messages} ${s.turns} ${s.lastActivityAt}
208
+ ${C(a)}
209
+ `),o}async function Kr(e,t,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new n({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${W()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${A.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let i=oe(),s=i.find((m)=>m.ref===e);if(s===void 0){let m=i.map((g)=>g.ref);throw new n({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${m.length===0?", which is empty":""}.`,hint:m.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${m.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=s.id;if(a===void 0)try{a=U(s.manifestPath).id}catch{}let d=t.filesOnly===!0||a===void 0,l=a??e,u=await r.agentFootprint(l),p=u.lease?await r.leases.get(l):void 0,c=Ur(t),f=Ar(A.slug,l);return{ref:e,agentId:l,manifestPath:s.manifestPath,dir:s.dir,files:qa(s.dir),footprint:u,logs:Lr(l),sharesIdWith:i.filter((m)=>m.ref!==e&&(m.id??"")===l).map((m)=>m.ref),...p!==void 0&&ee(p.pid)?{running:{pid:p.pid,mode:p.mode}}:{},...c?.state(f).installed===!0?{service:f}:{},filesOnly:d}}function Ur(e){let t=e.platform??process.platform;if(t!=="darwin")return;return sn(t,{home:Ha(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function qa(e){let t=0,r=0,i=(s)=>{let a;try{a=Rr(s)}catch{return}for(let d of a){let l=Tr(s,d);try{let u=xr(l);if(u.isDirectory()){i(l);continue}t+=1,r+=u.size}catch{}}};return i(e),{count:t,bytes:r}}function Lr(e){let t=fn(e),r=[];for(let i of[t.out,t.err])try{if(!Da(i))continue;r.push({path:i,bytes:xr(i).size})}catch{}return r}function Va(){let e;try{e=Rr(Tr(Oe(),"logs"))}catch{return[]}let t=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))t.add(r.slice(0,-i.length));return[...t]}async function nt(e,t,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,t)}async function Mr(e){if(e.manifestPath===void 0)return await Ut({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let t=De(e.manifestPath),r=await MA(e.manifestPath,e.store),i,s,a=o;switch(r.kind){case"reloaded":i="reloaded",s=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",s=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",s=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=E;break;case"failed":i="not reloaded",s=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=E;break;case"no-host":{let d=await ze(e.store);if(d===void 0)throw new n({code:"cli_restart_nothing_running",message:`Nothing is hosting ${t}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${t}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${t}\` reloads it in place.`});let l=await NA(d,e.manifestPath,e.store);if(l.ok)i="started",s=`nothing was hosting it — adopted by pid ${d.pid}`;else i="not started",s=`pid ${d.pid} did not adopt it${l.detail===void 0?"":`: ${l.detail}`}`,a=E;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:t,result:r,ok:a===o},null,2)}
210
+ `);else process.stdout.write(`${C([{label:t,value:i,note:s}])}
211
+ `);return a}import{randomBytes as st}from"node:crypto";import{existsSync as nd}from"node:fs";import{resolve as Zr}from"node:path";import{createInterface as eo}from"node:readline";class fe extends Error{code;hint;field;details;status;request;constructor(e,t={}){super([e.message,...(e.details??[]).map((r)=>` - ${r.field===void 0?"":`${r.field}: `}${r.message}`),...e.hint===void 0?[]:[` hint: ${e.hint}`]].join(`
212
+ `));if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.details=e.details??[],this.status=t.status,this.request=t.method===void 0||t.path===void 0?void 0:{method:t.method,path:t.path},t.cause!==void 0)this.cause=t.cause}}function Ja(e,t){let r=e instanceof Error?e.message:String(e);return new fe({code:"transport_failed",message:`${t.method} ${t.path} did not reach ${t.baseUrl}: ${r}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...t,cause:e})}async function Xa(e,t){let r;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")r={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new fe(r??{code:`http_${e.status}`,message:`${t.method} ${t.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...t})}var Wr=new Set(qt);async function*Br(e){for await(let t of pr(za(e))){if(t.event===void 0||t.data==="")continue;let r;try{r=JSON.parse(t.data)}catch{continue}yield{name:t.event,data:r}}}async function*za(e){let t=e.getReader();try{while(!0){let{done:r,value:i}=await t.read();if(r)return;if(i!==void 0)yield i}}finally{t.releaseLock()}}async function*Ya(e){for await(let{name:t,data:r}of Br(e)){if(Wr.has(t)){yield{kind:"event",event:r};continue}let i=r??{};switch(t){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Qa(e){for await(let{name:t,data:r}of Br(e)){if(Wr.has(t)){yield{kind:"event",event:r};continue}if(t==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*Za(e,t={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&t.allowTruncated!==!0)throw new fe({code:"replay_truncated",message:`This turn's replay is missing its oldest ${r.report.dropped} event(s), so the text reconstructed from it would be incomplete.`,hint:"Read the finished text from GET /v1/agents/:id/turns/:turnId, or pass { allowTruncated: true } to accept a fragment. Streaming from the start of a turn is never truncated — this only happens when reattaching to one that has already produced more events than the buffer holds."});if(r.kind==="unavailable")throw new fe({code:"turn_not_observable",message:`Turn ${r.turnId} is recorded as running but is not observable here: ${r.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(r.kind!=="event")continue;if(r.event.type!=="model.chunk")continue;let i=r.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function Vr(e){let t=e.baseUrl.length;while(t>0&&e.baseUrl[t-1]==="/")t-=1;let r=e.baseUrl.slice(0,t),i=e.fetch??fetch,s=(c={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...c});async function a(c,f,m={}){let g;try{g=await i(`${r}${f}`,{method:c,headers:s({...m.body===void 0?{}:{"content-type":"application/json"},...m.accept===void 0?{}:{accept:m.accept},...m.headers}),...m.body===void 0?{}:{body:JSON.stringify(m.body)},...m.signal===void 0?{}:{signal:m.signal}})}catch(R){throw Ja(R,{method:c,path:f,baseUrl:r})}if(!g.ok)throw await Xa(g,{method:c,path:f});return g}async function d(c,f,m){return await(await a(c,f,m??{})).json()}async function l(c,f){let m=await a("GET",c,{accept:"text/event-stream",...f===void 0?{}:{signal:f}});if(m.body===null)throw new fe({code:"no_response_body",message:`GET ${c} returned ${m.status} with no body to read.`,hint:"An SSE route always has a body. A missing one means something between you and the server buffered the response — commonly a proxy without streaming enabled."},{status:m.status,method:"GET",path:c});return m.body}function u(c,f,m,g={}){let R=(y)=>{let j=new URLSearchParams;if(y?.chunks===!0)j.set("chunks","true");if(y?.children===!0)j.set("children","true");let D=j.toString();return D===""?"":`?${D}`},P={turnId:f,sessionKey:m,replayed:g.replayed===!0,async*stream(y){let j=await l(`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stream${R(y)}`,y?.signal);yield*Ya(j)},async*tokens(y){yield*Za(P.stream({chunks:!0,...y,children:!1}),{...y?.allowTruncated===void 0?{}:{allowTruncated:y.allowTruncated}})},async text(){for await(let y of P.stream()){if(y.kind==="ended")break;if(y.kind==="unavailable")break;if(y.kind==="event"&&y.event.type==="turn.end")break}return(await P.get()).text},get:()=>d("GET",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(c)}/turns/${encodeURIComponent(f)}/stop`)}};return P}function p(c){let f=(m)=>`/v1/agents/${encodeURIComponent(c)}${m}`;return{id:c,async send(m,g){let R=await d("POST",f("/messages"),{body:{text:m,...g?.sessionKey===void 0?{}:{sessionKey:g.sessionKey},...g?.deliver===void 0?{}:{deliver:g.deliver},...g?.from===void 0?{}:{from:g.from},...g?.images===void 0?{}:{images:g.images},...g?.runtimeNote===void 0?{}:{runtimeNote:g.runtimeNote},...g?.chunks===!0?{chunks:!0}:{},...g?.role===void 0?{}:{role:g.role}},...g?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":g.idempotencyKey}},...g?.signal===void 0?{}:{signal:g.signal}});return u(c,R.turnId,R.sessionKey,{replayed:R.replayed===!0})},turn:(m)=>u(c,m,""),describe:()=>d("GET",f("")),tools:()=>d("GET",f("/tools")),skills:()=>d("GET",f("/skills")),sessions:()=>d("GET",f("/sessions")),messages:(m,g)=>{let R=new URLSearchParams;if(g?.before!==void 0)R.set("before",String(g.before));if(g?.limit!==void 0)R.set("limit",String(g.limit));let P=R.size===0?"":`?${R.toString()}`;return d("GET",f(`/sessions/${encodeURIComponent(m)}/messages${P}`))},clearSession:(m)=>d("DELETE",f(`/sessions/${encodeURIComponent(m)}`)),reload:()=>d("POST",f("/reload"),{body:{}}),usage:(m)=>d("GET",f(`/usage${Gr(m)}`)),turns:(m)=>{let g=new URLSearchParams;if(m?.limit!==void 0)g.set("limit",String(m.limit));if(m?.before!==void 0)g.set("before",String(m.before));let R=g.size===0?"":`?${g.toString()}`;return d("GET",f(`/turns${R}`))},secrets:async()=>(await d("GET",f("/secrets"))).secrets,setSecrets:(m)=>d("PUT",f("/secrets"),{body:{values:m}}),schedules:async()=>(await d("GET",f("/schedules"))).schedules,approvals:async()=>(await d("GET",f("/approvals"))).approvals,createSchedule:(m)=>d("POST",f("/schedules"),{body:m}),updateSchedule:(m,g)=>d("PATCH",f(`/schedules/${encodeURIComponent(m)}`),{body:g}),deleteSchedule:async(m)=>{await d("DELETE",f(`/schedules/${encodeURIComponent(m)}`))},refreshTools:(m)=>d("POST",f("/tools/refresh"),{body:m?.providers===void 0?{}:{providers:m.providers}}),previewSchedule:(m)=>{let g=new URLSearchParams({kind:m.kind,expr:m.expr});if(m.timezone!==void 0)g.set("timezone",m.timezone);if(m.count!==void 0)g.set("count",String(m.count));return d("GET",f(`/schedules/preview?${g.toString()}`))},runSchedule:(m)=>d("POST",f(`/schedules/${encodeURIComponent(m)}/run`),{body:{}}),config:()=>d("GET",f("/config")),setConfig:(m,g,R)=>d("PATCH",f("/config"),{body:{path:m,value:g,...R?.confirm===void 0?{}:{confirm:R.confirm}}}),removeConfig:(m,g)=>d("PATCH",f("/config"),{body:{path:m,remove:!0,...g?.confirm===void 0?{}:{confirm:g.confirm}}}),setConfigs:(m)=>d("PATCH",f("/config"),{body:{changes:m.map((g)=>({...g}))}}),setChannel:(m,g)=>d("PATCH",f(`/channels/${encodeURIComponent(m)}`),{body:{...g}}),unpairChannel:(m)=>d("POST",f(`/channels/${encodeURIComponent(m)}/unpair`)),session:(m)=>d("GET",f(`/sessions/${encodeURIComponent(m)}`)),setPhase:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/phase`),{body:{phase:g}}),setRecall:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/recall`),{body:{recall:g}}),resolveSessionKey:async(m)=>(await d("POST",f("/sessions/resolve"),{body:{sessionKey:m}})).sessionKey,compactSession:(m,g)=>d("POST",f(`/sessions/${encodeURIComponent(m)}/compact`),{body:g?.keepTurns===void 0?{}:{keepTurns:g.keepTurns}}),rotateSession:(m)=>d("POST",f("/sessions/rotate"),{body:m?.from===void 0?{}:{from:m.from}}),approve:async(m,g)=>{await d("POST",f(`/approvals/${encodeURIComponent(m)}`),{body:{granted:g}})},stop:(m)=>d("POST",f("/stop"),{body:m===void 0?{}:{reason:m}}),start:()=>d("POST",f("/start"),{body:{}}),assign:(m)=>d("PUT",f("/assignee"),{body:{participantId:m}}),unassign:()=>d("DELETE",f("/assignee")),assignment:()=>d("GET",f("/assignee")),workspaceFiles:()=>d("GET",f("/workspace")),workspaceFile:(m)=>d("GET",f(`/workspace/${encodeURIComponent(m)}`)),putWorkspaceFile:(m,g)=>d("PUT",f(`/workspace/${encodeURIComponent(m)}`),{body:{content:g}}),exportBundle:(m)=>d("GET",f(`/export${m===void 0?"":`?paths=${encodeURIComponent(m.join(","))}`}`)),importBundle:(m,g)=>d("POST",f("/import"),{body:{bundle:m,...g===void 0?{}:{mode:g}}}),setVars:(m)=>d("PATCH",f("/vars"),{body:{vars:m}}),vars:()=>d("GET",f("/vars")),deliver:(m)=>d("POST",f("/deliveries"),{body:m}),context:(m)=>{let g=new URLSearchParams;if(m?.sessionKey!==void 0)g.set("sessionKey",m.sessionKey);if(m?.input!==void 0)g.set("input",m.input);let R=g.size===0?"":`?${g.toString()}`;return d("GET",f(`/context${R}`))}}}return{agent:p,agents:()=>d("GET","/v1/agents"),health:()=>d("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(c){if(c instanceof fe&&c.status===503)return!1;throw c}},provision:()=>d("GET","/v1/provision"),keys:()=>d("GET","/v1/keys"),createKey:(c)=>d("POST","/v1/keys",{body:c}),revokeKey:(c)=>d("DELETE",`/v1/keys/${encodeURIComponent(c)}`),deleteAgent:(c,f)=>d("DELETE",`/v1/agents/${encodeURIComponent(c)}?confirm=${encodeURIComponent(f)}`),backup:async(c)=>(await a("GET",`/v1/backup${c===void 0||c.length===0?"":`?include=${c.join(",")}`}`,{accept:"application/gzip"})).blob(),deleteParticipant:(c)=>d("DELETE",`/v1/participants/${encodeURIComponent(c)}`),createAgent:(c)=>d("POST","/v1/agents",{body:{answers:c}}),usage:(c)=>d("GET",`/v1/usage${Gr(c)}`),activity:()=>d("GET","/v1/activity"),participants:async()=>(await d("GET","/v1/participants")).participants,registerParticipant:(c)=>d("POST","/v1/participants",{body:c}),conversations:async()=>(await d("GET","/v1/conversations")).conversations,createConversation:(c)=>d("POST","/v1/conversations",{body:c}),conversation:(c)=>d("GET",`/v1/conversations/${encodeURIComponent(c)}`),setMembers:(c,f)=>d("PATCH",`/v1/conversations/${encodeURIComponent(c)}/members`,{body:f}),postMessage:(c,f)=>d("POST",`/v1/conversations/${encodeURIComponent(c)}/messages`,{body:f}),conversationMessages:(c,f={})=>{let m=new URLSearchParams;if(f.after!==void 0)m.set("after",String(f.after));if(f.limit!==void 0)m.set("limit",String(f.limit));let g=m.size===0?"":`?${m}`;return d("GET",`/v1/conversations/${encodeURIComponent(c)}/messages${g}`)},setPresence:(c,f)=>d("PUT",`/v1/participants/${encodeURIComponent(c)}/presence`,{body:{presence:f}}),actions:async(c={})=>(await d("GET",`/v1/actions${c.status===void 0?"":`?status=${c.status}`}`)).actions,decideAction:(c,f)=>d("POST",`/v1/actions/${encodeURIComponent(c)}`,{body:{approve:f}}),addNote:(c)=>d("POST","/v1/memory/notes",{body:c}),notes:async(c)=>(await d("GET",`/v1/memory/notes?scope=${encodeURIComponent(c)}`)).notes,deleteNote:(c)=>d("DELETE",`/v1/memory/notes/${encodeURIComponent(c)}`),memoryReads:async(c)=>(await d("GET",`/v1/participants/${encodeURIComponent(c)}/memory/reads`)).reads,projects:async()=>(await d("GET","/v1/projects")).projects,putProject:(c,f)=>d("PUT",`/v1/projects/${encodeURIComponent(c)}`,{body:f}),deleteProject:(c)=>d("DELETE",`/v1/projects/${encodeURIComponent(c)}`),setSpaceWriter:(c)=>d("PUT","/v1/memory/space/writer",{body:{writer:c}}),webhooks:async()=>(await d("GET","/v1/webhooks")).webhooks,createWebhook:(c)=>d("POST","/v1/webhooks",{body:c}),deleteWebhook:(c)=>d("DELETE",`/v1/webhooks/${encodeURIComponent(c)}`),templates:async()=>(await d("GET","/v1/templates")).templates,createAgentFromTemplate:(c)=>d("POST","/v1/agents",{body:c}),async*events(c){let f=new URLSearchParams;if(c?.agentId!==void 0)f.set("agentId",c.agentId);if(c?.types!==void 0&&c.types.length>0)f.set("types",c.types.join(","));if(c?.chunks===!0)f.set("chunks","true");let m=f.size===0?"":`?${f.toString()}`,g=await l(`/v1/events${m}`,c?.signal);yield*Qa(g)}}}function Gr(e){let t=new URLSearchParams;if(e?.by!==void 0)t.set("by",e.by.join(","));if(e?.from!==void 0)t.set("from",e.from);if(e?.to!==void 0)t.set("to",e.to);return t.size===0?"":`?${t.toString()}`}function Te(e,t){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let s=Bi(i,t);if(s==="")continue;r.push({role:i.role,text:s})}return r}function Xr(e){let t=e.ref??"<your agent>",r=`${A.slug} run ${t} --session ${e.sessionKey}`;return`
213
+ ${da}Resume this session with:
214
+ ${r}${vo}
215
+ `}function tt(e,t){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return t===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${t}, still in the store. /sessions goes back to it.`}}function ed(e){return e==="nlt"?fr():Cr()}function zr(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(t)=>e.bus.on("*",t,{chunks:!0}),send:(t,r)=>e.send(t,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,ownConversation:e.ownConversation,resolveSessionKey:e.resolveSessionKey,rotateSession:e.rotateSession,tools:async()=>er(e.agent),context:e.context,close:async()=>{}}}function Yr(e){let t=e.client.agent(e.agentId),r=new Set,i=new AbortController,s,a=()=>{if(s!==void 0)return;s=(async()=>{for await(let d of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(d.kind!=="event"||d.event===void 0)continue;for(let l of r)l(d.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(d)=>(r.add(d),a(),()=>r.delete(d)),send:async(d,l)=>{let u=!1,p,c=()=>{if(u=!0,p!==void 0)t.turn(p).stop().catch(()=>{})};l.signal.addEventListener("abort",c,{once:!0});let f,m=new Promise((g)=>{let R=(P)=>{if(p!==void 0&&P.turnId!==void 0&&P.turnId!==p)return;if(P.type==="error"){f=P.data;return}if(P.type!=="turn.end")return;r.delete(R),g({text:"",reason:P.data.reason,steps:P.data.steps,durationMs:P.data.durationMs,tokens:P.data.tokens,...f===void 0?{}:{error:f}})};r.add(R),a()});try{if(p=(await t.send(d,{sessionKey:l.sessionKey})).turnId,u)t.turn(p).stop().catch(()=>{});return await m}finally{l.signal.removeEventListener("abort",c)}},streamFilter:()=>ed(e.description.dialect),history:async(d)=>{let l=await t.messages(d);return Te([...l.messages].reverse().map((u)=>({role:u.role,content:u.content,...u.origin===void 0?{}:{origin:u.origin}})),e.description.dialect)},sessions:()=>t.sessions(),clearSession:async(d)=>{await t.clearSession(d)},ownConversation:async()=>(await t.sessions()).find((d)=>d.head!==!1&&d.sessionKey.startsWith("owner:"))?.sessionKey,resolveSessionKey:async(d)=>{try{return await t.resolveSessionKey(d)}catch{return d}},rotateSession:async()=>{try{return(await t.rotateSession()).sessionKey}catch{return}},tools:async()=>{let d=await t.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:d.map((l)=>({slug:l.slug,mutating:l.mutating,trust:l.trust,...l.trustReason===void 0?{}:{trustReason:l.trustReason},summary:l.summary}))}},context:async(d)=>{let l=await t.context({sessionKey:d});return{...l,windowSource:"as the host resolved it",...l.lastCompaction===void 0&&l.compactions!==void 0?{lastCompaction:l.compactions===0?void 0:`${l.compactions} stage${l.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await t.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Qr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function td(e,t,r,i,s,a=[],d){let l=e.describe(),[u,p]=await Promise.all([e.turns(t,1),e.store.messages.count(e.id,t)]),c=[`${A.name} ${q} · ${l.id} · ${l.model}`,`session ${t} · ${p} message(s) · window ${l.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],f=tt(s,d);if(f!==void 0)c.push(f);if(u[0]?.errorCode==="turn_abandoned")c.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let m of[...e.warnings,...e.tools.warnings])c.push(`note: ${m.message}
216
+ ${m.hint}`);if(a.length>0)c.push(`note: ${a.join(", ")} in the .env here ${a.length===1?"was":"were"} ignored — this agent's own .env sets ${a.length===1?"it":"them"}.
217
+ A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return c}async function rt(e){let t=e.once!==void 0,r=gt({json:!1,plain:e.plain===!0,oneShot:t}),{mode:i}=r;if(e.manifestPath===void 0){let P=await rd(i,r.because,e);if(typeof P==="number")return P;return rt({...e,manifestPath:P})}let s=fi();if(e.store===void 0&&e.ephemeral!==!0&&Zr(s)!==Zr(G())&&nd(s))process.stdout.write(`note: a session store exists at ${s} from an earlier version — pass --store ${s} to keep using it; the default is now ${G()}
218
+ `);let a;H(()=>a?.stop("cli-exit"));let d={current:void 0},l={current:""},u={current:e.sessionKey},p={current:!1},c={current:void 0},f=e.quiet===!0,m="first",g={current:void 0},R=e.ephemeral===!0?void 0:Qr(await We(De(e.manifestPath),e.store));if(R!==void 0)return await dd({...e,host:R,mode:i==="rich"?"rich":"plain",quiet:f,oneShot:t,reader:d,draft:l,session:u,random:st});for(;;){let P=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=P;let y=P.list()[0];if(y===void 0)throw Error("The manifest produced no agent.");if(u.current===void 0||u.current===""){let N=await so({list:async()=>lo(await y.store.sessions.list(y.id)),mode:i,asked:u.current,wantsContinue:e.continueSession===!0,random:st});if(typeof N==="number")return await P.stop("cli-exit"),N;if(u.current=N.sessionKey,p.current=N.fresh,N.fresh)u.current=await no(y)??N.sessionKey}if(m==="new"){let N=await y.rotateSession({source:"repl"});if(N!==void 0)u.current=N.sessionKey}u.current=await y.resolveSessionKey(u.current??"",{source:"repl"});let j=u.current,D=y.roles.main.capabilities.thinking!=="none",b=e.noReasoning===!0?!1:D,x=f||t?[]:await td(y,j,P.store.location,m==="first"?P.boot.processMs:P.boot.bootMs,m,qs([e.manifestPath]),c.current),I=i==="rich"&&!f&&!t?Te(await y.history(j),y.describe().dialect):[],_=zr({agent:y,bus:P.bus,send:(N,Z)=>y.send(N,Z),history:async(N)=>Te(await y.history(N),y.describe().dialect),sessions:async()=>{let N=await y.store.sessions.heads(y.id);return(await y.store.sessions.list(y.id)).map((Z)=>({...Z,head:si(Z.sessionKey,N)}))},clearSession:async(N)=>{await y.clearSession(N)},ownConversation:()=>no(y),resolveSessionKey:(N)=>y.resolveSessionKey(N,{source:"repl"}),rotateSession:async()=>(await y.rotateSession({source:"repl"}))?.sessionKey,context:async(N)=>ld(y,N),streamFilter:()=>y.streamFilter(),description:{agentId:y.id,name:y.describe().name,model:y.describe().model,dialect:y.describe().dialect,window:y.describe().window,catalogueTokens:y.describe().catalogueTokens,thinking:y.roles.main.capabilities.thinking,warnings:[...y.warnings,...y.tools.warnings]}}),F={...e,source:_,embedded:{agent:y,runtime:P},sessionKey:j,banner:x,prior:I,quiet:f,reader:d,draft:l,showReasoning:b,freshSession:p.current,switchTo:g,random:st},V=i==="rich"?await oo(F):await io(F);if(await P.stop(V===me?"restart":"cli-exit"),V!==me)return V;if(g.current===void 0)m="restart";else m=g.current.reason,c.current=j,u.current=g.current.key,g.current=void 0;p.current=!1}}function sd(e,t){let r=[];for(let i of e)Yt({action:"install",manifestPath:t,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var me=Symbol("restart");async function rd(e,t,r){let i=oe();if(i.length===0){if(e==="rich"){let c=await Un({plain:r.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
219
+ `),o;if(c.kind==="failed")return c.code;return c.manifestPath}throw new n({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${A.slug} init\`, or pass a path to an agent.yaml.`})}if(i.length===1&&i[0]!==void 0)return process.stdout.write(`running ${i[0].ref} — the only agent in the sandbox
220
+ `),i[0].manifestPath;if(e!=="rich"){for(let c of i)process.stdout.write(`${c.ref} ${c.problem??c.modelId??"?"} ${c.dir}
221
+ `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${t})
222
+ `),E}let[{render:s},{createElement:a},{Picker:d}]=await Promise.all([import("ink"),import("react"),import("./Picker-32m79nmp.js")]),l={kind:"quit"};ro();let u=s(a(d,{title:`${A.name} ${q}`,agents:i,onDone:(c)=>{l=c}}),{exitOnCtrlC:!1,...Ke(r.noEnhancedKeys)});H(()=>u.unmount()),await u.waitUntilExit(),u.unmount();let p=l;if(p.kind==="quit")return process.stdout.write(`nothing run
223
+ `),o;if(p.kind==="create"){let c=await Un({plain:r.plain===!0});if(c.kind==="aborted")return process.stdout.write(`nothing to run
224
+ `),o;if(c.kind==="failed")return c.code;return c.manifestPath}return p.manifestPath}async function no(e){let r=await e.resolveSessionKey("local:-",{source:"repl"});return r==="local:-"?void 0:r}async function so(e){let t=()=>({sessionKey:Xo(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new n({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let r=await e.list(),i=od(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
225
+ `),t();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let r=await e.list();if(r.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
226
+ `),t();if(e.mode!=="rich"){for(let s of[...r].sort(vn))process.stdout.write(`${s.sessionKey} ${s.messages} ${s.turns} ${s.lastActivityAt}
227
227
  `);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
228
- `),d}let i=await id([...r].sort(vn));return i===void 0?n():{sessionKey:i,fresh:!1}}return e.asked===void 0?n():{sessionKey:e.asked,fresh:!1}}function vn(e,n){return Date.parse(n.lastActivityAt)-Date.parse(e.lastActivityAt)}function od(e){return[...e].sort(vn)[0]}async function id(e){let[{render:n},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-hpv2ncsb.js")]),s;oo();let a=n(r(i,{sessions:e,now:Date.now(),columns:Pe(process.stdout.columns,be),maxRows:Sn,onDone:(l)=>{s=l,a.unmount()}}),{exitOnCtrlC:!1,...Ue()});return U(()=>a.unmount()),await a.waitUntilExit(),s}function ad(e,n,r,i,s){let a=e.describe(),l=[`${t.name} ${J} · ${a.agentId} · ${a.model}`,`session ${n} · 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=tt(i,s);if(c!==void 0)l.push(c);for(let m of a.warnings)l.push(`warning: ${m.message}`);return l}async function dd(e){let n=e.manifestPath??"",r=me(n),i=RA(n),s=qr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await s.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=zr({client:s,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),c={current:void 0},m="first",w={current:void 0},f={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let S=await so({list:()=>co(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof S==="number")return S;if(e.session.current=S.sessionKey,f.current=S.fresh,S.fresh)e.session.current=await l.ownConversation()??S.sessionKey}if(m==="new"){let S=await l.rotateSession();if(S!==void 0)e.session.current=S}let h=e.session.current??"",g=e.quiet||e.oneShot?[]:ad(l,h,e.host,m,w.current),b=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(h):[],x={...e,source:l,sessionKey:h,banner:g,prior:b,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:f.current,switchTo:c,random:e.random},R=e.mode==="rich"?await ro(x):await io(x);if(R!==$e)return await l.close(),R;if(c.current===void 0)m="restart";else m=c.current.reason,w.current=h,e.session.current=c.current.key,c.current=void 0;f.current=!1}}async function ro(e){let[{render:n},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-4w3qkcs4.js")]),s=ln();U(()=>{s.close()}),St(),Cs(),process.stdout.write(`${Rt}${oa}`);let a=!1,l=n(r(i,{source:e.source,onSwitch:(c,m)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=m},onNew:(c)=>{a=!0,e.switchTo.current={key:$o(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await co(e.source)].sort(vn),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:Wi(Vi(e.banner.slice(1)),e.prior),correctKeys:s.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>LA({onStatus:c}),install:async(c,m)=>mn(sd(c,m))},status:()=>e.embedded===void 0?mo(e.source):ao(e.embedded),contextView:()=>po(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Ue(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),We(),!a)process.stdout.write(Vr({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?$e:o}async function io(e){let{source:n,sessionKey:r,quiet:i}=e,s=!0,a=(T)=>{if(T==="")return;process.stdout.write(T),s=T.endsWith(`
229
- `)},l=(T)=>{if(!s)a(`
230
- `);a(`${T}
228
+ `),E}let i=await id([...r].sort(vn));return i===void 0?t():{sessionKey:i,fresh:!1}}return e.asked===void 0?t():{sessionKey:e.asked,fresh:!1}}function vn(e,t){return Date.parse(t.lastActivityAt)-Date.parse(e.lastActivityAt)}function od(e){return[...e].sort(vn)[0]}async function id(e){let[{render:t},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-9p06npt5.js")]),s;ro();let a=t(r(i,{sessions:e,now:Date.now(),columns:Ue(process.stdout.columns,Me),maxRows:wn,onDone:(d)=>{s=d,a.unmount()}}),{exitOnCtrlC:!1,...Ke()});return H(()=>a.unmount()),await a.waitUntilExit(),s}function ad(e,t,r,i,s){let a=e.describe(),d=[`${A.name} ${q} · ${a.agentId} · ${a.model}`,`session ${t} · window ${a.window} · attached to ${r.baseUrl} (pid ${r.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],l=tt(i,s);if(l!==void 0)d.push(l);for(let u of a.warnings)d.push(`warning: ${u.message}`);return d}async function dd(e){let t=e.manifestPath??"",r=De(t),i=_A(t),s=Vr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await s.agent(r).describe();if(a.status==="disabled")throw new n({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${r}\`, then run again.`});let d=Yr({client:s,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),l={current:void 0},u="first",p={current:void 0},c={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let y=await so({list:()=>co(d),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof y==="number")return y;if(e.session.current=y.sessionKey,c.current=y.fresh,y.fresh)e.session.current=await d.ownConversation()??y.sessionKey}if(u==="new"){let y=await d.rotateSession();if(y!==void 0)e.session.current=y}e.session.current=await d.resolveSessionKey(e.session.current??"");let f=e.session.current??"",m=e.quiet||e.oneShot?[]:ad(d,f,e.host,u,p.current),g=e.mode==="rich"&&!e.quiet&&!e.oneShot?await d.history(f):[],R={...e,source:d,sessionKey:f,banner:m,prior:g,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:c.current,switchTo:l,random:e.random},P=e.mode==="rich"?await oo(R):await io(R);if(P!==me)return await d.close(),P;if(l.current===void 0)u="restart";else u=l.current.reason,p.current=f,e.session.current=l.current.key,l.current=void 0;c.current=!1}}async function oo(e){let[{render:t},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-wkpkwgjt.js")]),s=tn();H(()=>{s.close()}),wt(),Cs(),process.stdout.write(`${_t}${ra}`);let a=!1,d=t(r(i,{source:e.source,onSwitch:(l,u)=>{a=!0,e.switchTo.current={key:l,reason:"switch"},e.draft.current=u},onNew:(l)=>{a=!0,e.switchTo.current={key:Xo(e.random),reason:"new"},e.draft.current=l},sessions:async()=>[...await co(e.source)].sort(vn),onRestart:(l)=>{a=!0,e.draft.current=l},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((l)=>l.message),initial:zi(Wi(e.banner.slice(1)),e.prior),correctKeys:s.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(l)=>PA({onStatus:l}),install:async(l,u)=>Sn(sd(l,u))},status:()=>e.embedded===void 0?fo(e.source):ao(e.embedded),contextView:()=>po(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Ke(e.noEnhancedKeys)});if(H(()=>d.unmount()),await d.waitUntilExit(),Ze(),!a)process.stdout.write(Xr({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?me:o}async function io(e){let{source:t,sessionKey:r,quiet:i}=e,s=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),s=x.endsWith(`
229
+ `)},d=(x)=>{if(!s)a(`
230
+ `);a(`${x}
231
231
  `)};if(e.banner.length>0)a(`${e.banner.join(`
232
232
  `)}
233
233
 
234
- `);let c=!i&&e.once===void 0,m=!1,w,f=n.streamFilter(),h=(T)=>{if(T==="")return;a(T),m=!0},g=e.source.subscribe((T)=>{if(T.sessionKey!==void 0&&T.sessionKey!==r)return;switch(T.type){case"model.result":h(f.endStep());return;case"model.chunk":{let{delta:O,kind:C}=T.data;if(C==="reasoning"&&e.showReasoning!==!0)return;if(C!==w){if(w!==void 0)a(`
234
+ `);let l=!i&&e.once===void 0,u=!1,p,c=t.streamFilter(),f=(x)=>{if(x==="")return;a(x),u=!0},m=e.source.subscribe((x)=>{if(x.sessionKey!==void 0&&x.sessionKey!==r)return;switch(x.type){case"model.result":f(c.endStep());return;case"model.chunk":{let{delta:I,kind:_}=x.data;if(_==="reasoning"&&e.showReasoning!==!0)return;if(_!==p){if(p!==void 0)a(`
235
235
 
236
- `);if(e.showReasoning===!0)a(C==="reasoning"?`· reasoning ·
236
+ `);if(e.showReasoning===!0)a(_==="reasoning"?`· reasoning ·
237
237
  `:`· reply ·
238
- `);w=C}if(C==="reasoning"){a(O),m=!0;return}h(f.push(O));return}case"tool.result":{if(!c)return;let{slug:O,ok:C,latencyMs:L,truncated:B}=T.data;l(` · ${O} — ${C?"ok":"failed"} · ${L} ms${B?" · observation trimmed":""}`);return}case"agent.warning":l(` · ${T.data.message}
239
- ${T.data.hint}`);return;case"tool.repair":if(c)l(T.data.slugs.length===0?` · reply stopped short (${T.data.errors.join("; ")}), asking again`:` · ${T.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":l(` · ${T.data.slug} — blocked: ${T.data.reason}`);return;case"context.dropped":l(` · context: ${T.data.messages} older message(s) did not fit the ${T.data.budget}-token budget and were left out`);return;default:return}}),b=async(T)=>{let O=Hn(T,Yn());if(O===void 0)return"prompt";switch(O.kind){case"exit":return"exit";case"restart":{let C=n.reload;if(C===void 0)return"restart";try{let L=await C();l(`reloaded ${L.join(", ")} — this conversation continues`)}catch(L){l(`could not reload: ${L instanceof Error?L.message:String(L)}`)}return"handled"}case"new":return e.switchTo.current={key:$o(e.random),reason:"new"},"restart";case"help":return l(Kn()),"handled";case"tools":return l(DA(await n.tools())),"handled";case"status":return l(e.embedded===void 0?await mo(n):await ao(e.embedded)),"handled";case"context":return l(await po(e,r)),"handled";case"reset":return await n.clearSession(r),l("session cleared — memory files on disk are untouched"),"handled";case"unknown":return l(nn(O)),"handled";case"command":return l(`${O.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${t.slug} ${O.name}${O.rest===""?"":` ${O.rest}`}\``),"handled"}},x,R=0,S=o,N=(T=e.reader.current)=>{if(x!==void 0&&!x.signal.aborted){R=performance.now(),x.abort();return}T?.close(),a(`
240
- `)},H=async(T)=>{x=new AbortController,m=!1,w=void 0,f=n.streamFilter();let O=await n.send(T,{sessionKey:r,signal:x.signal});if(x=void 0,h(f.end()),m&&!s)a(`
241
- `);else if(!m&&O.text!=="")a(`${O.text}
242
- `);let C=Mt(O.reason,{steps:O.steps,durationMs:O.durationMs,...R===0?{}:{cancelledAfterMs:performance.now()-R}});if(C!==void 0)a(`
243
- (${C})
244
- `);if(O.reason==="error"&&O.error!==void 0)process.stderr.write(`
245
- ${O.error.code}: ${O.error.message}
246
- hint: ${O.error.hint}
247
- `);if(Bo(O.reason))S=d;if(!i&&O.reason==="final")a(` ${O.tokens.prompt} prompt · ${O.tokens.output} output · ${O.durationMs} ms
238
+ `);p=_}if(_==="reasoning"){a(I),u=!0;return}f(c.push(I));return}case"tool.result":{if(!l)return;let{slug:I,ok:_,latencyMs:F,truncated:V}=x.data;d(` · ${I} — ${_?"ok":"failed"} · ${F} ms${V?" · observation trimmed":""}`);return}case"agent.warning":d(` · ${x.data.message}
239
+ ${x.data.hint}`);return;case"tool.repair":if(l)d(x.data.slugs.length===0?` · reply stopped short (${x.data.errors.join("; ")}), asking again`:` · ${x.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":d(` · ${x.data.slug} — blocked: ${x.data.reason}`);return;case"context.dropped":d(` · context: ${x.data.messages} older message(s) did not fit the ${x.data.budget}-token budget and were left out`);return;default:return}}),g=async(x)=>{let I=Kn(x,jn());if(I===void 0)return"prompt";switch(I.kind){case"exit":return"exit";case"restart":{let _=t.reload;if(_===void 0)return"restart";try{let F=await _();d(`reloaded ${F.join(", ")} — this conversation continues`)}catch(F){d(`could not reload: ${F instanceof Error?F.message:String(F)}`)}return"handled"}case"new":return e.switchTo.current={key:Xo(e.random),reason:"new"},"restart";case"help":return d(Yn()),"handled";case"tools":return d(bA(await t.tools())),"handled";case"status":return d(e.embedded===void 0?await fo(t):await ao(e.embedded)),"handled";case"context":return d(await po(e,r)),"handled";case"reset":return await t.clearSession(r),d("session cleared — memory files on disk are untouched"),"handled";case"unknown":return d(on(I)),"handled";case"command":return d(`${I.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${A.slug} ${I.name}${I.rest===""?"":` ${I.rest}`}\``),"handled"}},R,P=0,y=o,j=(x=e.reader.current)=>{if(R!==void 0&&!R.signal.aborted){P=performance.now(),R.abort();return}x?.close(),a(`
240
+ `)},D=async(x)=>{R=new AbortController,u=!1,p=void 0,c=t.streamFilter();let I=await t.send(x,{sessionKey:r,signal:R.signal});if(R=void 0,f(c.end()),u&&!s)a(`
241
+ `);else if(!u&&I.text!=="")a(`${I.text}
242
+ `);let _=Tt(I.reason,{steps:I.steps,durationMs:I.durationMs,...P===0?{}:{cancelledAfterMs:performance.now()-P}});if(_!==void 0)a(`
243
+ (${_})
244
+ `);if(I.reason==="error"&&I.error!==void 0)process.stderr.write(`
245
+ ${I.error.code}: ${I.error.message}
246
+ hint: ${I.error.hint}
247
+ `);if(yo(I.reason))y=E;if(!i&&I.reason==="final")a(` ${I.tokens.prompt} prompt · ${I.tokens.output} output · ${I.durationMs} ms
248
248
 
249
- `);await Ct()},P=()=>N();process.on("SIGINT",P);try{if(e.once!==void 0)return await H(e.once),S;if(process.stdin.isTTY!==!0){let O=e.reader.current??Zr({input:process.stdin});e.reader.current=O;for await(let C of O){let L=C.trim();if(L==="")continue;let B=await b(L);if(B==="exit")break;if(B==="restart"){S=$e;break}if(B==="handled")continue;await H(L)}return S}let T=e.reader.current??Zr({input:process.stdin,output:process.stdout,prompt:Po,terminal:!1});e.reader.current=T,T.prompt();for await(let O of T){let C=O.trim();if(C===""){T.prompt();continue}let L=await b(C);if(L==="exit")break;if(L==="restart"){S=$e;break}if(L==="handled"){T.prompt();continue}await H(C),T.prompt()}if(S!==$e)T.close(),e.reader.current=void 0;return S}finally{process.off("SIGINT",P),g()}}async function ao(e){let{agent:n,runtime:r}=e,i=n.describe(),s=n.manifest,a=s.channels.filter((f)=>f.enabled).map((f)=>`${f.id} (${f.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=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,m=Nt(s),w=m.filter((f)=>f.role!=="main"&&f.role===f.configuredAs);return u([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${s.tools.dialect} · ${i.window} token window (${gA(m[0]?.window)})`},...w.map((f)=>({label:f.role,value:`${f.modelId} · ${f.window.contextWindow} token window (${gA(f.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await cd(r,i.id)}])}function lo(e){return e.filter((n)=>!fi(n.sessionKey))}async function co(e){return lo(await e.sessions())}async function mo(e){let n=e.describe(),r=e.host,[i,s]=await Promise.all([e.tools(),e.sessions()]);return u([{label:"agent",value:`${n.agentId} (${n.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:`${n.model} · ${n.window} token window`},{label:"dialect",value:n.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:n.warnings.length===0?"none":n.warnings.map((a)=>a.message).join("; ")}])}async function ld(e,n){let r=await e.previewContext({sessionKey:n}),[i]=Nt(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:gA(i?.window),wireTokens:r.wireTokens,reserveOutput:r.reserveOutput,calibration:r.calibration,lastCompaction:r.compactions===0?void 0:`${r.compactions} stage${r.compactions===1?"":"s"} run this session`}}async function po(e,n){return ji(await e.source.context(n))}async function cd(e,n){if(e.owned.includes(n))return"this session is serving this agent";let r=await e.store.leases.get(n);if(r!==void 0&&Z(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${t.slug} daemon status ${n}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${t.slug} daemon install ${n}\` keeps it running without a terminal`}function te(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function ud(e,n){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-n;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let s=Math.round(r/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function fd(e,n){if(e.lastFiredAt===void 0)return"never run";let r=rA(e.lastFiredAt,n);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function md(e,n){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(`${te("SCHEDULE",r)} ${te("WHEN",i)} ${te("NEXT",7)} LAST
250
- `);for(let a of e)process.stdout.write(`${te(a.id,r)} ${te(`${a.kind} ${a.expr}`,i)} ${te(ud(a,n),7)} ${fd(a,n)}
249
+ `);await ht()},b=()=>j();process.on("SIGINT",b);try{if(e.once!==void 0)return await D(e.once),y;if(process.stdin.isTTY!==!0){let I=e.reader.current??eo({input:process.stdin});e.reader.current=I;for await(let _ of I){let F=_.trim();if(F==="")continue;let V=await g(F);if(V==="exit")break;if(V==="restart"){y=me;break}if(V==="handled")continue;await D(F)}return y}let x=e.reader.current??eo({input:process.stdin,output:process.stdout,prompt:Go,terminal:!1});e.reader.current=x,x.prompt();for await(let I of x){let _=I.trim();if(_===""){x.prompt();continue}let F=await g(_);if(F==="exit")break;if(F==="restart"){y=me;break}if(F==="handled"){x.prompt();continue}await D(_),x.prompt()}if(y!==me)x.close(),e.reader.current=void 0;return y}finally{process.off("SIGINT",b),m()}}async function ao(e){let{agent:t,runtime:r}=e,i=t.describe(),s=t.manifest,a=s.channels.filter((c)=>c.enabled).map((c)=>`${c.id} (${c.type})`).join(", "),d=a===""?"none — reached through this session and the HTTP API only":r.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,l=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,u=Mt(s),p=u.filter((c)=>c.role!=="main"&&c.role===c.configuredAs);return C([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${s.tools.dialect} · ${i.window} token window (${cA(u[0]?.window)})`},...p.map((c)=>({label:c.role,value:`${c.modelId} · ${c.window.contextWindow} token window (${cA(c.window)})`})),{label:"channels",value:d},{label:"http api",value:l},{label:"store",value:r.store.location},{label:"background",value:await cd(r,i.id)}])}function lo(e){return e.filter((t)=>!hi(t.sessionKey))}async function co(e){return lo(await e.sessions())}async function fo(e){let t=e.describe(),r=e.host,[i,s]=await Promise.all([e.tools(),e.sessions()]);return C([{label:"agent",value:`${t.agentId} (${t.name})`},{label:"attached to",value:r===void 0?"a host":`${r.baseUrl} · pid ${r.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${t.model} · ${t.window} token window`},{label:"dialect",value:t.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:t.warnings.length===0?"none":t.warnings.map((a)=>a.message).join("; ")}])}async function ld(e,t){let r=await e.previewContext({sessionKey:t}),[i]=Mt(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:cA(i?.window),wireTokens:r.wireTokens,reserveOutput:r.reserveOutput,calibration:r.calibration,lastCompaction:r.compactions===0?void 0:`${r.compactions} stage${r.compactions===1?"":"s"} run this session`}}async function po(e,t){return Ji(await e.source.context(t))}async function cd(e,t){if(e.owned.includes(t))return"this session is serving this agent";let r=await e.store.leases.get(t);if(r!==void 0&&ee(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${A.slug} daemon status ${t}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${A.slug} daemon install ${t}\` keeps it running without a terminal`}function ne(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function ud(e,t){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-t;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let s=Math.round(r/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function fd(e,t){if(e.lastFiredAt===void 0)return"never run";let r=sA(e.lastFiredAt,t);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function md(e,t){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let r=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${ne("SCHEDULE",r)} ${ne("WHEN",i)} ${ne("NEXT",7)} LAST
250
+ `);for(let a of e)process.stdout.write(`${ne(a.id,r)} ${ne(`${a.kind} ${a.expr}`,i)} ${ne(ud(a,t),7)} ${fd(a,t)}
251
251
  `);let s=e.filter((a)=>a.lastStatus==="error");if(s.length>0)process.stdout.write(`
252
252
  ${s.length} failing — \`schedules --id ${s[0]?.id}\` for the error
253
- `)}function pd(e){let n=[["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)n.push(["last error",e.lastError]);let r=Math.max(...n.map(([i])=>i.length));process.stdout.write(`${e.id}
254
- `);for(let[i,s]of n)process.stdout.write(` ${te(i,r)} ${s}
255
- `)}function hd(e,n){let r=new Set(n),i=new Map;for(let s of e){if(!r.has(s.channel))continue;let a=`${s.channel}\x00${s.peerId}`,l=i.get(a);if(l!==void 0&&l.lastSeen>=s.lastActivityAt)continue;i.set(a,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...i.values()].sort((s,a)=>s.channelId===a.channelId?a.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(a.channelId))}function gd(e,n){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
253
+ `)}function pd(e){let t=[["kind",`${e.kind} ${e.expr}`],["timezone",e.timezone??"(host)"],["task",e.task],["deliver",e.deliverChannel===void 0?"none — the reply reaches the event stream only":`${e.deliverChannel} → ${e.deliverTo}`],["session",e.sessionMode],["model role",e.role??"main"],["enabled",e.enabled?"yes":"no"],["declared in",e.origin==="manifest"?"agent.yaml":"the API"],["next run",e.nextRunAt??"(never again)"],["runs",String(e.runs)],["last run",e.lastFiredAt??"never"],["last status",e.lastStatus??"-"]];if(e.lastError!==void 0)t.push(["last error",e.lastError]);let r=Math.max(...t.map(([i])=>i.length));process.stdout.write(`${e.id}
254
+ `);for(let[i,s]of t)process.stdout.write(` ${ne(i,r)} ${s}
255
+ `)}function hd(e,t){let r=new Set(t),i=new Map;for(let s of e){if(!r.has(s.channel))continue;let a=`${s.channel}\x00${s.peerId}`,d=i.get(a);if(d!==void 0&&d.lastSeen>=s.lastActivityAt)continue;i.set(a,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...i.values()].sort((s,a)=>s.channelId===a.channelId?a.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(a.channelId))}function gd(e,t){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
256
256
  `+` An address appears here once a first message arrives on one.
257
- `);return}let r=Math.max(7,...e.map((s)=>s.channelId.length)),i=Math.max(7,...e.map((s)=>s.address.length));process.stdout.write(`${te("CHANNEL",r)} ${te("ADDRESS",i)} LAST SEEN
258
- `);for(let s of e)process.stdout.write(`${te(s.channelId,r)} ${te(s.address,i)} ${rA(s.lastSeen,n)}
257
+ `);return}let r=Math.max(7,...e.map((s)=>s.channelId.length)),i=Math.max(7,...e.map((s)=>s.address.length));process.stdout.write(`${ne("CHANNEL",r)} ${ne("ADDRESS",i)} LAST SEEN
258
+ `);for(let s of e)process.stdout.write(`${ne(s.channelId,r)} ${ne(s.address,i)} ${sA(s.lastSeen,t)}
259
259
  `);process.stdout.write(`
260
260
  Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
261
261
  `+`never a person — a private chat is reached by the numeric id above.
262
- `)}async function go(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath]),lease:!1});U(()=>n.stop("cli-exit"));let r=n.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}
262
+ `)}async function go(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath]),lease:!1});H(()=>t.stop("cli-exit"));let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,d]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let l=await r.store.schedules.get(r.id,a);if(l===void 0)return process.stderr.write(`no schedule "${a}" on ${r.id}
263
263
  hint: run \`schedules\` with no flags to see what this agent has.
264
- `),d;if(c.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
264
+ `),E;if(l.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
265
265
  `+` Writing it here would last until the next start — reconciliation restores every
266
266
  `+` field from the file, enabled included.
267
267
 
268
- hint: set \`enabled: ${l}\` on the "${a}" entry under schedules: in
268
+ hint: set \`enabled: ${d}\` on the "${a}" entry under schedules: in
269
269
  ${e.manifestPath}
270
- `),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
270
+ `),E;await r.store.schedules.setEnabled(r.id,a,d,new Date(i).toISOString()),process.stdout.write(d?`${a} enabled — it fires at its next occurrence, not now
271
271
  `:`${a} disabled — still listed, and it keeps its place in the sequence
272
- `)}if(e.recipients===!0){let a=hd(await r.store.sessions.list(r.id),r.manifest.channels.map((l)=>l.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
272
+ `)}if(e.recipients===!0){let a=hd(await r.store.sessions.list(r.id),r.manifest.channels.map((d)=>d.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
273
273
  `),o;return gd(a,i),o}let s=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:s},null,2)}
274
- `),o;if(e.id!==void 0){let a=s.find((l)=>l.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
275
- `),d;return pd(a),o}if(e.enable===void 0&&e.disable===void 0)md(s,i);return o}import{rmSync as Td}from"node:fs";import{dirname as Ko,join as Id}from"node:path";import{readFileSync as yd}from"node:fs";var wd="server.tokenEnv";function dt(e){let n=yd(e,"utf8"),r=Gt(e),i=new Map,s=new Set(jA(n).filter((a)=>a.path===wd).map((a)=>a.name));for(let a of jA(n)){if(s.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:on(r,a),usedBy:l}))}function vo(e,n){let r=dt(e).map((l)=>l.name);for(let[l,c]of Object.entries(n)){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=k([e]),s=[],a=[];for(let[l,c]of Object.entries(n))if(Je(e,l,c),s.push(l),on(i,l))a.push(l);return{written:s,shadowed:a}}import{createHash as bd}from"node:crypto";import{existsSync as ke,lstatSync as ft,mkdirSync as lt,readdirSync as Eo,readFileSync as He,renameSync as $d,rmSync as Ro,writeFileSync as De}from"node:fs";import{basename as Ge,dirname as xo,join as X}from"node:path";var Me="template.yaml",To=/^[a-z0-9][a-z0-9-]*$/;function mt(e){let n;try{n=Eo(e)}catch{return[]}let r=[];for(let i of n.sort()){if(!To.test(i))continue;let s=X(e,i);if(!ft(s).isDirectory())continue;try{let a=Pn(s);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(!p(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function Pn(e){let n=X(e,Me);if(!ke(n))throw new A({code:"template_spec_missing",message:`${Ge(e)} has no ${Me}.`,hint:`A template is an agent directory with a ${Me} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return di(He(n,"utf8"),`${Ge(e)}/${Me}`)}function pt(e,n=""){let r=[];for(let i of Eo(X(e,n)).sort()){let s=n===""?i:`${n}/${i}`;if(s===Me)continue;let a=X(e,s),l=ft(a);if(l.isSymbolicLink())throw new A({code:"template_symlink",message:`${s} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:s});if(l.isDirectory()){r.push(...pt(e,s));continue}let c=He(a);if(c.includes(0))throw new A({code:"template_binary_file",message:`${s} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:s});r.push({relPath:s,contents:c.toString("utf8")})}return r}function Ao(e){if(!To.test(e.template))throw ct(e.template,e.templatesDir);let n=X(e.templatesDir,e.template);if(!ke(n)||!ft(n).isDirectory())throw ct(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=at(r),s=X(e.agentDirBase,i);if(ke(s))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=Or({spec:Pn(n),files:pt(n),id:i,name:r,vars:e.vars}),l=X(xo(e.agentDirBase),`.${Ge(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);lt(l,{recursive:!0});try{_e(l,a.files),jo(l,{template:e.template,name:r,vars:_o(Pn(n),e.vars),files:vd(a.files)});let c=X(l,"agent.yaml");for(let[f,h]of Object.entries(a.env))Je(c,f,h);let m=a.files.find((f)=>f.relPath==="agent.yaml"),w={};for(let f of jA(m?.contents??""))if(a.env[f.name]===void 0&&!process.env[f.name])w[f.name]="(pending)";Ze(c,w),lt(e.agentDirBase,{recursive:!0}),$d(l,s)}catch(c){throw Ro(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:s,manifestPath:X(s,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ct(e,n){let r=mt(n).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 ${n}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var gt=".template.json";function kn(e){return bd("sha256").update(e).digest("hex")}function vd(e){return Object.fromEntries(e.map((n)=>[n.relPath,kn(n.contents)]))}function _o(e,n){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(n).filter(([i])=>!r.has(i)))}function jo(e,n){De(X(e,gt),`${JSON.stringify({version:1,...n},null,2)}
276
- `,{mode:384})}function Fo(e){let n=X(e,gt);if(!ke(n))return;let r=JSON.parse(He(n,"utf8"));return{template:r.template,vars:r.vars}}function Uo(e){let n=X(e.agentDir,gt);if(!ke(n))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(He(n,"utf8")),i=X(e.templatesDir,r.template);if(!ke(i))throw ct(r.template,e.templatesDir);let s=Pn(i);for(let h of Object.keys(e.vars)){let g=s.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=Or({spec:s,files:pt(i),id:Ge(e.agentDir),name:r.name,vars:{...Object.fromEntries(s.vars.filter((h)=>h.secret!==void 0&&h.required).map((h)=>[h.name,"(in .env)"])),...a}}),c=[],m=[],w=[],f={...r.files};try{for(let h of l.files){let g=X(e.agentDir,h.relPath),b=r.files[h.relPath];if(!ke(g)){if(b!==void 0){w.push({file:h.relPath,reason:"removed"});continue}lt(xo(g),{recursive:!0}),De(g,h.contents),c.push({path:g,before:void 0}),f[h.relPath]=kn(h.contents),m.push(h.relPath);continue}let x=He(g,"utf8");if(Sd(h.relPath,x)){w.push({file:h.relPath,reason:"memory"});continue}if(b===void 0||kn(x)!==b){w.push({file:h.relPath,reason:"edited"});continue}if(x===h.contents)continue;De(g,h.contents),c.push({path:g,before:x}),f[h.relPath]=kn(h.contents),m.push(h.relPath)}jo(e.agentDir,{template:r.template,name:r.name,vars:_o(s,a),files:f})}catch(h){throw So(c),h}return{rendered:m,skipped:w,undo:()=>{So(c),De(n,`${JSON.stringify(r,null,2)}
277
- `,{mode:384})}}}function So(e){for(let n of e)if(n.before===void 0)Ro(n.path,{force:!0});else De(n.path,n.before)}function Sd(e,n){if(Ge(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return HA(e,n).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as kd,renameSync as Pd,writeFileSync as Ed}from"node:fs";function Rd(e){try{let n=JSON.parse(kd(e,"utf8"));return typeof n==="object"&&n!==null&&!Array.isArray(n)?n:{}}catch{return{}}}async function xd(e,n){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${n}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Lo(e){let n=e.fetch??globalThis.fetch,r=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},s=Rd(e.cacheFile);return{cachedPeers:(a)=>s[a]??[],async refreshPeers(a,l){let c=await n(`${r}/v1/relay/peers?participant=${encodeURIComponent(l)}`,{headers:i});if(!c.ok)throw await xd(c,"the peer list");let{peers:m}=await c.json();s[a]=m;let w=`${e.cacheFile}.partial`;return Ed(w,`${JSON.stringify(s,null,2)}
278
- `,{mode:384}),Pd(w,e.cacheFile),m},async ask(a){let l=await n(`${r}/v1/relay/ask`,{method:"POST",headers:{...i,"content-type":"application/json"},body:JSON.stringify({participant:a.participantId,toSilo:a.silo,toAgent:a.agent,question:a.question,askedBy:a.fromAgent,sessionKey:a.sessionKey}),...a.signal===void 0?{}:{signal:a.signal}});if(!l.ok){let c=await l.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:c.error??{code:"relay_unavailable",message:`The control plane answered ${l.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await l.json()}}}function Od(){return KA.shape.server.parse({})}async function Mo(e){let n=k(e.manifestPaths),r=Ad(n),i=e.store??G(),s=await gs(e.manifestPaths,n,i),a=s.filter((E)=>!E.enabled),l=s.filter((E)=>E.enabled),c=e.manifestPaths.length===0,m=[],w=[];for(let E of l)try{m.push({path:E.manifestPath,loaded:V(E.manifestPath,{env:n})})}catch(I){if(!c)throw I;w.push({path:E.manifestPath,detail:p(I)?I.message:String(I),...p(I)&&I.hint!==void 0?{hint:I.hint}:{}})}let f=m[0],h=f?.loaded,g=h?.manifest.server??Od();for(let E of m.slice(1)){let I=E.loaded.manifest.server;for(let[_,z,ze,Re]of[["server.port",g.port,I.port,e.port!==void 0],["server.host",g.host,I.host,e.host!==void 0],["server.tokenEnv",g.tokenEnv,I.tokenEnv,!1]]){if(Re||z===ze)continue;throw new A({code:"serve_bind_conflict",message:`${f?.path??"the first manifest"} sets ${_} to ${String(z)} and ${E.path} sets it to ${String(ze)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:_})}}let b=e.port??g.port,x=e.port===void 0,R=e.host??g.host,S=h===void 0?n[g.tokenEnv]:h.env[g.tokenEnv],N=n[g.tokenEnv],H=m.every((E)=>Zt(Ko(E.path),n)),P=S;if(H&&(N===void 0||N==="")){let E=fn(q(n));if(E!==void 0)P=E;else if(S!==void 0&&S!=="")ri(q(n),S)}let T=n[`${t.envPrefix}SERVICE`]!==void 0,O=new Dt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)O.on("agent.channel.status",(E)=>{let I=E.data,_=I.input===void 0?"":I.input.kind==="pairing_code"?`
274
+ `),o;if(e.id!==void 0){let a=s.find((d)=>d.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
275
+ `),E;return pd(a),o}if(e.enable===void 0&&e.disable===void 0)md(s,i);return o}import{rmSync as Td}from"node:fs";import{dirname as Uo,join as Id}from"node:path";import{readFileSync as yd}from"node:fs";var wd="server.tokenEnv";function ot(e){let t=yd(e,"utf8"),r=Ft(e),i=new Map,s=new Set(JA(t).filter((a)=>a.path===wd).map((a)=>a.name));for(let a of JA(t)){if(s.has(a.name))continue;let d=i.get(a.name)??[];d.push(a.path),i.set(a.name,d)}return[...i].map(([a,d])=>({name:a,set:rn(r,a),usedBy:d}))}function wo(e,t){let r=ot(e).map((d)=>d.name);for(let[d,l]of Object.entries(t)){if(!r.includes(d))throw new n({code:"secret_not_referenced",message:`"${d}" is not a variable this agent's manifest reads.`,hint:r.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${r.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${d}`});if(l==="")throw new n({code:"secret_value_empty",message:`An empty value for ${d} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${d}`})}let i=v([e]),s=[],a=[];for(let[d,l]of Object.entries(t))if(Ve(e,d,l),s.push(d),rn(i,d))a.push(d);return{written:s,shadowed:a}}import{createHash as bd}from"node:crypto";import{existsSync as he,lstatSync as ct,mkdirSync as it,readdirSync as So,readFileSync as Ne,renameSync as $d,rmSync as ko,writeFileSync as _e}from"node:fs";import{basename as je,dirname as Po,join as X}from"node:path";var Ae="template.yaml",Ro=/^[a-z0-9][a-z0-9-]*$/;function ut(e){let t;try{t=So(e)}catch{return[]}let r=[];for(let i of t.sort()){if(!Ro.test(i))continue;let s=X(e,i);if(!ct(s).isDirectory())continue;try{let a=Pn(s);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((d)=>({name:d.name,...d.description===void 0?{}:{description:d.description},required:d.required,...d.default===void 0?{}:{default:d.default},secret:d.secret!==void 0}))})}catch(a){if(!h(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function Pn(e){let t=X(e,Ae);if(!he(t))throw new n({code:"template_spec_missing",message:`${je(e)} has no ${Ae}.`,hint:`A template is an agent directory with a ${Ae} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return ui(Ne(t,"utf8"),`${je(e)}/${Ae}`)}function mt(e,t=""){let r=[];for(let i of So(X(e,t)).sort()){let s=t===""?i:`${t}/${i}`;if(s===Ae)continue;let a=X(e,s),d=ct(a);if(d.isSymbolicLink())throw new n({code:"template_symlink",message:`${s} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:s});if(d.isDirectory()){r.push(...mt(e,s));continue}let l=Ne(a);if(l.includes(0))throw new n({code:"template_binary_file",message:`${s} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:s});r.push({relPath:s,contents:l.toString("utf8")})}return r}function xo(e){if(!Ro.test(e.template))throw dt(e.template,e.templatesDir);let t=X(e.templatesDir,e.template);if(!he(t)||!ct(t).isDirectory())throw dt(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new n({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=lt(r),s=X(e.agentDirBase,i);if(he(s))throw new n({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Nr({spec:Pn(t),files:mt(t),id:i,name:r,vars:e.vars}),d=X(Po(e.agentDirBase),`.${je(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);it(d,{recursive:!0});try{ke(d,a.files),Io(d,{template:e.template,name:r,vars:To(Pn(t),e.vars),files:vd(a.files)});let l=X(d,"agent.yaml");for(let[c,f]of Object.entries(a.env))Ve(l,c,f);let u=a.files.find((c)=>c.relPath==="agent.yaml"),p={};for(let c of JA(u?.contents??""))if(a.env[c.name]===void 0&&!process.env[c.name])p[c.name]="(pending)";Xe(l,p),it(e.agentDirBase,{recursive:!0}),$d(d,s)}catch(l){throw ko(d,{recursive:!0,force:!0}),l}return{agentId:i,dir:s,manifestPath:X(s,"agent.yaml"),files:[...a.files.map((l)=>l.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function dt(e,t){let r=ut(t).map((i)=>i.name);return new n({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:r.length===0?`This server has no templates. An operator adds one as a directory under ${t}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var pt=".template.json";function kn(e){return bd("sha256").update(e).digest("hex")}function vd(e){return Object.fromEntries(e.map((t)=>[t.relPath,kn(t.contents)]))}function To(e,t){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(t).filter(([i])=>!r.has(i)))}function Io(e,t){_e(X(e,pt),`${JSON.stringify({version:1,...t},null,2)}
276
+ `,{mode:384})}function _o(e){let t=X(e,pt);if(!he(t))return;let r=JSON.parse(Ne(t,"utf8"));return{template:r.template,vars:r.vars}}function jo(e){let t=X(e.agentDir,pt);if(!he(t))throw new n({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0 or later carries one, because re-rendering needs the hash of every file as it was rendered. For an older agent, edit the files directly or create it again from the template."});let r=JSON.parse(Ne(t,"utf8")),i=X(e.templatesDir,r.template);if(!he(i))throw dt(r.template,e.templatesDir);let s=Pn(i);for(let f of Object.keys(e.vars)){let m=s.vars.find((g)=>g.name===f);if(m?.secret!==void 0)throw new n({code:"template_var_secret",message:`"${f}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${m.secret}.`,field:`vars.${f}`})}let a={...r.vars,...e.vars},d=Nr({spec:s,files:mt(i),id:je(e.agentDir),name:r.name,vars:{...Object.fromEntries(s.vars.filter((f)=>f.secret!==void 0&&f.required).map((f)=>[f.name,"(in .env)"])),...a}}),l=[],u=[],p=[],c={...r.files};try{for(let f of d.files){let m=X(e.agentDir,f.relPath),g=r.files[f.relPath];if(!he(m)){if(g!==void 0){p.push({file:f.relPath,reason:"removed"});continue}it(Po(m),{recursive:!0}),_e(m,f.contents),l.push({path:m,before:void 0}),c[f.relPath]=kn(f.contents),u.push(f.relPath);continue}let R=Ne(m,"utf8");if(Sd(f.relPath,R)){p.push({file:f.relPath,reason:"memory"});continue}if(g===void 0||kn(R)!==g){p.push({file:f.relPath,reason:"edited"});continue}if(R===f.contents)continue;_e(m,f.contents),l.push({path:m,before:R}),c[f.relPath]=kn(f.contents),u.push(f.relPath)}Io(e.agentDir,{template:r.template,name:r.name,vars:To(s,a),files:c})}catch(f){throw $o(l),f}return{rendered:u,skipped:p,undo:()=>{$o(l),_e(t,`${JSON.stringify(r,null,2)}
277
+ `,{mode:384})}}}function $o(e){for(let t of e)if(t.before===void 0)ko(t.path,{force:!0});else _e(t.path,t.before)}function Sd(e,t){if(je(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return KA(e,t).frontmatter.eviction==="oldest"}catch{return!1}}import{readFileSync as kd,renameSync as Pd,writeFileSync as Ed}from"node:fs";function Rd(e){try{let t=JSON.parse(kd(e,"utf8"));return typeof t==="object"&&t!==null&&!Array.isArray(t)?t:{}}catch{return{}}}async function xd(e,t){let i=(await e.json().catch(()=>({}))).error;return Error(i?.message===void 0?`the control plane answered ${e.status} to ${t}`:`${i.message}${i.hint===void 0?"":` ${i.hint}`}`)}function Fo(e){let t=e.fetch??globalThis.fetch,r=e.url.replace(/\/+$/,""),i={authorization:`Bearer ${e.token}`},s=Rd(e.cacheFile);return{cachedPeers:(a)=>s[a]??[],async refreshPeers(a,d){let l=await t(`${r}/v1/relay/peers?participant=${encodeURIComponent(d)}`,{headers:i});if(!l.ok)throw await xd(l,"the peer list");let{peers:u}=await l.json();s[a]=u;let p=`${e.cacheFile}.partial`;return Ed(p,`${JSON.stringify(s,null,2)}
278
+ `,{mode:384}),Pd(p,e.cacheFile),u},async ask(a){let d=await t(`${r}/v1/relay/ask`,{method:"POST",headers:{...i,"content-type":"application/json"},body:JSON.stringify({participant:a.participantId,toSilo:a.silo,toAgent:a.agent,question:a.question,askedBy:a.fromAgent,sessionKey:a.sessionKey}),...a.signal===void 0?{}:{signal:a.signal}});if(!d.ok){let l=await d.json().catch(()=>({}));return{text:"",reason:"error",steps:0,tokens:{prompt:0,output:0},error:l.error??{code:"relay_unavailable",message:`The control plane answered ${d.status}.`,hint:"Check the control plane is reachable from this silo."}}}return await d.json()}}}function Od(){return YA.shape.server.parse({})}async function Lo(e){let t=v(e.manifestPaths),r=Ad(t),i=e.store??G(),s=await cs(e.manifestPaths,t,i),a=s.filter((k)=>!k.enabled),d=s.filter((k)=>k.enabled),l=e.manifestPaths.length===0,u=[],p=[];for(let k of d)try{u.push({path:k.manifestPath,loaded:z(k.manifestPath,{env:t})})}catch(T){if(!l)throw T;p.push({path:k.manifestPath,detail:h(T)?T.message:String(T),...h(T)&&T.hint!==void 0?{hint:T.hint}:{}})}let c=u[0],f=c?.loaded,m=f?.manifest.server??Od();for(let k of u.slice(1)){let T=k.loaded.manifest.server;for(let[O,Y,Be,ye]of[["server.port",m.port,T.port,e.port!==void 0],["server.host",m.host,T.host,e.host!==void 0],["server.tokenEnv",m.tokenEnv,T.tokenEnv,!1]]){if(ye||Y===Be)continue;throw new n({code:"serve_bind_conflict",message:`${c?.path??"the first manifest"} sets ${O} to ${String(Y)} and ${k.path} sets it to ${String(Be)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:O})}}let g=e.port??m.port,R=e.port===void 0,P=e.host??m.host,y=f===void 0?t[m.tokenEnv]:f.env[m.tokenEnv],j=t[m.tokenEnv],D=u.every((k)=>Xt(Uo(k.path),t)),b=y;if(D&&(j===void 0||j==="")){let k=hn(W(t));if(k!==void 0)b=k;else if(y!==void 0&&y!=="")ii(W(t),y)}let x=t[`${A.envPrefix}SERVICE`]!==void 0,I=new bt({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)I.on("agent.channel.status",(k)=>{let T=k.data,O=T.input===void 0?"":T.input.kind==="pairing_code"?`
279
279
 
280
- ${I.input.payload}
281
- ${I.input.expiresAt===void 0?"":`
282
- expires ${I.input.expiresAt}`}`:` (${I.input.kind}${I.input.expiresAt===void 0?"":`, expires ${I.input.expiresAt}`} — GET /v1/agents/${E.agentId??""} carries it)`;process.stdout.write(` ${I.channelId}: ${I.status}${I.detail===void 0?"":` — ${I.detail}`}${_}
283
- `)}),O.on("agent.channel.error",(E)=>{let I=E.data;process.stderr.write(` ${I.channelId}: ${I.message}
284
- hint: ${I.hint}
285
- `)}),O.on("error",(E)=>{let I=E.data,_=E.sessionKey===void 0?"":` [${E.sessionKey}]`;process.stderr.write(` turn failed${_}: ${I.code}: ${I.message}
286
- hint: ${I.hint}
287
- `)}),O.on("agent.channel.rejected",(E)=>{let I=E.data;process.stdout.write(` ${I.channelId}: ${I.reason} — ${I.detail}
288
- `)});let C=Yr(),L=n[`${t.envPrefix}RELAY_URL`],B=n[`${t.envPrefix}RELAY_TOKEN`],K=L===void 0||L===""||B===void 0||B===""?void 0:Lo({url:L,token:B,cacheFile:Id(Ko(i),"relay-peers.json")}),ee=(E)=>({agents:E,...K===void 0?{}:{relay:K},approve:C.approver,env:n,bus:O,toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,startChannels:!0,startSchedules:!0,store:i,mode:T?"daemon":"terminal"}),M;try{M=await Ee.create(ee(m.map((E)=>E.path)))}catch(E){if(!c||m.length===0)throw E;let I=[];for(let _ of m)try{await(await Ee.create({...ee([_.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),I.push(_)}catch(z){w.push({path:_.path,detail:p(z)?z.message:String(z),...p(z)&&z.hint!==void 0?{hint:z.hint}:{}})}if(I.length===m.length)throw E;m.splice(0,m.length,...I),M=await Ee.create(ee(I.map((_)=>_.path)))}fs();let Xe=_d(),Ie=await M.store.operatorKeys.liveCount(),se=Ie===0||e.claim===!0?As():void 0,re,xn=[];try{re=await Nd(b,x,(E)=>(xn.push(E),rs({runtime:M,host:R,port:E,approvals:C,allowedOrigins:g.allowedOrigins,allowedHosts:g.allowedHosts,resolveAgent:(I)=>eo(I,n),provision:{steps:()=>Bt({agentDirBase:q(n)}),create:(I)=>qt({answers:I,defaults:{agentDirBase:q(n)}}),claim:async(I)=>{await Te(M.store,I,q(n))},templates:()=>mt(Dr(n)),createFromTemplate:(I)=>Ao({...I,templatesDir:Dr(n),agentDirBase:q(n)}),rerender:(I)=>Uo({...I,templatesDir:Dr(n)}),templateOf:Fo},secrets:{status:dt,write:vo},remover:Fd(n),home:we(n),channels:{setEnabled:Vn,setCredential:Wn,unpair:zn},...se===void 0?{}:{claim:se},...P===void 0||P===""?{}:{token:P}})))}catch(E){if(await M.stop("server failed to bind"),p(E))throw E;let I=xn.length>1?` — also tried ${xn.slice(1).join(", ")}`:"";throw new A({code:"server_bind_failed",message:`Could not bind ${R}:${b}${I}: ${E instanceof Error?E.message:String(E)}`,hint:x?`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 si=M.owned.length===0&&await cs(M.store.leases,{runtimeId:M.runtimeId,mode:T?"daemon":"terminal"});await M.publishAddress(re.url);let ce=M.list(),yt=ce[0];if(yt!==void 0)process.title=ce.length===1?`${t.slug} ${yt.id}`:`${t.slug} ${ce.length} agents`;for(let E of ce)E.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:re.url,websocket:re.websocket,authenticated:P!==void 0&&P!=="",keys:Ie,...se===void 0?{}:{claim:se.token},agents:ce.map((E)=>({id:E.id,channels:M.channels.statusOf(E.id)})),declined:M.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}}))})}
289
- `);else{let E=`http://${an(R)}:${re.port}`,I=E===re.url?"":` (bound ${R} — every interface)`;if(process.stdout.write(`${t.name} serving on ${E}${I}
290
- `),re.port!==b)process.stdout.write(` moved from ${b} — something else is on it. \`--port ${b}\` would refuse instead of moving.
291
- `);process.stdout.write(` web UI ${E}/ · API reference ${E}/docs
292
- `);for(let _ of ce){let z=M.channels.statusOf(_.id),ze=z.length===0?"no channels":z.map((Oe)=>`${Oe.id} (${Oe.type}${Oe.status==="error"?", BROKEN":""})`).join(", "),Re=_.manifest.schedules.filter((Oe)=>Oe.enabled),oi=_.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${_.manifest.schedules.length>Re.length?` (+${_.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${_.id} — ${ze}${oi}
293
- `)}for(let _ of a)process.stdout.write(` ${_.agentId} — stopped${_.reason===void 0?"":` (${_.reason})`}, \`${t.slug} start ${_.agentId}\`
294
- `);for(let _ of w)if(process.stdout.write(` ${_.path} — NOT served: ${_.detail}
295
- `),_.hint!==void 0)process.stdout.write(` hint: ${_.hint}
296
- `);for(let _ of M.declined)process.stdout.write(` ${_.agentId} — NOT served here: pid ${_.pid} (${_.mode}) already has it
297
- `);if(M.declined.length>0)process.stdout.write(` \`${t.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
298
- `);if(se!==void 0){if(process.stdout.write(` open once to claim this server:
299
- ${ns(R,re.port,se.token)}
300
- without a browser: ${os(R,re.port,se.token)}
301
- `),P===void 0||P==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
302
- `)}if(P===void 0||P==="")process.stdout.write(` unauthenticated — loopback only. Set ${g.tokenEnv} to bind a public host.
303
- `);if(T)process.stdout.write(` running as a background service · ${t.slug} daemon status ${ce[0]?.id??""}
304
- `);else if(xr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
305
- `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${t.slug} daemon install${ce[0]?.id===void 0?"":` ${ce[0].id}`}\` keeps it running.
306
- `)}let wt=!1,bt=async()=>{if(wt)return;if(wt=!0,r>0&&M.all().some((E)=>E.inFlight>0)){let E=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
307
- `);let I=await M.drain(r);process.stdout.write(I===0?`drained in ${Date.now()-E} ms
308
- `:`${I} turn(s) still running after ${r} ms; the next start marks them interrupted
309
- `)}if(await re.stop(),si)await M.store.leases.release(Ut,M.runtimeId).catch(()=>{});await M.stop("interrupted")};return U(bt),await Xe,process.stdout.write(`stopping
310
- `),await bt(),o}function Ad(e){let n=`${t.envPrefix}DRAIN_MS`,r=e[n];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new A({code:"serve_drain_invalid",message:`${n} 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:n});return Number(r)}function _d(){return new Promise((e)=>{let n=()=>{process.off("SIGINT",n),process.off("SIGTERM",n),e()};process.once("SIGINT",n),process.once("SIGTERM",n)})}var Cd=16;async function Nd(e,n,r){let i=n&&e!==0?e+Cd:e;for(let s=e;;s+=1)try{return await r(s)}catch(a){if(s>=i||!jd(a))throw a}}function jd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let n=e instanceof Error?e.message:String(e);return n.includes("EADDRINUSE")||n.includes("in use")}function Fd(e){return{locate(n){let r=Ae(e).filter((s)=>s.id===n),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${n}" 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 "${n}": ${r.map((s)=>s.dir).join(", ")}.`,hint:"They share one conversation history, so deleting either would delete the other's too. Give one a different id first."}};return{ok:!0,dir:i.dir}},async deleteDir(n){if(!Zt(n,e))throw Error(`refusing to delete ${n}: it is outside the sandbox`);Td(n,{recursive:!0,force:!0})}}}function W(e,n){return e.length>=n?e:e+" ".repeat(n-e.length)}function Ud(e){let n=new Map,r=[];for(let i of e){let s=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){r.push(a);continue}let l=`schedule:${s[1]}`,c=n.get(l);if(c===void 0){let m={...a,sessionKey:`${l}:*`,runs:1};n.set(l,m),r.push(m);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
311
- `);return}let n=Ud(e),r=Math.max(7,...n.map((i)=>i.sessionKey.length));process.stdout.write(`${W("SESSION",r)} ${W("MSGS",5)} ${W("TURNS",5)} ${W("PHASE",8)} LAST
312
- `);for(let i of n){let s=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${W(i.sessionKey,r)} ${W(String(i.messages),5)} ${W(String(i.turns),5)} ${W(i.phase??"-",8)} ${rA(i.lastActivityAt,Date.now())}${s}
313
- `)}}async function Kd(e,n,r){let i=await e.store.messages.page(e.id,n,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${n}
280
+ ${T.input.payload}
281
+ ${T.input.expiresAt===void 0?"":`
282
+ expires ${T.input.expiresAt}`}`:` (${T.input.kind}${T.input.expiresAt===void 0?"":`, expires ${T.input.expiresAt}`} — GET /v1/agents/${k.agentId??""} carries it)`;process.stdout.write(` ${T.channelId}: ${T.status}${T.detail===void 0?"":` — ${T.detail}`}${O}
283
+ `)}),I.on("agent.channel.error",(k)=>{let T=k.data;process.stderr.write(` ${T.channelId}: ${T.message}
284
+ hint: ${T.hint}
285
+ `)}),I.on("error",(k)=>{let T=k.data,O=k.sessionKey===void 0?"":` [${k.sessionKey}]`;process.stderr.write(` turn failed${O}: ${T.code}: ${T.message}
286
+ hint: ${T.hint}
287
+ `)}),I.on("agent.channel.rejected",(k)=>{let T=k.data;process.stdout.write(` ${T.channelId}: ${T.reason} — ${T.detail}
288
+ `)});let _=jr(),F=t[`${A.envPrefix}RELAY_URL`],V=t[`${A.envPrefix}RELAY_TOKEN`],N=F===void 0||F===""||V===void 0||V===""?void 0:Fo({url:F,token:V,cacheFile:Id(Uo(i),"relay-peers.json")}),Z=(k)=>({agents:k,...N===void 0?{}:{relay:N},approve:_.approver,env:t,bus:I,toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),K;try{K=await Ce.create(Z(u.map((k)=>k.path)))}catch(k){if(!l||u.length===0)throw k;let T=[];for(let O of u)try{await(await Ce.create({...Z([O.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),T.push(O)}catch(Y){p.push({path:O.path,detail:h(Y)?Y.message:String(Y),...h(Y)&&Y.hint!==void 0?{hint:Y.hint}:{}})}if(T.length===u.length)throw k;u.splice(0,u.length,...T),K=await Ce.create(Z(T.map((O)=>O.path)))}hs();let Le=_d(),$e=await K.store.operatorKeys.liveCount(),te=$e===0||e.claim===!0?ns():void 0,se,Rn=[];try{se=await Nd(g,R,(k)=>(Rn.push(k),is({runtime:K,host:P,port:k,approvals:_,allowedOrigins:m.allowedOrigins,allowedHosts:m.allowedHosts,resolveAgent:(T)=>to(T,t),provision:{steps:()=>Dt({agentDirBase:W(t)}),create:(T)=>Gt({answers:T,defaults:{agentDirBase:W(t)}}),claim:async(T)=>{await we(K.store,T,W(t))},templates:()=>ut(br(t)),createFromTemplate:(T)=>xo({...T,templatesDir:br(t),agentDirBase:W(t)}),rerender:(T)=>jo({...T,templatesDir:br(t)}),templateOf:_o},secrets:{status:ot,write:wo},remover:Fd(t),home:Oe(t),channels:{setEnabled:Wn,setCredential:zn,unpair:Zn},...te===void 0?{}:{claim:te},...b===void 0||b===""?{}:{token:b}})))}catch(k){if(await K.stop("server failed to bind"),h(k))throw k;let T=Rn.length>1?` — also tried ${Rn.slice(1).join(", ")}`:"";throw new n({code:"server_bind_failed",message:`Could not bind ${P}:${g}${T}: ${k instanceof Error?k.message:String(k)}`,hint:R?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${A.slug} stop\` releases one this runtime started.`:"Another process is on that port, and --port was given explicitly so nothing else was tried. Drop the flag to let it walk to the next free port, or name a different one.",cause:k})}let ri=K.owned.length===0&&await ls(K.store.leases,{runtimeId:K.runtimeId,mode:x?"daemon":"terminal"});await K.publishAddress(se.url);let de=K.list(),yt=de[0];if(yt!==void 0)process.title=de.length===1?`${A.slug} ${yt.id}`:`${A.slug} ${de.length} agents`;for(let k of de)k.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:se.url,websocket:se.websocket,authenticated:b!==void 0&&b!=="",keys:$e,...te===void 0?{}:{claim:te.token},agents:de.map((k)=>({id:k.id,channels:K.channels.statusOf(k.id)})),declined:K.declined.map((k)=>({agentId:k.agentId,pid:k.pid,mode:k.mode,since:k.startedAt})),disabled:a.map((k)=>({agentId:k.agentId,...k.reason===void 0?{}:{reason:k.reason}})),broken:p.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
289
+ `);else{let k=`http://${gn(P)}:${se.port}`,T=k===se.url?"":` (bound ${P} — every interface)`;if(process.stdout.write(`${A.name} serving on ${k}${T}
290
+ `),se.port!==g)process.stdout.write(` moved from ${g} — something else is on it. \`--port ${g}\` would refuse instead of moving.
291
+ `);process.stdout.write(` web UI ${k}/ · API reference ${k}/docs
292
+ `);for(let O of de){let Y=K.channels.statusOf(O.id),Be=Y.length===0?"no channels":Y.map((ve)=>`${ve.id} (${ve.type}${ve.status==="error"?", BROKEN":""})`).join(", "),ye=O.manifest.schedules.filter((ve)=>ve.enabled),oi=O.manifest.schedules.length===0?"":`, ${ye.length} schedule${ye.length===1?"":"s"}${O.manifest.schedules.length>ye.length?` (+${O.manifest.schedules.length-ye.length} disabled)`:""}`;process.stdout.write(` ${O.id} — ${Be}${oi}
293
+ `)}for(let O of a)process.stdout.write(` ${O.agentId} — stopped${O.reason===void 0?"":` (${O.reason})`}, \`${A.slug} start ${O.agentId}\`
294
+ `);for(let O of p)if(process.stdout.write(` ${O.path} — NOT served: ${O.detail}
295
+ `),O.hint!==void 0)process.stdout.write(` hint: ${O.hint}
296
+ `);for(let O of K.declined)process.stdout.write(` ${O.agentId} — NOT served here: pid ${O.pid} (${O.mode}) already has it
297
+ `);if(K.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
298
+ `);if(te!==void 0){if(process.stdout.write(` open once to claim this server:
299
+ ${os(P,se.port,te.token)}
300
+ without a browser: ${rs(P,se.port,te.token)}
301
+ `),b===void 0||b==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
302
+ `)}if(b===void 0||b==="")process.stdout.write(` unauthenticated — loopback only. Set ${m.tokenEnv} to bind a public host.
303
+ `);if(x)process.stdout.write(` running as a background service · ${A.slug} daemon status ${de[0]?.id??""}
304
+ `);else if(Hr())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
305
+ `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${de[0]?.id===void 0?"":` ${de[0].id}`}\` keeps it running.
306
+ `)}let vt=!1,St=async()=>{if(vt)return;if(vt=!0,r>0&&K.all().some((k)=>k.inFlight>0)){let k=Date.now();process.stdout.write(`draining — waiting up to ${r} ms for running turns
307
+ `);let T=await K.drain(r);process.stdout.write(T===0?`drained in ${Date.now()-k} ms
308
+ `:`${T} turn(s) still running after ${r} ms; the next start marks them interrupted
309
+ `)}if(await se.stop(),ri)await K.store.leases.release(xt,K.runtimeId).catch(()=>{});await K.stop("interrupted")};return H(St),await Le,process.stdout.write(`stopping
310
+ `),await St(),o}function Ad(e){let t=`${A.envPrefix}DRAIN_MS`,r=e[t];if(r===void 0||r==="")return 0;if(!/^\d+$/.test(r))throw new n({code:"serve_drain_invalid",message:`${t} is "${r}", which is not a number of milliseconds.`,hint:"Set it to a whole number, a few seconds under the orchestrator's grace period — 25000 beside Kubernetes' default terminationGracePeriodSeconds of 30. Unset, a stop does not wait.",field:t});return Number(r)}function _d(){return new Promise((e)=>{let t=()=>{process.off("SIGINT",t),process.off("SIGTERM",t),e()};process.once("SIGINT",t),process.once("SIGTERM",t)})}var Cd=16;async function Nd(e,t,r){let i=t&&e!==0?e+Cd:e;for(let s=e;;s+=1)try{return await r(s)}catch(a){if(s>=i||!jd(a))throw a}}function jd(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let t=e instanceof Error?e.message:String(e);return t.includes("EADDRINUSE")||t.includes("in use")}function Fd(e){return{locate(t){let r=oe(e).filter((s)=>s.id===t),i=r[0];if(i===void 0)return{ok:!1,status:404,error:{code:"agent_remove_not_in_sandbox",message:`No agent "${t}" in the sandbox, so there are no files here to delete.`,hint:"Only sandbox agents are deleted over the API. An agent elsewhere is removed by deleting its directory yourself."}};if(r.length>1)return{ok:!1,status:409,error:{code:"agent_remove_shared_id",message:`${r.length} sandbox directories declare id "${t}": ${r.map((s)=>s.dir).join(", ")}.`,hint:"They share one conversation history, so deleting either would delete the other's too. Give one a different id first."}};return{ok:!0,dir:i.dir}},async deleteDir(t){if(!Xt(t,e))throw Error(`refusing to delete ${t}: it is outside the sandbox`);Td(t,{recursive:!0,force:!0})}}}function B(e,t){return e.length>=t?e:e+" ".repeat(t-e.length)}function Kd(e){let t=new Map,r=[];for(let i of e){let s=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){r.push(a);continue}let d=`schedule:${s[1]}`,l=t.get(d);if(l===void 0){let u={...a,sessionKey:`${d}:*`,runs:1};t.set(d,u),r.push(u);continue}if(l.runs=(l.runs??1)+1,l.messages+=i.messages,l.turns+=i.turns,i.lastActivityAt>l.lastActivityAt)l.lastActivityAt=i.lastActivityAt}return r}function Ud(e){if(e.length===0){process.stdout.write(`no sessions yet
311
+ `);return}let t=Kd(e),r=Math.max(7,...t.map((i)=>i.sessionKey.length));process.stdout.write(`${B("SESSION",r)} ${B("MSGS",5)} ${B("TURNS",5)} ${B("PHASE",8)} LAST
312
+ `);for(let i of t){let s=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${B(i.sessionKey,r)} ${B(String(i.messages),5)} ${B(String(i.turns),5)} ${B(i.phase??"-",8)} ${sA(i.lastActivityAt,Date.now())}${s}
313
+ `)}}async function Ld(e,t,r){let i=await e.store.messages.page(e.id,t,{limit:r});if(i.messages.length===0){process.stdout.write(`no messages in ${t}
314
314
  `);return}for(let s of[...i.messages].reverse())process.stdout.write(`${s.role}: ${s.content}
315
315
  `);if(i.nextBefore!==void 0)process.stdout.write(`
316
316
  … older messages exist; raise --limit
317
- `)}async function Md(e,n,r){let i=await e.turns(n,r);if(i.length===0){process.stdout.write(`no turns in ${n}
318
- `);return}process.stdout.write(`${W("TURN",22)} ${W("STATUS",9)} ${W("STEPS",5)} ${W("TOKENS",13)} ${W("MS",6)} SOURCE
319
- `);for(let s of i)if(process.stdout.write(`${W(s.turnId,22)} ${W(s.status,9)} ${W(String(s.steps),5)} ${W(`${s.promptTokens}/${s.outputTokens}`,13)} ${W(String(s.durationMs??"-"),6)} ${s.source}
317
+ `)}async function Md(e,t,r){let i=await e.turns(t,r);if(i.length===0){process.stdout.write(`no turns in ${t}
318
+ `);return}process.stdout.write(`${B("TURN",22)} ${B("STATUS",9)} ${B("STEPS",5)} ${B("TOKENS",13)} ${B("MS",6)} SOURCE
319
+ `);for(let s of i)if(process.stdout.write(`${B(s.turnId,22)} ${B(s.status,9)} ${B(String(s.steps),5)} ${B(`${s.promptTokens}/${s.outputTokens}`,13)} ${B(String(s.durationMs??"-"),6)} ${s.source}
320
320
  `),s.errorCode!==void 0){if(process.stdout.write(` ${s.errorCode}: ${s.errorMessage}
321
321
  `),s.errorHint!==void 0)process.stdout.write(` hint: ${s.errorHint}
322
- `)}}async function Go(e){let n=await Ee.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});U(()=>n.stop("cli-exit"));let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ho;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await r.store.messages.count(r.id,e.sessionKey);return await r.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
323
- `),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:n.store.location,sessions:await r.sessions()}:{store:n.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)}
324
- `),o}if(process.stdout.write(`store: ${n.store.location}
322
+ `)}}async function Ho(e){let t=await Ce.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});H(()=>t.stop("cli-exit"));let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ko;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await r.store.messages.count(r.id,e.sessionKey);return await r.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
323
+ `),o}if(e.json===!0){let a=e.sessionKey===void 0?{store:t.store.location,sessions:await r.sessions()}:{store:t.store.location,session:await r.store.sessions.get(r.id,e.sessionKey),messages:(await r.store.messages.page(r.id,e.sessionKey,{limit:i})).messages,turns:await r.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
324
+ `),o}if(process.stdout.write(`store: ${t.store.location}
325
325
 
326
- `),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}
326
+ `),e.sessionKey===void 0)return Ud(await r.sessions()),o;if(await r.store.sessions.get(r.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${r.id}
327
327
  hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
328
- `),d;if(e.turns===!0)await Md(r,e.sessionKey,i);else await Kd(r,e.sessionKey,i);return o}import{existsSync as Dd,readFileSync as Hd,writeFileSync as Gd}from"node:fs";import{basename as Wd,dirname as Bd,join as qd}from"node:path";var Vd=/^(#{1,6})\s+(.*)$/,Jd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Xd=/^[ \t]*<\/rules>[ \t]*$/,zd=/^\s*(?:```|~~~)/;function Wo(e){if(e.action!=="distill")throw new 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 n;try{n=Hd(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=Wd(e.file),i=e.out??qd(Bd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(Dd(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:s}=HA(r,n),a=Yd(r,s);return Gd(i,a,"utf8"),process.stdout.write(`wrote ${i}
328
+ `),E;if(e.turns===!0)await Md(r,e.sessionKey,i);else await Ld(r,e.sessionKey,i);return o}import{existsSync as Dd,readFileSync as Hd,writeFileSync as Gd}from"node:fs";import{basename as Wd,dirname as Bd,join as qd}from"node:path";var Vd=/^(#{1,6})\s+(.*)$/,Jd=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Xd=/^[ \t]*<\/rules>[ \t]*$/,zd=/^\s*(?:```|~~~)/;function Wo(e){if(e.action!=="distill")throw new n({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${e.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let t;try{t=Hd(e.file,"utf8")}catch{throw new n({code:"cli_soul_file_missing",message:`${e.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let r=Wd(e.file),i=e.out??qd(Bd(e.file),`${r.replace(/\.md$/i,"")}.compact.md`);if(Dd(i))throw new n({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:s}=KA(r,t),a=Yd(r,s);return Gd(i,a,"utf8"),process.stdout.write(`wrote ${i}
329
329
 
330
330
  The scaffold copies ${r}'s headings and its <rules> blocks verbatim, and leaves a
331
331
  {{PLACEHOLDER}} under each heading. Now:
332
332
  `+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
333
333
  `+` document's own voice. The workspace command warns until none are left.
334
334
  2. Name the file in context.soul.distilled.
335
- `),o}function Yd(e,n){let r=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,s=!1,a=0,l=!1;for(let c of n.split(`
336
- `)){if(zd.test(c)){if(i=!i,s)r.push(c);continue}if(i){if(s)r.push(c);continue}if(Jd.test(c)){s=!0,r.push(c);continue}if(s){if(r.push(c),Xd.test(c))s=!1,r.push("");continue}if(Vd.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(`
335
+ `),o}function Yd(e,t){let r=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,s=!1,a=0,d=!1;for(let l of t.split(`
336
+ `)){if(zd.test(l)){if(i=!i,s)r.push(l);continue}if(i){if(s)r.push(l);continue}if(Jd.test(l)){s=!0,r.push(l);continue}if(s){if(r.push(l),Xd.test(l))s=!1,r.push("");continue}if(Vd.exec(l)!==null)d=!0,a+=1,r.push(l),r.push(""),r.push(`{{SECTION_${a}}}`),r.push("")}if(!d)r.push("{{ESSENCE}}"),r.push("");return`${r.join(`
337
337
  `).replace(/\n{3,}/g,`
338
338
 
339
339
  `).trimEnd()}
340
- `}var Qd=["list","add","remove","update","search"],Zd=12;async function qo(e){try{switch(e.action){case"list":return el(e);case"add":return nl(e);case"remove":return sl(e);case"update":return await rl(e);case"search":return await ol(e);default:throw new A({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Qd.join(", ")}.`})}}catch(n){if(p(n))return process.stdout.write(`${n.message}
340
+ `}var Qd=["list","add","remove","update","search"],Zd=12;async function qo(e){try{switch(e.action){case"list":return el(e);case"add":return nl(e);case"remove":return sl(e);case"update":return await rl(e);case"search":return await ol(e);default:throw new n({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Qd.join(", ")}.`})}}catch(t){if(h(t))return process.stdout.write(`${t.message}
341
341
 
342
- ${n.hint}
343
- `),d;throw n}}function el(e){let r=Fe(e.env).map((i)=>{let s=ar(i.name,e.env);return{...i,cached:Et(i.name,e.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:to(e.env),sources:r},null,2)}
342
+ ${t.hint}
343
+ `),E;throw t}}function el(e){let r=He(e.env).map((i)=>{let s=gr(i.name,e.env);return{...i,cached:ft(i.name,e.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:Ao(e.env),sources:r},null,2)}
344
344
  `),o;if(r.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
345
345
 
346
- \`sources add <name> <url>\` to add one, or \`sources add ${_A[0]?.name??"anthropic"} ${_A[0]?.url??""}\` to put a built-in back.
347
- `),o;process.stdout.write(v("sources",!0));for(let i of r)process.stdout.write(`
348
- ${Q(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
349
- `),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(`
350
- ${v("registry")}
351
- ${y(to(e.env))}
352
- `),o}function nl(e){let[n,r]=e.rest;if(n===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,s=i?r:n,a=sr(s),l=i?n:tl(a.url);if(!kA(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=Fe(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> ${s}\`.`});let m=e.path??a.path,w=e.ref??a.ref,f={name:l,url:a.url,...m===void 0?{}:{path:m},...w===void 0?{}:{ref:w}};if(ls(f,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:f},null,2)}
353
- `),o;return process.stdout.write(`${u([{label:c===void 0?"added":"replaced",value:l},{label:"url",value:f.url},...f.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:f.path}],...f.ref===void 0?[]:[{label:"branch",value:f.ref}]])}
354
- `),process.stdout.write(`${v("next")}
355
- ${Q(`sources update ${l}`)}
356
- ${Q("sources search <what you need>")}
357
- `),o}function tl(e){let n=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(n[n.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function sl(e){let n=e.rest[0];if(n===void 0)throw new A({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=Fe(e.env).map((s)=>s.name);if(!Is(n,e.env)){let s=j(n,r);throw new A({code:"sources_unknown",message:`no source called ${n}`,hint:s===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${s}?`})}let i=_A.some((s)=>s.name===n);return process.stdout.write(`removed ${n}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
346
+ \`sources add <name> <url>\` to add one, or \`sources add ${kA[0]?.name??"anthropic"} ${kA[0]?.url??""}\` to put a built-in back.
347
+ `),o;process.stdout.write(L("sources",!0));for(let i of r)process.stdout.write(`
348
+ ${w(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
349
+ `),process.stdout.write(S(C([{label:"url",value:i.url},...i.path===void 0?[]:[{label:"path",value:i.path}],...i.ref===void 0?[]:[{label:"branch",value:i.ref}],{label:"cached",value:i.cached?`${i.skills??"?"} skills at ${i.commit??"?"}, fetched ${i.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
350
+ ${L("registry")}
351
+ ${S(Ao(e.env))}
352
+ `),o}function nl(e){let[t,r]=e.rest;if(t===void 0)throw new n({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=r!==void 0,s=i?r:t,a=ar(s),d=i?t:tl(a.url);if(!vA(d))throw new n({code:"sources_name_invalid",message:`${JSON.stringify(d)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let l=He(e.env).find((f)=>f.name===d);if(l!==void 0&&!i)throw new n({code:"sources_name_taken",message:`${d} is already a source, pointing at ${l.url}`,hint:`Give this one its own name: \`sources add <name> ${s}\`.`});let u=e.path??a.path,p=e.ref??a.ref,c={name:d,url:a.url,...u===void 0?{}:{path:u},...p===void 0?{}:{ref:p}};if(Is(c,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:c},null,2)}
353
+ `),o;return process.stdout.write(`${C([{label:l===void 0?"added":"replaced",value:d},{label:"url",value:c.url},...c.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:c.path}],...c.ref===void 0?[]:[{label:"branch",value:c.ref}]])}
354
+ `),process.stdout.write(`${L("next")}
355
+ ${w(`sources update ${d}`)}
356
+ ${w("sources search <what you need>")}
357
+ `),o}function tl(e){let t=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(t[t.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function sl(e){let t=e.rest[0];if(t===void 0)throw new n({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=He(e.env).map((s)=>s.name);if(!ds(t,e.env)){let s=J(t,r);throw new n({code:"sources_unknown",message:`no source called ${t}`,hint:s===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${s}?`})}let i=kA.some((s)=>s.name===t);return process.stdout.write(`removed ${t}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
358
358
  `),process.stdout.write(`
359
359
  The cached copy is left on disk; nothing already installed into an agent is touched.
360
- `),o}async function rl(e){let n=Fe(e.env),r=e.rest.length===0?n:e.rest.map((a)=>{let l=n.find((c)=>c.name===a);if(l===void 0){let c=j(a,n.map((m)=>m.name));throw new A({code:"sources_unknown",message:`no source called ${a}`,hint:c===void 0?`Configured: ${n.map((m)=>m.name).join(", ")||"none"}.`:`Did you mean ${c}?`})}return l});if(r.length===0)return process.stdout.write(`no sources configured
360
+ `),o}async function rl(e){let t=He(e.env),r=e.rest.length===0?t:e.rest.map((a)=>{let d=t.find((l)=>l.name===a);if(d===void 0){let l=J(a,t.map((u)=>u.name));throw new n({code:"sources_unknown",message:`no source called ${a}`,hint:l===void 0?`Configured: ${t.map((u)=>u.name).join(", ")||"none"}.`:`Did you mean ${l}?`})}return d});if(r.length===0)return process.stdout.write(`no sources configured
361
361
 
362
362
  \`sources add <url>\` to add one.
363
- `),o;let i=[],s=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let l=await vA(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)":""}
364
- `)}catch(l){let c=l instanceof Error?l.message:String(l);if(s.push({name:a.name,reason:c}),e.json!==!0)process.stdout.write(`failed
365
- `);if(e.json!==!0&&p(l))process.stdout.write(`${y(l.message)}
366
- ${y(l.hint,4)}
363
+ `),o;let i=[],s=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let d=await LA(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:d.commit,skills:d.skills}),e.json!==!0)process.stdout.write(`${d.skills} skills at ${d.commit}${d.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
364
+ `)}catch(d){let l=d instanceof Error?d.message:String(d);if(s.push({name:a.name,reason:l}),e.json!==!0)process.stdout.write(`failed
365
+ `);if(e.json!==!0&&h(d))process.stdout.write(`${S(d.message)}
366
+ ${S(d.hint,4)}
367
367
  `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:s},null,2)}
368
- `);return i.length===0?d:o}async function ol(e){let n=e.rest.join(" ").trim(),r=Fe(e.env);if(r.length===0)return process.stdout.write(`no sources configured
368
+ `);return i.length===0?E:o}async function ol(e){let t=e.rest.join(" ").trim(),r=He(e.env);if(r.length===0)return process.stdout.write(`no sources configured
369
369
 
370
370
  \`sources add <url>\` to add one.
371
- `),d;let i=r.filter((c)=>!Et(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 m=await vA(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${m.skills} skills
372
- `)}catch(m){if(e.json!==!0){if(process.stdout.write(`failed
373
- `),p(m))process.stdout.write(`${y(m.message)}
374
- `)}}}let s=r.flatMap((c)=>Ht(c,e.env));if(s.length===0)return process.stdout.write(`
371
+ `),E;let i=r.filter((l)=>!ft(l.name,e.env));for(let l of i){if(e.json!==!0)process.stdout.write(`fetching ${l.name} for the first time … `);try{let u=await LA(l,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${u.skills} skills
372
+ `)}catch(u){if(e.json!==!0){if(process.stdout.write(`failed
373
+ `),h(u))process.stdout.write(`${S(u.message)}
374
+ `)}}}let s=r.flatMap((l)=>Kt(l,e.env));if(s.length===0)return process.stdout.write(`
375
375
  nothing to search — no source has been fetched successfully
376
376
 
377
377
  \`sources update\` reports why.
378
- `),d;let a=n.length===0?s:il(n,s);if(a.length===0)return process.stdout.write(`
379
- nothing in ${s.length} skills across ${r.length} sources matches ${JSON.stringify(n)}
378
+ `),E;let a=t.length===0?s:il(t,s);if(a.length===0)return process.stdout.write(`
379
+ nothing in ${s.length} skills across ${r.length} sources matches ${JSON.stringify(t)}
380
380
 
381
381
  Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
382
- `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:n,searched:s.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)}
383
- `),o;let l=a.slice(0,Zd);process.stdout.write(`
384
- ${v(n.length===0?`${s.length} skills`:`${a.length} of ${s.length} skills match ${JSON.stringify(n)}`,!0)}
385
- `);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"}
386
- `);let m=c.problem??c.description;process.stdout.write(`${y(m.length>160?`${m.slice(0,157)}…`:m,4)}
387
- `)}if(a.length>l.length)process.stdout.write(`
388
- ${y(`… and ${a.length-l.length} more; narrow the query or use --json`)}
382
+ `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:t,searched:s.length,results:a.map((l)=>({source:l.source,skill:l.skill,description:l.description,tokens:l.tokens,scripts:l.scripts.length,repoPath:l.repoPath,...l.problem===void 0?{}:{problem:l.problem}}))},null,2)}
383
+ `),o;let d=a.slice(0,Zd);process.stdout.write(`
384
+ ${L(t.length===0?`${s.length} skills`:`${a.length} of ${s.length} skills match ${JSON.stringify(t)}`,!0)}
385
+ `);for(let l of d){process.stdout.write(`${w(`${l.source}/${l.skill}`)} ${l.tokens} tokens${l.scripts.length===0?"":`, ${l.scripts.length} runnable file${l.scripts.length===1?"":"s"}`}${l.problem===void 0?"":" — will not load"}
386
+ `);let u=l.problem??l.description;process.stdout.write(`${S(u.length>160?`${u.slice(0,157)}…`:u,4)}
387
+ `)}if(a.length>d.length)process.stdout.write(`
388
+ ${S(`… and ${a.length-d.length} more; narrow the query or use --json`)}
389
389
  `);return process.stdout.write(`
390
- ${v("install")}
391
- ${y(`skills install <agent> ${l[0]?.source}/${l[0]?.skill}`)}
392
- `),o}function il(e,n){let r=new Map,i=n.map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return JA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}async function Vo(e){let n=al(e.manifestPath),r=await ir(n,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await rr(n,!0,void 0,e.store);let s=await Ve(e.store),a=!1;if(s===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)i.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let l=await ut(s,`/v1/agents/${encodeURIComponent(n)}/start`,{},e.manifestPath);if(l.ok)a=!0,i.push(`adopted by pid ${s.pid}, live now`);else if(l.status===501)i.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(l.status===401)i.push(`pid ${s.pid} refused the request — set ${t.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${s.pid} could not adopt it${l.detail===void 0?"":`: ${l.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:n,enabled:!0,running:a,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:i.join(" · ")}]},null,2)}
393
- `);else if(process.stdout.write(`${u([{label:n,value:a?"running":"switched on",note:i.join(" · ")}])}
390
+ ${L("install")}
391
+ ${S(`skills install <agent> ${d[0]?.source}/${d[0]?.skill}`)}
392
+ `),o}function il(e,t){let r=new Map,i=t.map((s)=>{let a=`${s.source}/${s.skill}`;return r.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return qA(e,i).filter((s)=>s.score>0).map((s)=>r.get(s.skill.name)).filter((s)=>s!==void 0)}async function Vo(e){let t=al(e.manifestPath),r=await sr(t,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await ir(t,!0,void 0,e.store);let s=await ze(e.store),a=!1;if(s===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)i.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let d=await Ct(s,`/v1/agents/${encodeURIComponent(t)}/start`,{},e.manifestPath);if(d.ok)a=!0,i.push(`adopted by pid ${s.pid}, live now`);else if(d.status===501)i.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(d.status===401)i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${s.pid} could not adopt it${d.detail===void 0?"":`: ${d.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:t,enabled:!0,running:a,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:i.join(" · ")}]},null,2)}
393
+ `);else if(process.stdout.write(`${C([{label:t,value:a?"running":"switched on",note:i.join(" · ")}])}
394
394
  `),!a&&s!==void 0&&s.baseUrl!==void 0)process.stdout.write(`
395
- Switched on but not yet running. \`${t.slug} daemon restart\` picks it up.
396
- `);return s!==void 0&&s.baseUrl!==void 0&&!a?d:o}function al(e){let n=F(e);if(n.id===void 0||n.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 n.id}async function Jo(e){let n=await Tn(e.store),r=new Map;for(let a of n){if(a.serving===void 0)continue;let l=await sn(a.manifestPath,e.store);if(l!==void 0)r.set(a.ref,l)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:n.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
397
- `),o;let i=await Ft({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${u(In(n))}
398
- `);let s=[];for(let[a,l]of r)for(let c of l.values())s.push({label:`${a} / ${c.id}`,value:c.status,note:c.input!==void 0?`${c.detail??"enter this code"}: ${c.input.payload}`:c.detail??""});if(s.length>0)process.stdout.write(`
399
- ${u(s)}
400
- `);return i}import{copyFileSync as dl,existsSync as ll,mkdirSync as cl,readFileSync as ul,writeFileSync as fl}from"node:fs";import{dirname as ml,join as zo}from"node:path";async function Yo(e){let n=e.env??k([]),r=e.home??n.HOME??"",i=un(n),s=hn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:zo(r,s.configPath),line:s?.line,steps:s?.steps},null,2)}
401
- `),s===void 0?d:o;if(process.stdout.write(`${v("shift+enter",!0)}
402
- ${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.")}
395
+ Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
396
+ `);return s!==void 0&&s.baseUrl!==void 0&&!a?E:o}function al(e){let t=U(e);if(t.id===void 0||t.id==="")throw new n({code:"cli_start_agent_id_missing",message:`${e} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return t.id}async function Jo(e){let t=await xn(e.store),r=new Map;for(let a of t){if(a.serving===void 0)continue;let d=await an(a.manifestPath,e.store);if(d!==void 0)r.set(a.ref,d)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:t.map((a)=>({...a,channels:[...r.get(a.ref)?.values()??[]]}))},null,2)}
397
+ `),o;let i=await Ut({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${C(Tn(t))}
398
+ `);let s=[];for(let[a,d]of r)for(let l of d.values())s.push({label:`${a} / ${l.id}`,value:l.status,note:l.input!==void 0?`${l.detail??"enter this code"}: ${l.input.payload}`:l.detail??""});if(s.length>0)process.stdout.write(`
399
+ ${C(s)}
400
+ `);return i}import{copyFileSync as dl,existsSync as ll,mkdirSync as cl,readFileSync as ul,writeFileSync as fl}from"node:fs";import{dirname as ml,join as zo}from"node:path";async function Yo(e){let t=e.env??v([]),r=e.home??t.HOME??"",i=dn(t),s=mn(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:zo(r,s.configPath),line:s?.line,steps:s?.steps},null,2)}
401
+ `),s===void 0?E:o;if(process.stdout.write(`${L("shift+enter",!0)}
402
+ ${S("⌥ or ⇧ ⏎ already puts a new line in a message, everywhere, with no setup. This command is for shift+⏎, which a terminal can only send once it has been given a key binding.")}
403
403
  `),s===void 0)return process.stdout.write(`
404
- ${v("this terminal was not recognised")}
405
- ${y(`TERM_PROGRAM=${n.TERM_PROGRAM??"(unset)"} TERM=${n.TERM??"(unset)"}`)}
406
- ${y(`known: ${ss().map((a)=>a.name).join(", ")}`)}
407
- ${Q("⌥⏎ works here regardless — nothing needs configuring for it")}
408
- `),d;if(process.stdout.write(`
409
- ${v(s.name)}
410
- `),s.how!=="write"){process.stdout.write(`${y(s.how==="unverified"?`no verified recipe for this one — ${s.reason??"nobody has checked it"}`:`this one has to be done by hand — ${s.reason??"its settings are not a text file"}`)}
404
+ ${L("this terminal was not recognised")}
405
+ ${S(`TERM_PROGRAM=${t.TERM_PROGRAM??"(unset)"} TERM=${t.TERM??"(unset)"}`)}
406
+ ${S(`known: ${Qt().map((a)=>a.name).join(", ")}`)}
407
+ ${w("⌥⏎ works here regardless — nothing needs configuring for it")}
408
+ `),E;if(process.stdout.write(`
409
+ ${L(s.name)}
410
+ `),s.how!=="write"){process.stdout.write(`${S(s.how==="unverified"?`no verified recipe for this one — ${s.reason??"nobody has checked it"}`:`this one has to be done by hand — ${s.reason??"its settings are not a text file"}`)}
411
411
 
412
- `);for(let[a,l]of(s.steps??[]).entries())process.stdout.write(`${y(`${a+1}. ${l}`)}
412
+ `);for(let[a,d]of(s.steps??[]).entries())process.stdout.write(`${S(`${a+1}. ${d}`)}
413
413
  `);return process.stdout.write(s.how==="unverified"?`
414
- ${Q("⌥⏎ works here today — nothing has to be configured for it")}
414
+ ${w("⌥⏎ works here today — nothing has to be configured for it")}
415
415
  `:`
416
- ${Q("then restart the terminal and press shift+⏎ in a session to check it")}
417
- `),o}return await pl(s,{...e,env:n,home:r})}async function pl(e,n){let r=zo(n.home,e.configPath??""),i=ll(r)?ul(r,"utf8"):"";if(ms(i,e))return process.stdout.write(`${y("already configured — a binding for shift+enter is present")}
418
- ${y(oA(r,n.home),4)}
419
- `),o;let s=ps(i,e);if(s===void 0)return process.stdout.write(`${y("this file is not in a shape this command can edit safely:")}
420
- ${y(oA(r,n.home),4)}
421
- ${Q("add the line below by hand:")}
422
- ${y(e.line??"",4)}
423
- `),d;if(process.stdout.write(`${u([{label:"file",value:oA(r,n.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
424
- `),n.dryRun===!0)return process.stdout.write(`
425
- ${Q("--dry-run: nothing was written")}
426
- `),o;if(n.yes!==!0){if(!(n.confirm===void 0?!1:await n.confirm("write this change?")))return process.stdout.write(`
427
- ${Q("nothing was written")}
428
- `),o}try{if(cl(ml(r),{recursive:!0}),i!=="")dl(r,`${r}.${t.slug}-backup`);fl(r,s,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
429
- `),d}return process.stdout.write(`
430
- ${v("done")}
431
- ${i===""?"":`${y(`a copy of the old file is at ${oA(`${r}.${t.slug}-backup`,n.home)}`)}
432
- `}${Q("restart the terminal, then press shift+⏎ in a session to check it")}
433
- `),o}async function Zo(e){return e.warm===!0?await hl(e):await gl(e)}async function hl(e){let n=V(e.manifestPath,{env:k([e.manifestPath])}),r=ht(n.manifest.tools).selections,i=n.manifest.tools.pinned;if(r.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
434
- `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((c)=>c.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
435
- `),o;let s=[],a=new Set;for(let c of r){let m=ie[c.id];if(m===void 0)return d;let w;try{let f=m({dir:n.dir,env:n.env,config:c.config,agentId:n.manifest.id});if(f.refresh===void 0){for(let h of await f.resolve(i))a.add(h.spec.slug);if(e.json!==!0)process.stdout.write(`${c.id}: nothing to warm — it resolves without a cache.
436
- `);continue}w=await f.refresh(i)}catch(f){let h=p(f)?`${f.message}
437
- hint: ${f.hint}`:f instanceof Error?f.message:String(f);process.stdout.write(`${c.id}: not warmed — ${h}
438
- `);continue}for(let f of i)if(!w.missing.includes(f))a.add(f);s.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(s,null,2)}
439
- `);else for(let c of s){if(process.stdout.write(`${c.fetched} of ${i.length} pinned tools fetched from ${c.provider}
440
- `),c.changed.length>0)process.stdout.write(` changed: ${c.changed.join(", ")}
441
- `);if(c.cachePath!=="")process.stdout.write(` cache: ${c.cachePath}
442
- `)}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
443
- `);return l.length>0?d:o}async function gl(e){let n=await Ee.create({agents:[e.manifestPath],toolProviders:ie,modelTransports:Se,mediaProviders:de,builtInPlugins:Be,pluginRoot:ae(),scriptRunner:ue(),channels:le,env:k([e.manifestPath])});try{let r=n.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=Xo(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
444
- `:`${DA(i)}
445
- `),o}finally{await n.stop("cli-exit")}}import{dirname as ei,isAbsolute as yl,resolve as Rn}from"node:path";async function ni(e){try{let n=F(e.manifestPath),r=await Do({refs:n.plugins??[],agentId:n.id??e.manifestPath,paths:{workspace:ei(Rn(e.manifestPath)),state:ei(Rn(e.manifestPath)),manifest:Rn(e.manifestPath)},env:k([e.manifestPath]),bus:new Dt({runtimeId:"validate"}),builtIn:Be,pluginRoot:ae(),base:{toolProviders:ie,modelTransports:Se,mediaProviders:de,channels:le}}),i=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:s}=i,a=ye(s.model.main.id,s.model.main.capabilities),{workspace:l,warnings:c}=uA(i,a.promptStyle),m=No(Oo(i,{channels:r.channels})),w=await yn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let P of w.providers)await P.stop?.();let f=ho(s,{env:i.env,transports:new Map([...cA,...Object.entries(r.modelTransports)])});YA(s,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let h=$t(l,s.context.rules);if(h!==void 0&&s.context.rules.onExceed==="fail")throw h;let g=[...c,...r.failed,...w.warnings,...w.registry.warnings,...m,...Qo(s),...yo(s),...h===void 0?[]:[h.toDetail()]],b=s.knowledge===void 0?void 0:bo({dir:yl(s.knowledge.dir)?s.knowledge.dir:Rn(i.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:a.promptStyle}),x=["static","volatile","reminder"].map((P)=>{let T=l.files.filter((O)=>O.tier===P).map((O)=>O.name);if(T.length===0)return;return`${P}=${T.join(",")} (${l.tokens[P]}/${s.context.budgets[P]})`}).filter((P)=>P!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:s.id,model:s.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((P)=>({name:P.name,tier:P.tier,editable:P.editable,tokens:P.tokens,budget:P.budget})),tokens:l.tokens},knowledge:b===void 0?[]:b.entries.map((P)=>({name:P.name,keywords:P.keywords,tokens:P.tokens})),warnings:g},null,2)}
446
- `),o;let R=Nt(s),S=R.map((P)=>P.role===P.configuredAs?`${P.role}=${P.modelId}`:`${P.role}=→main`).join(" "),N=R.filter((P)=>P.role===P.configuredAs),H=Xi({manifestPath:e.manifestPath,rawModelId:n.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((P)=>{let T=$i(P.origin);return T===void 0?[]:[` env ${P.variable} — ${T}
416
+ ${w("then restart the terminal and press shift+⏎ in a session to check it")}
417
+ `),o}return await pl(s,{...e,env:t,home:r})}async function pl(e,t){let r=zo(t.home,e.configPath??""),i=ll(r)?ul(r,"utf8"):"";if(as(i,e))return process.stdout.write(`${S("already configured — a binding for shift+enter is present")}
418
+ ${S(iA(r,t.home),4)}
419
+ `),o;let s=fs(i,e);if(s===void 0)return process.stdout.write(`${S("this file is not in a shape this command can edit safely:")}
420
+ ${S(iA(r,t.home),4)}
421
+ ${w("add the line below by hand:")}
422
+ ${S(e.line??"",4)}
423
+ `),E;if(process.stdout.write(`${C([{label:"file",value:iA(r,t.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
424
+ `),t.dryRun===!0)return process.stdout.write(`
425
+ ${w("--dry-run: nothing was written")}
426
+ `),o;if(t.yes!==!0){if(!(t.confirm===void 0?!1:await t.confirm("write this change?")))return process.stdout.write(`
427
+ ${w("nothing was written")}
428
+ `),o}try{if(cl(ml(r),{recursive:!0}),i!=="")dl(r,`${r}.${A.slug}-backup`);fl(r,s,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
429
+ `),E}return process.stdout.write(`
430
+ ${L("done")}
431
+ ${i===""?"":`${S(`a copy of the old file is at ${iA(`${r}.${A.slug}-backup`,t.home)}`)}
432
+ `}${w("restart the terminal, then press shift+⏎ in a session to check it")}
433
+ `),o}async function Zo(e){return e.warm===!0?await hl(e):await gl(e)}async function hl(e){let t=z(e.manifestPath,{env:v([e.manifestPath])}),r=Bt(t.manifest.tools).selections,i=t.manifest.tools.pinned;if(r.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
434
+ `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((l)=>l.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
435
+ `),o;let s=[],a=new Set;for(let l of r){let u=ae[l.id];if(u===void 0)return E;let p;try{let c=u({dir:t.dir,env:t.env,config:l.config,agentId:t.manifest.id});if(c.refresh===void 0){for(let f of await c.resolve(i))a.add(f.spec.slug);if(e.json!==!0)process.stdout.write(`${l.id}: nothing to warm — it resolves without a cache.
436
+ `);continue}p=await c.refresh(i)}catch(c){let f=h(c)?`${c.message}
437
+ hint: ${c.hint}`:c instanceof Error?c.message:String(c);process.stdout.write(`${l.id}: not warmed — ${f}
438
+ `);continue}for(let c of i)if(!p.missing.includes(c))a.add(c);s.push({provider:l.id,fetched:p.fetched,changed:[...p.changed],missing:[...p.missing],cachePath:"cachePath"in p&&typeof p.cachePath==="string"?p.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(s,null,2)}
439
+ `);else for(let l of s){if(process.stdout.write(`${l.fetched} of ${i.length} pinned tools fetched from ${l.provider}
440
+ `),l.changed.length>0)process.stdout.write(` changed: ${l.changed.join(", ")}
441
+ `);if(l.cachePath!=="")process.stdout.write(` cache: ${l.cachePath}
442
+ `)}let d=i.filter((l)=>!a.has(l));for(let l of d)process.stdout.write(` missing: ${l} — no configured provider has a tool with that slug
443
+ `);return d.length>0?E:o}async function gl(e){let t=await Ce.create({agents:[e.manifestPath],toolProviders:ae,modelTransports:be,mediaProviders:Ee,builtInPlugins:Qe,pluginRoot:ge(),scriptRunner:pe(),channels:Ie,env:v([e.manifestPath])});try{let r=t.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=er(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
444
+ `:`${bA(i)}
445
+ `),o}finally{await t.stop("cli-exit")}}import{dirname as ei,isAbsolute as yl,resolve as En}from"node:path";async function ni(e){try{let t=U(e.manifestPath),r=await bo({refs:t.plugins??[],agentId:t.id??e.manifestPath,paths:{workspace:ei(En(e.manifestPath)),state:ei(En(e.manifestPath)),manifest:En(e.manifestPath)},env:v([e.manifestPath]),bus:new bt({runtimeId:"validate"}),builtIn:Qe,pluginRoot:ge(),base:{toolProviders:ae,modelTransports:be,mediaProviders:Ee,channels:Ie}}),i=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:s}=i,a=Se(s.model.main.id,s.model.main.capabilities),{workspace:d,warnings:l}=EA(i,a.promptStyle),u=Mo(No(i,{channels:r.channels})),p=await Qn(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let b of p.providers)await b.stop?.();let c=Bo(s,{env:i.env,transports:new Map([...lA,...Object.entries(r.modelTransports)])});jA(s,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let f=eA(d,s.context.rules);if(f!==void 0&&s.context.rules.onExceed==="fail")throw f;let m=[...l,...r.failed,...p.warnings,...p.registry.warnings,...u,...mo(s),...Qo(s),...f===void 0?[]:[f.toDetail()]],g=s.knowledge===void 0?void 0:Oo({dir:yl(s.knowledge.dir)?s.knowledge.dir:En(i.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:a.promptStyle}),R=["static","volatile","reminder"].map((b)=>{let x=d.files.filter((I)=>I.tier===b).map((I)=>I.name);if(x.length===0)return;return`${b}=${x.join(",")} (${d.tokens[b]}/${s.context.budgets[b]})`}).filter((b)=>b!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:s.id,model:s.model.main.id,window:i.window,capabilities:a,workspace:{files:d.files.map((b)=>({name:b.name,tier:b.tier,editable:b.editable,tokens:b.tokens,budget:b.budget})),tokens:d.tokens},knowledge:g===void 0?[]:g.entries.map((b)=>({name:b.name,keywords:b.keywords,tokens:b.tokens})),warnings:m},null,2)}
446
+ `),o;let P=Mt(s),y=P.map((b)=>b.role===b.configuredAs?`${b.role}=${b.modelId}`:`${b.role}=→main`).join(" "),j=P.filter((b)=>b.role===b.configuredAs),D=es({manifestPath:e.manifestPath,rawModelId:t.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((b)=>{let x=Xi(b.origin);return x===void 0?[]:[` env ${b.variable} — ${x}
447
447
  `]}).join("");return process.stdout.write(`ok ${i.path}
448
448
  id ${s.id}${s.name===void 0?"":` (${s.name})`}
449
- models ${S}
450
- `+H+` window ${i.window} ${gA(R[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${a.maxOutput})
451
- `+(N.length<2?"":`${N.slice(1).map((P)=>` ${P.role.padEnd(12)} ${P.modelId} · window ${P.window.contextWindow} ${gA(P.window)}
452
- `).join("")}`)+` capabilities thinking=${f.main.capabilities.thinking} promptCache=${f.main.capabilities.promptCache} nativeTools=${f.main.capabilities.nativeTools} strictSchema=${f.main.capabilities.strictSchema}
453
- `+wl(f.main.capabilities.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
454
- workspace ${x===""?"(none)":x}
455
- `+(b===void 0?"":` knowledge ${b.entries.length} entries, maxActive=${b.maxActive}, budget=${b.budget}
449
+ models ${y}
450
+ `+D+` window ${i.window} ${cA(P[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${a.maxOutput})
451
+ `+(j.length<2?"":`${j.slice(1).map((b)=>` ${b.role.padEnd(12)} ${b.modelId} · window ${b.window.contextWindow} ${cA(b.window)}
452
+ `).join("")}`)+` capabilities thinking=${c.main.capabilities.thinking} promptCache=${c.main.capabilities.promptCache} nativeTools=${c.main.capabilities.nativeTools} strictSchema=${c.main.capabilities.strictSchema}
453
+ `+wl(c.main.capabilities.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
454
+ workspace ${R===""?"(none)":R}
455
+ `+(g===void 0?"":` knowledge ${g.entries.length} entries, maxActive=${g.maxActive}, budget=${g.budget}
456
456
  `)+` memory ${s.memory===void 0?"none — nothing is retrieved across sessions":`${s.memory.retriever} at ${s.memory.dir}, maxActive=${s.memory.maxActive}, threshold=${s.memory.threshold}, budget=${s.memory.budget}, history=${s.memory.includeHistory}`}
457
- schedules ${s.schedules.length===0?"none":s.schedules.map((P)=>`${P.id} (${P.kind} ${P.expr}${P.timezone===void 0?"":` ${P.timezone}`}${P.role===void 0?"":` role=${P.role}`}${P.enabled?"":", disabled"})`).join(" ")}
458
- team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((P)=>`${P.id} (${P.manifest})`).join(" ")} — run one at a time`}
457
+ schedules ${s.schedules.length===0?"none":s.schedules.map((b)=>`${b.id} (${b.kind} ${b.expr}${b.timezone===void 0?"":` ${b.timezone}`}${b.role===void 0?"":` role=${b.role}`}${b.enabled?"":", disabled"})`).join(" ")}
458
+ team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((b)=>`${b.id} (${b.manifest})`).join(" ")} — run one at a time`}
459
459
  limits maxSteps=${s.limits.maxSteps} turnTimeoutMs=${s.limits.turnTimeoutMs}
460
- `+g.map((P)=>` warning ${P.message}
461
- `).join("")),o}catch(n){if(e.json===!0&&p(n))return process.stdout.write(`${JSON.stringify({ok:!1,error:n.toDetail(),details:n.details},null,2)}
462
- `),d;throw n}}function wl(e,n){if(e!=="none")return"";return/(^|\/)claude-/i.test(n)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
460
+ `+m.map((b)=>` warning ${b.message}
461
+ `).join("")),o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
462
+ `),E;throw t}}function wl(e,t){if(e!=="none")return"";return/(^|\/)claude-/i.test(t)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
463
463
  `+` caching at all, so no request field reaches it. Caching lives on the native
464
464
  Messages API, which this runtime does not speak.
465
465
  `:` promptCache none — this runtime sends no cache directives. Many endpoints cache
466
- `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function ti(e){try{let n=V(e.manifestPath,{env:k([e.manifestPath])}),{manifest:r}=n,i=ye(r.model.main.id,r.model.main.capabilities),{workspace:s,warnings:a}=uA(n,i.promptStyle),l=[...a,...Bi(s.files.map((w)=>({name:w.name,authored:w.authored,tier:w.tier,field:w.field})))],c=$t(s,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:n.path,promptStyle:i.promptStyle,files:s.files.map((w)=>({name:w.name,tier:w.tier,editable:w.editable,tokens:w.tokens,budget:w.budget})),tokens:s.tokens,findings:l},null,2)}
467
- `),e.strict===!0&&l.length>0?d:o;let m=i.promptStyle;process.stdout.write(`${n.path}
468
- rendering delimiters=${m.delimiters} intensity=${m.intensity} examplesIn=${m.examplesIn}
466
+ `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function ti(e){try{let t=z(e.manifestPath,{env:v([e.manifestPath])}),{manifest:r}=t,i=Se(r.model.main.id,r.model.main.capabilities),{workspace:s,warnings:a}=EA(t,i.promptStyle),d=[...a,...yi(s.files.map((p)=>({name:p.name,authored:p.authored,tier:p.tier,field:p.field})))],l=eA(s,r.context.rules);if(l!==void 0)d.push(l.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:d.length===0,path:t.path,promptStyle:i.promptStyle,files:s.files.map((p)=>({name:p.name,tier:p.tier,editable:p.editable,tokens:p.tokens,budget:p.budget})),tokens:s.tokens,findings:d},null,2)}
467
+ `),e.strict===!0&&d.length>0?E:o;let u=i.promptStyle;process.stdout.write(`${t.path}
468
+ rendering delimiters=${u.delimiters} intensity=${u.intensity} examplesIn=${u.examplesIn}
469
469
  total ${s.tokens.total} tokens (static ${s.tokens.static}, volatile ${s.tokens.volatile}, reminder ${s.tokens.reminder})
470
- `);for(let w of s.files)process.stdout.write(` ${w.name.padEnd(14)} ${w.tier.padEnd(9)} ${String(w.tokens).padStart(5)}/${w.budget} tokens, editable=${w.editable}
471
- `);if(l.length===0)return process.stdout.write(`
470
+ `);for(let p of s.files)process.stdout.write(` ${p.name.padEnd(14)} ${p.tier.padEnd(9)} ${String(p.tokens).padStart(5)}/${p.budget} tokens, editable=${p.editable}
471
+ `);if(d.length===0)return process.stdout.write(`
472
472
  no findings
473
- `),o;for(let w of l)process.stdout.write(`
474
- ${w.code}: ${w.message}
475
- `),process.stdout.write(` hint: ${w.hint}
473
+ `),o;for(let p of d)process.stdout.write(`
474
+ ${p.code}: ${p.message}
475
+ `),process.stdout.write(` hint: ${p.hint}
476
476
  `);return process.stdout.write(`
477
- ${l.length} finding(s)
478
- `),e.strict===!0?d:o}catch(n){if(e.json===!0&&p(n))return process.stdout.write(`${JSON.stringify({ok:!1,error:n.toDetail(),details:n.details},null,2)}
479
- `),d;throw n}}function bl(e){let n=$s(e);if(n!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${n} is not installed.
480
- 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.
481
- `),d;if(p(e))process.stderr.write(`${e.format()}
477
+ ${d.length} finding(s)
478
+ `),e.strict===!0?E:o}catch(t){if(e.json===!0&&h(t))return process.stdout.write(`${JSON.stringify({ok:!1,error:t.toDetail(),details:t.details},null,2)}
479
+ `),E;throw t}}function bl(e){let t=ws(e);if(t!==void 0)return process.stderr.write(`cli_interface_missing: this command draws the terminal UI, and ${t} is not installed.
480
+ hint: it is an optional dependency, left out by an install with --omit=optional. Reinstall without it (npm i -g ${A.slug}), or pass --plain where the command has it.
481
+ `),E;if(h(e))process.stderr.write(`${e.format()}
482
482
  `);else if(e instanceof Error){if(process.stderr.write(`${e.message}
483
- `),zt().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
483
+ `),$t().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
484
484
  `)}else process.stderr.write(`${String(e)}
485
- `);return d}async function $l(e){let n=is(e);switch(n.kind){case"version":return process.stdout.write(`${J}
486
- `),o;case"help":return process.stdout.write(Gn(n.command)),o;case"usage":return process.stdout.write(Gn()),d;case"command":break}let{command:r,positionals:i,flags:s}=n.parsed,a=i[0],l=()=>ve(a),c=r.flags.some((f)=>f.name==="store")?s.str("store"):void 0,m=await Ar({needsServer:r.needsServer,disabled:s.bool("no-bootstrap"),install:()=>nr(),...c===void 0?{}:{store:c}}),w=bA(m);if(w!==void 0)process.stderr.write(w);switch(r.name){case"init":{let f=s.str("dir"),h=s.str("user"),g=s.str("name"),b=s.str("purpose"),x=s.str("preset"),R=s.str("model"),S=s.str("base-url"),N=s.str("region"),H=s.str("api-key-env"),P=s.str("system"),T=s.str("web"),O=s.str("web-backend"),C=s.str("composio"),L=s.str("telegram"),B=s.str("telegram-allow"),K=s.str("whatsapp"),ee=s.str("whatsapp-number"),M=s.str("server"),Xe=s.str("schedules"),Ie=s.str("skills"),se=s.str("daemon");return await Xt({...f===void 0?{}:{dir:f},...h===void 0?{}:{user:h},...g===void 0?{}:{name:g},...b===void 0?{}:{purpose:b},...x===void 0?{}:{preset:x},...R===void 0?{}:{model:R},...S===void 0?{}:{baseUrl:S},...N===void 0?{}:{region:N},...H===void 0?{}:{apiKeyEnv:H},...P===void 0?{}:{system:P},...T===void 0?{}:{web:T},...O===void 0?{}:{webBackend:O},...C===void 0?{}:{composio:C},...L===void 0?{}:{telegram:L},...Xe===void 0?{}:{schedules:Xe},...B===void 0?{}:{telegramAllow:B},...K===void 0?{}:{whatsapp:K},...ee===void 0?{}:{whatsappNumber:ee},...M===void 0?{}:{server:M},...Ie===void 0?{}:{skills:Ie},...se===void 0?{}:{daemon:se},yes:s.bool("yes"),plain:s.bool("plain"),measureWindow:s.bool("measure-window"),installServer:nr})}case"run":{let f=s.str("session"),h=s.str("input"),g=s.str("store");return await ot({...i[0]===void 0?{}:{manifestPath:l()},...f===void 0?{}:{sessionKey:f},continueSession:s.bool("continue"),...h===void 0?{}:{once:h},...g===void 0?{}:{store:g},ephemeral:s.bool("ephemeral"),quiet:s.bool("quiet"),showReasoning:s.bool("show-reasoning"),noReasoning:s.bool("no-reasoning"),...s.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:s.bool("plain")})}case"schedules":{let f=s.str("store"),h=s.str("id"),g=s.str("enable"),b=s.str("disable");return await go({manifestPath:l(),...f===void 0?{}:{store:f},...h===void 0?{}:{id:h},...g===void 0?{}:{enable:g},...b===void 0?{}:{disable:b},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let f=s.str("session"),h=s.str("store"),g=s.num("limit");return await Go({manifestPath:l(),...f===void 0?{}:{sessionKey:f},...h===void 0?{}:{store:h},...g===void 0?{}:{limit:g},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"owner":{let f=s.str("store");return await Bs({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},...f===void 0?{}:{store:f},json:s.bool("json")})}case"memory":{let f=s.num("limit"),h=s.str("store");return await Rs({action:a,manifestPath:ve(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...f===void 0?{}:{limit:f},...h===void 0?{}:{store:h},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:f,readAction:h}=await import("./config-35r6n1gh.js"),g=h(a,i[1]);return await f({action:g.action,...g.ref===void 0?{}:{ref:g.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...s.str("channel")===void 0?{}:{channel:s.str("channel")},remove:s.bool("remove"),yes:s.bool("yes"),...s.str("store")===void 0?{}:{store:s.str("store")}})}case"validate":return await ni({manifestPath:l(),json:s.bool("json")});case"workspace":return ti({manifestPath:l(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let f=s.str("out");return Wo({action:a,file:i[1],...f===void 0?{}:{out:f}})}case"skills":{if(i.length===0)return await us({plain:s.bool("plain"),json:s.bool("json")});let f=i[2];return Kt({action:a,manifestPath:ve(i[1]??""),...f===void 0?{}:{name:f},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let f=s.str("path"),h=s.str("ref");return await qo({action:a,rest:i.slice(1),...f===void 0?{}:{path:f},...h===void 0?{}:{ref:h},json:s.bool("json")})}case"channels":{let f=as("channels",a),h=f.ref??i[1]??"",{channelsCommand:g}=await import("./channels-4t89qpdt.js");return await g({...f.action===void 0?{}:{action:f.action},manifestPath:ve(h),...i[2]===void 0?{}:{channelId:i[2]},json:s.bool("json"),installServer:nr})}case"plugins":{let f=s.str("ref"),h=s.str("name");return await mr({action:a,manifestPath:ve(i[1]??""),rest:i.slice(2),...f===void 0?{}:{ref:f},...h===void 0?{}:{name:h},json:s.bool("json")})}case"agents":{let f=s.str("store");return await vt({manifestPaths:i.map((h)=>ve(h)),...f===void 0?{}:{store:f},json:s.bool("json")})}case"restart":{let f=s.str("store");return await Hr({...a===void 0?{}:{manifestPath:l()},...f===void 0?{}:{store:f},json:s.bool("json")})}case"status":{let f=s.str("store");return await Jo({...f===void 0?{}:{store:f},json:s.bool("json")})}case"logs":{let f=s.num("lines"),h=s.str("store");return await Ft({action:"logs",...a===void 0?{}:{manifestPath:l()},...f===void 0?{}:{lines:f},follow:s.bool("follow"),truncate:s.bool("truncate"),...h===void 0?{}:{store:h},json:s.bool("json")})}case"serve":{let f=s.num("port"),h=s.str("host"),g=s.str("store");return await Mo({manifestPaths:i.map((b)=>ve(b)),...f===void 0?{}:{port:f},...h===void 0?{}:{host:h},...g===void 0?{}:{store:g},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await ys({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await Yo({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:MA});case"remove":return await Fr({...a===void 0?{}:{ref:a},dryRun:s.bool("dry-run"),filesOnly:s.bool("files-only"),prune:s.bool("prune"),all:s.bool("all"),yes:s.bool("yes"),json:s.bool("json"),...s.str("store")===void 0?{}:{store:s.str("store")},confirm:ts});case"stop":{let f=s.str("reason");return await $n({...a===void 0?{}:{manifestPath:l()},dryRun:s.bool("dry-run"),...f===void 0?{}:{reason:f},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await Vo({manifestPath:l(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:f}=await import("./web-zph4h3p9.js");return await f({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:f}=await import("./credential-dpdgg4j6.js");return await f({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...s.str("label")===void 0?{}:{label:s.str("label")},...s.str("agents")===void 0?{}:{agents:s.str("agents")},...s.str("sessions")===void 0?{}:{sessions:s.str("sessions")},...s.str("can")===void 0?{}:{can:s.str("can")},...s.str("expires")===void 0?{}:{expires:s.str("expires")},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"daemon":{let f=s.num("lines");return await Ft({action:a,...i[1]===void 0?{}:{manifestPath:ve(i[1])},...f===void 0?{}:{lines:f},follow:s.bool("follow"),truncate:s.bool("truncate"),dryRun:s.bool("dry-run"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"model":{let f=s.num("price");return await Ws({manifestPath:ve(i[1]),window:s.bool("window"),...f===void 0?{}:{price:f},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await Zo({manifestPath:l(),warm:s.bool("warm"),json:s.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."})}}ks();hs();vs();await $l(process.argv.slice(2)).catch(bl).then((e)=>lr(e));
485
+ `);return E}async function $l(e){let t=ss(e);switch(t.kind){case"version":return process.stdout.write(`${q}
486
+ `),o;case"help":return process.stdout.write(Dn(t.command)),o;case"usage":return process.stdout.write(Dn()),E;case"command":break}let{command:r,positionals:i,flags:s}=t.parsed,a=i[0],d=()=>Ge(a),l=r.flags.some((c)=>c.name==="store")?s.str("store"):void 0,u=await nr({needsServer:r.needsServer,disabled:s.bool("no-bootstrap"),install:()=>or(),...l===void 0?{}:{store:l}}),p=OA(u);if(p!==void 0)process.stderr.write(p);switch(r.name){case"init":{let c=s.str("dir"),f=s.str("user"),m=s.str("name"),g=s.str("purpose"),R=s.str("preset"),P=s.str("model"),y=s.str("base-url"),j=s.str("region"),D=s.str("api-key-env"),b=s.str("system"),x=s.str("web"),I=s.str("web-backend"),_=s.str("composio"),F=s.str("telegram"),V=s.str("telegram-allow"),N=s.str("whatsapp"),Z=s.str("whatsapp-number"),K=s.str("server"),Le=s.str("schedules"),$e=s.str("skills"),te=s.str("daemon");return await Wt({...c===void 0?{}:{dir:c},...f===void 0?{}:{user:f},...m===void 0?{}:{name:m},...g===void 0?{}:{purpose:g},...R===void 0?{}:{preset:R},...P===void 0?{}:{model:P},...y===void 0?{}:{baseUrl:y},...j===void 0?{}:{region:j},...D===void 0?{}:{apiKeyEnv:D},...b===void 0?{}:{system:b},...x===void 0?{}:{web:x},...I===void 0?{}:{webBackend:I},..._===void 0?{}:{composio:_},...F===void 0?{}:{telegram:F},...Le===void 0?{}:{schedules:Le},...V===void 0?{}:{telegramAllow:V},...N===void 0?{}:{whatsapp:N},...Z===void 0?{}:{whatsappNumber:Z},...K===void 0?{}:{server:K},...$e===void 0?{}:{skills:$e},...te===void 0?{}:{daemon:te},yes:s.bool("yes"),plain:s.bool("plain"),measureWindow:s.bool("measure-window"),installServer:or})}case"run":{let c=s.str("session"),f=s.str("input"),m=s.str("store");return await rt({...i[0]===void 0?{}:{manifestPath:d()},...c===void 0?{}:{sessionKey:c},continueSession:s.bool("continue"),...f===void 0?{}:{once:f},...m===void 0?{}:{store:m},ephemeral:s.bool("ephemeral"),quiet:s.bool("quiet"),showReasoning:s.bool("show-reasoning"),noReasoning:s.bool("no-reasoning"),...s.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:s.bool("plain")})}case"schedules":{let c=s.str("store"),f=s.str("id"),m=s.str("enable"),g=s.str("disable");return await go({manifestPath:d(),...c===void 0?{}:{store:c},...f===void 0?{}:{id:f},...m===void 0?{}:{enable:m},...g===void 0?{}:{disable:g},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let c=s.str("session"),f=s.str("store"),m=s.num("limit");return await Ho({manifestPath:d(),...c===void 0?{}:{sessionKey:c},...f===void 0?{}:{store:f},...m===void 0?{}:{limit:m},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"owner":{let c=s.str("store");return await Ws({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{store:c},json:s.bool("json")})}case"memory":{let c=s.num("limit"),f=s.str("store");return await Ps({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...c===void 0?{}:{limit:c},...f===void 0?{}:{store:f},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:c,readAction:f}=await import("./config-3mz4zwsf.js"),m=f(a,i[1]);return await c({action:m.action,...m.ref===void 0?{}:{ref:m.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...s.str("channel")===void 0?{}:{channel:s.str("channel")},remove:s.bool("remove"),yes:s.bool("yes"),...s.str("store")===void 0?{}:{store:s.str("store")}})}case"validate":return await ni({manifestPath:d(),json:s.bool("json")});case"workspace":return ti({manifestPath:d(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let c=s.str("out");return Wo({action:a,file:i[1],...c===void 0?{}:{out:c}})}case"skills":{if(i.length===0)return await Es({plain:s.bool("plain"),json:s.bool("json")});let c=i[2];return Yt({action:a,manifestPath:Ge(i[1]??""),...c===void 0?{}:{name:c},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let c=s.str("path"),f=s.str("ref");return await qo({action:a,rest:i.slice(1),...c===void 0?{}:{path:c},...f===void 0?{}:{ref:f},json:s.bool("json")})}case"channels":{let c=gs("channels",a),f=c.ref??i[1]??"",{channelsCommand:m}=await import("./channels-a9zx9yba.js");return await m({...c.action===void 0?{}:{action:c.action},manifestPath:Ge(f),...i[2]===void 0?{}:{channelId:i[2]},json:s.bool("json"),installServer:or})}case"plugins":{let c=s.str("ref"),f=s.str("name");return await mr({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...c===void 0?{}:{ref:c},...f===void 0?{}:{name:f},json:s.bool("json")})}case"agents":{let c=s.str("store");return await kt({manifestPaths:i.map((f)=>Ge(f)),...c===void 0?{}:{store:c},json:s.bool("json")})}case"restart":{let c=s.str("store");return await Mr({...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{store:c},json:s.bool("json")})}case"status":{let c=s.str("store");return await Jo({...c===void 0?{}:{store:c},json:s.bool("json")})}case"logs":{let c=s.num("lines"),f=s.str("store");return await Ut({action:"logs",...a===void 0?{}:{manifestPath:d()},...c===void 0?{}:{lines:c},follow:s.bool("follow"),truncate:s.bool("truncate"),...f===void 0?{}:{store:f},json:s.bool("json")})}case"serve":{let c=s.num("port"),f=s.str("host"),m=s.str("store");return await Lo({manifestPaths:i.map((g)=>Ge(g)),...c===void 0?{}:{port:c},...f===void 0?{}:{host:f},...m===void 0?{}:{store:m},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await ms({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await Yo({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:TA});case"remove":return await _r({...a===void 0?{}:{ref:a},dryRun:s.bool("dry-run"),filesOnly:s.bool("files-only"),prune:s.bool("prune"),all:s.bool("all"),yes:s.bool("yes"),json:s.bool("json"),...s.str("store")===void 0?{}:{store:s.str("store")},confirm:As});case"stop":{let c=s.str("reason");return await $n({...a===void 0?{}:{manifestPath:d()},dryRun:s.bool("dry-run"),...c===void 0?{}:{reason:c},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await Vo({manifestPath:d(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:c}=await import("./web-7mdrcb8a.js");return await c({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:c}=await import("./credential-ja7zmd4c.js");return await c({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...s.str("label")===void 0?{}:{label:s.str("label")},...s.str("agents")===void 0?{}:{agents:s.str("agents")},...s.str("sessions")===void 0?{}:{sessions:s.str("sessions")},...s.str("can")===void 0?{}:{can:s.str("can")},...s.str("expires")===void 0?{}:{expires:s.str("expires")},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"daemon":{let c=s.num("lines");return await Ut({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...c===void 0?{}:{lines:c},follow:s.bool("follow"),truncate:s.bool("truncate"),dryRun:s.bool("dry-run"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"model":{let c=s.num("price");return await Gs({manifestPath:Ge(i[1]),window:s.bool("window"),...c===void 0?{}:{price:c},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await Zo({manifestPath:d(),warm:s.bool("warm"),json:s.bool("json")});default:throw new n({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}vs();Bs();bs();await $l(process.argv.slice(2)).catch(bl).then((e)=>Ir(e));
487
487
 
488
- //# debugId=9DD151FC6202E27A64756E2164756E21
488
+ //# debugId=02CBB3535531C9CA64756E2164756E21
489
489
  //# sourceMappingURL=index.js.map