dispach 0.2.0-pilot.11 → 0.2.0-pilot.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (145) hide show
  1. package/dist/APEv2Parser-2vz72g1g.js +5 -0
  2. package/dist/AiffParser-rbjjk155.js +5 -0
  3. package/dist/{AiffParser-zry2dcmd.js.map → AiffParser-rbjjk155.js.map} +1 -1
  4. package/dist/{App-w7520pb8.js → App-7mb3d8v1.js} +8 -8
  5. package/dist/{App-w7520pb8.js.map → App-7mb3d8v1.js.map} +1 -1
  6. package/dist/{AsfParser-5y1jqcjp.js → AsfParser-bedaycyh.js} +2 -2
  7. package/dist/{ConfigEditor-zeaexfb7.js → ConfigEditor-rz1cgr5x.js} +2 -2
  8. package/dist/DsdiffParser-bgjkyws0.js +5 -0
  9. package/dist/{DsdiffParser-kwy431r7.js.map → DsdiffParser-bgjkyws0.js.map} +1 -1
  10. package/dist/{DsfParser-q7hdxgrc.js → DsfParser-b886w01y.js} +2 -2
  11. package/dist/FlacParser-nre0v2fj.js +5 -0
  12. package/dist/{KeyProbe-mr7cgsfy.js → KeyProbe-6v095zeb.js} +2 -2
  13. package/dist/MP4Parser-kgm0h57x.js +5 -0
  14. package/dist/{MP4Parser-q77agvt9.js.map → MP4Parser-kgm0h57x.js.map} +1 -1
  15. package/dist/{MatroskaParser-tgyy0yvr.js → MatroskaParser-8s082chk.js} +2 -2
  16. package/dist/{MpegParser-drv4aqcw.js → MpegParser-6z25pvms.js} +3 -3
  17. package/dist/{MpegParser-drv4aqcw.js.map → MpegParser-6z25pvms.js.map} +1 -1
  18. package/dist/{MusepackParser-cyk5cxhn.js → MusepackParser-0qyp97mp.js} +2 -2
  19. package/dist/{OggParser-8de3gn04.js → OggParser-tnrbtgh0.js} +2 -2
  20. package/dist/{Picker-j6n1pda7.js → Picker-1wc5b3j6.js} +3 -3
  21. package/dist/{Picker-j6n1pda7.js.map → Picker-1wc5b3j6.js.map} +1 -1
  22. package/dist/{SessionPicker-6ac1574k.js → SessionPicker-msy4q87n.js} +2 -2
  23. package/dist/{SkillBrowser-djqmg8gg.js → SkillBrowser-40jpxzd4.js} +3 -3
  24. package/dist/{SkillBrowser-djqmg8gg.js.map → SkillBrowser-40jpxzd4.js.map} +1 -1
  25. package/dist/{WavPackParser-t5w3x5py.js → WavPackParser-894pr6fr.js} +2 -2
  26. package/dist/{WaveParser-bahy59fn.js → WaveParser-872sshw3.js} +2 -2
  27. package/dist/{WizardApp-aaggpzrr.js → WizardApp-k43w5pfv.js} +3 -3
  28. package/dist/{WizardApp-aaggpzrr.js.map → WizardApp-k43w5pfv.js.map} +1 -1
  29. package/dist/{channels-473gvnrt.js → channels-x2d7g01r.js} +5 -5
  30. package/dist/{channels-473gvnrt.js.map → channels-x2d7g01r.js.map} +1 -1
  31. package/dist/client.d.ts +10 -0
  32. package/dist/client.js +2 -2
  33. package/dist/client.js.map +4 -4
  34. package/dist/{config-cba40q0x.js → config-d1xb6rwr.js} +19 -19
  35. package/dist/{config-cba40q0x.js.map → config-d1xb6rwr.js.map} +1 -1
  36. package/dist/{credential-5g1zskdk.js → credential-ghqxh2eg.js} +2 -2
  37. package/dist/{index-s1szab5x.js → index-0fh8rhgw.js} +2 -2
  38. package/dist/{index-xaahw3zf.js → index-0x9j2qjg.js} +3 -3
  39. package/dist/{index-xaahw3zf.js.map → index-0x9j2qjg.js.map} +1 -1
  40. package/dist/{index-hjvv7xes.js → index-1qwyr9dj.js} +2 -2
  41. package/dist/{index-n4eedpq7.js → index-1xd6yfbh.js} +2 -2
  42. package/dist/{index-f6jg05cs.js → index-5v9ybqh5.js} +30 -30
  43. package/dist/index-5v9ybqh5.js.map +12 -0
  44. package/dist/{index-0hhw1s9z.js → index-5y06tb8d.js} +2 -2
  45. package/dist/{index-7akvq1g1.js → index-7n00wj27.js} +29 -29
  46. package/dist/{index-7akvq1g1.js.map → index-7n00wj27.js.map} +1 -1
  47. package/dist/{index-w64hxpyf.js → index-9f771kmt.js} +6 -6
  48. package/dist/{index-w64hxpyf.js.map → index-9f771kmt.js.map} +1 -1
  49. package/dist/{index-7jy19x9b.js → index-a2nbjq8e.js} +3 -3
  50. package/dist/{index-7jy19x9b.js.map → index-a2nbjq8e.js.map} +1 -1
  51. package/dist/index-f0eeh0e2.js +6 -0
  52. package/dist/{index-g9v6cy45.js.map → index-f0eeh0e2.js.map} +1 -1
  53. package/dist/{index-tbnbw2fm.js → index-f49fv8pa.js} +2 -2
  54. package/dist/{index-tdtycvp0.js → index-g1p6m2b6.js} +5 -5
  55. package/dist/{index-tdtycvp0.js.map → index-g1p6m2b6.js.map} +1 -1
  56. package/dist/{index-gwxm26c8.js → index-g7p7m95k.js} +7 -7
  57. package/dist/{index-gwxm26c8.js.map → index-g7p7m95k.js.map} +1 -1
  58. package/dist/{index-ysa7hs65.js → index-g835zmer.js} +2 -2
  59. package/dist/{index-vcmys6ss.js → index-h8nygehe.js} +4 -4
  60. package/dist/{index-vcmys6ss.js.map → index-h8nygehe.js.map} +1 -1
  61. package/dist/{index-zkym8848.js → index-hx5vfjgf.js} +4 -4
  62. package/dist/{index-zkym8848.js.map → index-hx5vfjgf.js.map} +1 -1
  63. package/dist/{index-45mab5vk.js → index-j3e122r9.js} +4 -4
  64. package/dist/{index-45mab5vk.js.map → index-j3e122r9.js.map} +1 -1
  65. package/dist/{index-7xb94248.js → index-jx50753v.js} +4 -4
  66. package/dist/{index-7xb94248.js.map → index-jx50753v.js.map} +1 -1
  67. package/dist/{index-hgmt3w0e.js → index-k1rmxdxp.js} +4 -4
  68. package/dist/{index-hgmt3w0e.js.map → index-k1rmxdxp.js.map} +1 -1
  69. package/dist/{index-z2c8pytd.js → index-k2fp5wsv.js} +45 -45
  70. package/dist/{index-z2c8pytd.js.map → index-k2fp5wsv.js.map} +1 -1
  71. package/dist/{index-jbnn0d4r.js → index-m9sxtq0p.js} +4 -4
  72. package/dist/{index-jbnn0d4r.js.map → index-m9sxtq0p.js.map} +1 -1
  73. package/dist/{index-vj53nd8y.js → index-myd646mz.js} +2 -2
  74. package/dist/{index-p6mrqa6w.js → index-n23ycxer.js} +14 -14
  75. package/dist/{index-p6mrqa6w.js.map → index-n23ycxer.js.map} +2 -2
  76. package/dist/{index-8r75tf6v.js → index-nw5rsr24.js} +6 -6
  77. package/dist/{index-8r75tf6v.js.map → index-nw5rsr24.js.map} +1 -1
  78. package/dist/{index-f9hvx8j0.js → index-pjn9rksn.js} +9 -9
  79. package/dist/{index-f9hvx8j0.js.map → index-pjn9rksn.js.map} +1 -1
  80. package/dist/{index-dnm674eg.js → index-prs76s9x.js} +4 -4
  81. package/dist/{index-dnm674eg.js.map → index-prs76s9x.js.map} +1 -1
  82. package/dist/{index-3bj4jmzt.js → index-r5wptwfx.js} +4 -4
  83. package/dist/{index-3bj4jmzt.js.map → index-r5wptwfx.js.map} +1 -1
  84. package/dist/index-rdfy5wjx.js +1148 -0
  85. package/dist/{index-hy8tgxtt.js.map → index-rdfy5wjx.js.map} +11 -11
  86. package/dist/{index-7y4xej0x.js → index-rgez2vg3.js} +2 -2
  87. package/dist/{index-zzq38p11.js → index-rgvnpnwe.js} +19 -19
  88. package/dist/{index-zzq38p11.js.map → index-rgvnpnwe.js.map} +2 -2
  89. package/dist/{index-3hc7yk2j.js → index-t03x33yv.js} +2 -2
  90. package/dist/index-tpmnrjwt.js +6 -0
  91. package/dist/{index-b14can5c.js.map → index-tpmnrjwt.js.map} +1 -1
  92. package/dist/{index-az0s35qx.js → index-v0c8rkx2.js} +2 -2
  93. package/dist/{index-442x31t7.js → index-vdveqv55.js} +2 -2
  94. package/dist/{index-zexaphwb.js → index-x8yqdb0z.js} +2 -2
  95. package/dist/{index-0edatywx.js → index-xwa9phcm.js} +33 -33
  96. package/dist/{index-0edatywx.js.map → index-xwa9phcm.js.map} +1 -1
  97. package/dist/{index-fdks6f1s.js → index-y6pv5wfg.js} +3 -3
  98. package/dist/{index-fdks6f1s.js.map → index-y6pv5wfg.js.map} +1 -1
  99. package/dist/{index-gfbggwrd.js → index-za4402qp.js} +47 -47
  100. package/dist/{index-gfbggwrd.js.map → index-za4402qp.js.map} +4 -4
  101. package/dist/index.js +74 -74
  102. package/dist/index.js.map +2 -2
  103. package/dist/{web-v93ey21m.js → web-memgad0h.js} +4 -4
  104. package/dist/{web-v93ey21m.js.map → web-memgad0h.js.map} +1 -1
  105. package/dist/wire.d.ts +11 -0
  106. package/dist/wire.js +2 -2
  107. package/dist/wire.js.map +4 -4
  108. package/dist/wrapper-djxwcj55.js +5 -0
  109. package/package.json +1 -1
  110. package/dist/APEv2Parser-4s0g9cgm.js +0 -5
  111. package/dist/AiffParser-zry2dcmd.js +0 -5
  112. package/dist/DsdiffParser-kwy431r7.js +0 -5
  113. package/dist/FlacParser-g3bp67z7.js +0 -5
  114. package/dist/MP4Parser-q77agvt9.js +0 -5
  115. package/dist/index-b14can5c.js +0 -6
  116. package/dist/index-f6jg05cs.js.map +0 -12
  117. package/dist/index-g9v6cy45.js +0 -6
  118. package/dist/index-hy8tgxtt.js +0 -1148
  119. package/dist/wrapper-62c5fhqp.js +0 -5
  120. /package/dist/{APEv2Parser-4s0g9cgm.js.map → APEv2Parser-2vz72g1g.js.map} +0 -0
  121. /package/dist/{AsfParser-5y1jqcjp.js.map → AsfParser-bedaycyh.js.map} +0 -0
  122. /package/dist/{ConfigEditor-zeaexfb7.js.map → ConfigEditor-rz1cgr5x.js.map} +0 -0
  123. /package/dist/{DsfParser-q7hdxgrc.js.map → DsfParser-b886w01y.js.map} +0 -0
  124. /package/dist/{FlacParser-g3bp67z7.js.map → FlacParser-nre0v2fj.js.map} +0 -0
  125. /package/dist/{KeyProbe-mr7cgsfy.js.map → KeyProbe-6v095zeb.js.map} +0 -0
  126. /package/dist/{MatroskaParser-tgyy0yvr.js.map → MatroskaParser-8s082chk.js.map} +0 -0
  127. /package/dist/{MusepackParser-cyk5cxhn.js.map → MusepackParser-0qyp97mp.js.map} +0 -0
  128. /package/dist/{OggParser-8de3gn04.js.map → OggParser-tnrbtgh0.js.map} +0 -0
  129. /package/dist/{SessionPicker-6ac1574k.js.map → SessionPicker-msy4q87n.js.map} +0 -0
  130. /package/dist/{WavPackParser-t5w3x5py.js.map → WavPackParser-894pr6fr.js.map} +0 -0
  131. /package/dist/{WaveParser-bahy59fn.js.map → WaveParser-872sshw3.js.map} +0 -0
  132. /package/dist/{credential-5g1zskdk.js.map → credential-ghqxh2eg.js.map} +0 -0
  133. /package/dist/{index-s1szab5x.js.map → index-0fh8rhgw.js.map} +0 -0
  134. /package/dist/{index-hjvv7xes.js.map → index-1qwyr9dj.js.map} +0 -0
  135. /package/dist/{index-n4eedpq7.js.map → index-1xd6yfbh.js.map} +0 -0
  136. /package/dist/{index-0hhw1s9z.js.map → index-5y06tb8d.js.map} +0 -0
  137. /package/dist/{index-tbnbw2fm.js.map → index-f49fv8pa.js.map} +0 -0
  138. /package/dist/{index-ysa7hs65.js.map → index-g835zmer.js.map} +0 -0
  139. /package/dist/{index-vj53nd8y.js.map → index-myd646mz.js.map} +0 -0
  140. /package/dist/{index-7y4xej0x.js.map → index-rgez2vg3.js.map} +0 -0
  141. /package/dist/{index-3hc7yk2j.js.map → index-t03x33yv.js.map} +0 -0
  142. /package/dist/{index-az0s35qx.js.map → index-v0c8rkx2.js.map} +0 -0
  143. /package/dist/{index-442x31t7.js.map → index-vdveqv55.js.map} +0 -0
  144. /package/dist/{index-zexaphwb.js.map → index-x8yqdb0z.js.map} +0 -0
  145. /package/dist/{wrapper-62c5fhqp.js.map → wrapper-djxwcj55.js.map} +0 -0
package/dist/index.js CHANGED
@@ -1,31 +1,31 @@
1
1
  #!/usr/bin/env node
2
- import{A,Y,B,t,QA,Ft,JA,Ut,it,pe,ao,ei,Ai,st,go,yA,co,mA,xt,uA,lo,Io,Ve,G,J,oi,Sr,Ht,j,Co,fo,ct,Kt,po,lt,V,ue,ai,Ie,un,Bo,ho,gi,ci,li,R,ks}from"./index-hy8tgxtt.js";import{ir,ve,sr,ar,xA,gr,cr,lr}from"./index-f6jg05cs.js";import{te,me,ce,le,se,fe,Hr}from"./index-gfbggwrd.js";import{Js}from"./index-0yfwt2xf.js";import{Cn}from"./index-vcmys6ss.js";import{Mt,Tt,Wn,Le,ts,ns,Ar,xr,tr,gA,nr,Rt,GA,or,FA,_t,os,rs}from"./index-7akvq1g1.js";import{Wo,$t,LA,vr,zo,wt,Zo,Gn,Dt,Fn,en,Un,xn,ji,Hn,Kn,Yn}from"./index-z2c8pytd.js";import{kt,Lt,ro,an,io,Pt,hr,gn,nA,rt,HA,vt,Qr}from"./index-tdtycvp0.js";import{Ur,qi,An,Vi,Wi,zi,ZA}from"./index-p6mrqa6w.js";import{tn,eA,nn,$i}from"./index-vj53nd8y.js";import{Ln,Pn,Zt,qo,St,Pi,vn,Fi,Ui}from"./index-ysa7hs65.js";import"./index-58sfewaf.js";import{Jo}from"./index-4d3tmeda.js";import{kA,Xt,Ki,Yi}from"./index-tbnbw2fm.js";import{bt,Ji}from"./index-e99e8wvr.js";import{Ke}from"./index-3hc7yk2j.js";import{Zi}from"./index-s1szab5x.js";import{es,$o,er,Ye,je,PA,As,vA,ye,Nt,aA,Vn}from"./index-jbnn0d4r.js";import{Pe,AA}from"./index-n4eedpq7.js";import{Xn,BA,ss,U,gs,Je,cA,rr,cs}from"./index-h050xv73.js";import{u,_,y,Q,XA,sn,$A,et}from"./index-45mab5vk.js";import{KA,Se,ne,yr,F,oe,mr,cn,ln,Zr,Ns,Gt,Ms,Z,Ge}from"./index-hgmt3w0e.js";import{_e}from"./index-0hhw1s9z.js";import{xs,Ks}from"./index-vcjasmkq.js";import{wo,ea,wA,be,Oo,_o,o,d,fn}from"./index-svwaxgs5.js";async function yn(e){let s=await vA(e),r=[];for(let i of Z()){let n=i.id??i.ref,a=await er(n,e)??{enabled:!0},l=s.find((f)=>f.agentId===n),c=l===void 0?Number.NaN:Date.now()-Date.parse(l.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...l===void 0?{}:{pid:l.pid,serving:`serving · ${l.mode} · pid ${l.pid}${Number.isFinite(c)?` · up ${sn(c)}`:""}`}})}return r}function wn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((s)=>({label:s.ref,value:s.problem!==void 0?"broken":s.enabled?"on":"off",note:s.problem??s.serving??(s.enabled?`not hosted${s.modelId===void 0?"":` · ${s.modelId}`}`:`switched off${s.reason===void 0?"":` — ${s.reason}`}`)}))}async function pt(e){if(e.manifestPaths.length===0){let a=await yn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
2
+ import{A,Y,B,t,yA,Ft,JA,Ut,it,pe,ao,ei,Ai,st,go,QA,co,mA,xt,uA,lo,Io,Ve,G,J,oi,Sr,Ht,j,Co,fo,ct,Kt,po,lt,V,ue,ai,Ie,un,Bo,ho,gi,ci,li,R,ks}from"./index-rdfy5wjx.js";import{ir,ve,sr,ar,xA,gr,cr,lr}from"./index-5v9ybqh5.js";import{te,me,ce,le,se,fe,Hr}from"./index-za4402qp.js";import{Js}from"./index-0yfwt2xf.js";import{Cn}from"./index-h8nygehe.js";import{Mt,Tt,Wn,Le,ts,ns,Ar,xr,tr,gA,nr,Rt,GA,or,FA,_t,os,rs}from"./index-7n00wj27.js";import{Wo,$t,LA,vr,zo,wt,Zo,Gn,Dt,Fn,en,Un,xn,ji,Hn,Kn,Yn}from"./index-k2fp5wsv.js";import{kt,Lt,ro,an,io,Pt,hr,gn,nA,rt,HA,vt,yr}from"./index-g1p6m2b6.js";import{Ur,qi,An,Vi,Wi,zi,ZA}from"./index-n23ycxer.js";import{tn,eA,nn,$i}from"./index-myd646mz.js";import{Ln,Pn,Zt,qo,St,Pi,vn,Fi,Ui}from"./index-g835zmer.js";import"./index-58sfewaf.js";import{Jo}from"./index-4d3tmeda.js";import{kA,Xt,Ki,Yi}from"./index-f49fv8pa.js";import{bt,Ji}from"./index-e99e8wvr.js";import{Ke}from"./index-t03x33yv.js";import{Zi}from"./index-0fh8rhgw.js";import{es,$o,er,Ye,je,PA,As,vA,Qe,Nt,aA,Vn}from"./index-m9sxtq0p.js";import{Pe,AA}from"./index-1xd6yfbh.js";import{Xn,BA,ss,U,gs,Je,cA,rr,cs}from"./index-h050xv73.js";import{u,_,Q,y,XA,sn,$A,et}from"./index-j3e122r9.js";import{KA,Se,ne,Qr,F,oe,mr,cn,ln,Zr,Ns,Gt,Ms,Z,Ge}from"./index-k1rmxdxp.js";import{_e}from"./index-5y06tb8d.js";import{xs,Ks}from"./index-vcjasmkq.js";import{wo,ea,wA,be,Oo,_o,o,d,fn}from"./index-svwaxgs5.js";async function yn(e){let s=await vA(e),r=[];for(let i of Z()){let n=i.id??i.ref,a=await er(n,e)??{enabled:!0},l=s.find((f)=>f.agentId===n),c=l===void 0?Number.NaN:Date.now()-Date.parse(l.startedAt);r.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...l===void 0?{}:{pid:l.pid,serving:`serving · ${l.mode} · pid ${l.pid}${Number.isFinite(c)?` · up ${sn(c)}`:""}`}})}return r}function wn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((s)=>({label:s.ref,value:s.problem!==void 0?"broken":s.enabled?"on":"off",note:s.problem??s.serving??(s.enabled?`not hosted${s.modelId===void 0?"":` · ${s.modelId}`}`:`switched off${s.reason===void 0?"":` — ${s.reason}`}`)}))}async function pt(e){if(e.manifestPaths.length===0){let a=await yn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
3
  `);else process.stdout.write(`${u(wn(a))}
4
4
  `);return o}let s=await Ie.create({agents:[...e.manifestPaths],toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,env:R(e.manifestPaths),store:e.store??F(),lease:!1});U(()=>s.stop("cli-exit"));let r=s.list().map((a)=>a.describe()),i=new Map;for(let a of await s.store.leases.all()){if(a.runtimeId===s.runtimeId||!V(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 ${sn(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
5
  `),o;let n=r.map((a)=>({label:a.id,value:`${a.model} ${String(a.window).padStart(7)} window`,note:i.get(a.id)??a.name}));return process.stdout.write(`${u(n)}
6
6
  `),o}import{basename as Rn,dirname as ni,join as de,resolve as ti}from"node:path";import{rmSync as jo}from"node:fs";import{isAbsolute as ht,join as Fo,resolve as gt}from"node:path";var Lo=3;async function yt(e){if(e.answers.skills!=="find")return;let s=e.answers.skillsSearch?.trim()??"";if(s===""){process.stdout.write("\nno words to search for, so no skill was installed — `sources search <words>` when you know what you want\n");return}let r=Le(e.env);if(r.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
7
  searching ${r.length} skill source(s) for ${JSON.stringify(s)}
8
- `);let i=[],n=[];for(let m of r){if(!gA(m.name,e.env))try{await Rt(m,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(p){n.push(`${m.name} — ${B(p)?p.message:String(p)}`);continue}i.push(...GA(m,e.env))}for(let m of n)process.stdout.write(Q(`could not fetch ${m}
9
- `));if(i.length===0){process.stdout.write(`${Q("no source could be read, so no skill was installed — the directory is there and empty")}
10
- ${Q("`sources update` reports why; `sources search <words>` when it works",4)}
11
- `);return}let a=Uo(s,i);if(a.length===0){process.stdout.write(`${Q(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
- ${Q("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(`${Q(`best of ${i.length}: ${c}`)}
14
- `),a.length>1)process.stdout.write(`${Q(`also matched: ${a.slice(1,1+Lo).map((m)=>`${m.source}/${m.skill}`).join(", ")}`,4)}
8
+ `);let i=[],n=[];for(let m of r){if(!gA(m.name,e.env))try{await Rt(m,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(p){n.push(`${m.name} — ${B(p)?p.message:String(p)}`);continue}i.push(...GA(m,e.env))}for(let m of n)process.stdout.write(y(`could not fetch ${m}
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=Uo(s,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+Lo).map((m)=>`${m.source}/${m.skill}`).join(", ")}`,4)}
15
15
  `);if(process.stdout.write(`
16
16
  `),FA({action:"install",manifestPath:e.manifestPath,name:c,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==o)return;let g=Ko(e.manifestPath,e.envOverlay);if(g!==void 0)Mo(e.manifestPath,l.skill,e.envOverlay),process.stdout.write(`
17
- ${y(`${c} was removed again: it does not load on this machine`)}
18
- ${Q(g,4)}
19
- ${Q("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
- `)}function Uo(e,s){let r=new Map,i=s.filter((n)=>n.problem===void 0).map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return Kt(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}function Ko(e,s){try{let r=J(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=r.manifest.skills;if(i===void 0)return;let n=pe(r.manifest.model.main.id,r.manifest.model.main.capabilities);ct({dir:ht(i.dir)?i.dir:gt(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:n.promptStyle,agentDir:r.dir,runner:le()});return}catch(r){return B(r)?r.message:String(r)}}function Mo(e,s,r){try{let i=J(e,{...r===void 0?{}:{env:{...process.env,...r}}}),n=i.manifest.skills;if(n===void 0)return;let a=ht(n.dir)?n.dir:gt(i.dir,n.dir);jo(Fo(a,s),{recursive:!0,force:!0}),or(a,s)}catch{}}import{existsSync as Do,mkdirSync as Ho,writeFileSync as Go}from"node:fs";import{dirname as Vo,join as bn,resolve as $n,sep as Xo}from"node:path";var He={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function kn(e,s,r){let i=[];for(;;){let n=rt(e,r);if(n===void 0)break;if(n.optional===!0){e[n.step]="";continue}if(n.fallback===""){i.push(n.step),e[n.step]="(missing)";continue}let a=HA(n.step,n.fallback);if(a.ok)e[n.step]=a.value}if(i.length>0){let n=i.map((a)=>He[a]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${s}), and ${i.join(", ")} ${i.length===1?"has":"have"} no default.`,hint:`Pass ${n} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Sn(e,s){let r=e,i=kt(r.preset),n=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??Lt(r.dirChoice,r.name,s);if(l===void 0)throw new t({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(r.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:r.user,name:r.name,purpose:r.purpose,preset:r.preset,model:r.model,baseUrl:r.baseUrl,system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:Yo(l,s.agentDirBase)?Ns(s.agentDirBase,Et):Et()}:{},...n===void 0?{}:{apiKeyEnv:n},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function Yo(e,s){let r=$n(e),i=$n(s);return r===i||r.startsWith(i+Xo)}function Et(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((s)=>s.toString(16).padStart(2,"0")).join("")}function Ae(e,s){let r=s.map((i)=>bn(e,i.relPath)).filter((i)=>Do(i));if(r.length>0)throw new t({code:"cli_init_target_exists",message:`${r.length} of the files init would write already exist: ${r.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of s){let n=bn(e,i.relPath);Ho(Vo(n),{recursive:!0}),Go(n,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function We(e,s){let r=J(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=pe(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:n,warnings:a}=lt(r,i.promptStyle),l=JA(n,r.manifest.context.rules);if(l!==void 0&&r.manifest.context.rules.onExceed==="fail")throw l;return{distilled:a.some((c)=>c.code==="soul_distilled")}}var At=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."}]]),En=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 Ot(e){let s=HA(e.step,e.fallback);return s.ok?s.value:e.fallback}function Qo(e,s){let r=En.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Ot(e),optional:e.optional===!0,secret:gn.has(e.step),...s===void 0?{}:{requires:s},...e.options===void 0?{}:{choices:e.options.filter((i)=>r?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var It=64;function Ct(e){let s=new Map,r=new Set,i=(a,l)=>{let c={...a},f=[];for(let g=0;g<It;g+=1){let m=rt(c,e);if(m===void 0)break;let p=Ot(m);if(!At.has(m.step)&&!s.has(m.step))s.set(m.step,Qo(m,l));for(let h of m.options??[]){if(h.value===p)continue;if(En.get(m.step)?.has(h.value)===!0)continue;f.push({seed:{...c,[m.step]:h.value},opened:{step:m.step,value:h.value}})}c[m.step]=p}return f},n=[...i({})];for(let a=0;a<It&&n.length>0;a+=1){let l=n.splice(0,n.length);for(let c of l){let f=`${c.opened.step}=${c.opened.value}`;if(r.has(f))continue;r.add(f),n.push(...i(c.seed,c.opened))}}return[...s.values()].sort((a,l)=>hr.indexOf(a.step)-hr.indexOf(l.step))}function jt(e){let s={};for(let[c,f]of Object.entries(e.answers)){let g=c;if(!(g in He))throw new t({code:"provision_unknown_answer",message:`"${c}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:c});let m=At.get(g);if(m!==void 0)throw new t({code:m.code,message:`"${c}" cannot be set over the API.`,hint:m.hint,field:c});let p=En.get(g)?.get(f.trim().toLowerCase());if(p!==void 0)throw new t({code:p.code,message:`${c} is ${JSON.stringify(f)}, which this runtime cannot do over the API.`,hint:p.hint,field:c});let h=HA(g,f);if(!h.ok)throw new t({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(f)}, which ${h.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:c});s[g]=h.value}kn(s,"this is the provisioning API",e.defaults);let r=Sn(s,e.defaults),i=nA(r.name),n=Lt("sandbox",r.name,e.defaults);if(n===void 0)throw new t({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(r.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=$n(n),l=Qr({...r,dir:a});return Ae(a,l),{agentId:i,dir:a,manifestPath:bn(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function si(e){if(e.web!=="search")return;return ro(e.webBackend??"tavily")?.apiKeyEnv}async function Wt(e){let s=await qt(e);if(s.kind==="aborted")return process.stdout.write(`nothing written
17
+ ${Q(`${c} was removed again: it does not load on this machine`)}
18
+ ${y(g,4)}
19
+ ${y("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
+ `)}function Uo(e,s){let r=new Map,i=s.filter((n)=>n.problem===void 0).map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return Kt(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}function Ko(e,s){try{let r=J(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=r.manifest.skills;if(i===void 0)return;let n=pe(r.manifest.model.main.id,r.manifest.model.main.capabilities);ct({dir:ht(i.dir)?i.dir:gt(r.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:n.promptStyle,agentDir:r.dir,runner:le()});return}catch(r){return B(r)?r.message:String(r)}}function Mo(e,s,r){try{let i=J(e,{...r===void 0?{}:{env:{...process.env,...r}}}),n=i.manifest.skills;if(n===void 0)return;let a=ht(n.dir)?n.dir:gt(i.dir,n.dir);jo(Fo(a,s),{recursive:!0,force:!0}),or(a,s)}catch{}}import{existsSync as Do,mkdirSync as Ho,writeFileSync as Go}from"node:fs";import{dirname as Vo,join as bn,resolve as $n,sep as Xo}from"node:path";var De={user:"--user",name:"--name",purpose:"--purpose",preset:"--preset",model:"--model",baseUrl:"--base-url",apiKeyEnv:"--api-key-env",apiKey:"(asked at the prompt only)",system:"--system",web:"--web",webBackend:"--web-backend",webKey:"(asked at the prompt only)",composio:"--composio",composioKey:"(asked at the prompt only)",telegram:"--telegram",telegramAllow:"--telegram-allow",whatsapp:"--whatsapp",whatsappNumber:"--whatsapp-number",telegramToken:"(asked at the prompt only)",schedules:"--schedules",server:"--server",skills:"--skills",skillsSearch:"--skills",skillsPick:"--skills",daemon:"--daemon",serverToken:"(generated)",dirChoice:"--dir",dir:"--dir"};function kn(e,s,r){let i=[];for(;;){let n=rt(e,r);if(n===void 0)break;if(n.optional===!0){e[n.step]="";continue}if(n.fallback===""){i.push(n.step),e[n.step]="(missing)";continue}let a=HA(n.step,n.fallback);if(a.ok)e[n.step]=a.value}if(i.length>0){let n=i.map((a)=>De[a]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${s}), and ${i.join(", ")} ${i.length===1?"has":"have"} no default.`,hint:`Pass ${n} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function Sn(e,s){let r=e,i=kt(r.preset),n=r.apiKeyEnv??i?.apiKeyEnv,a=r.server??"local",l=r.dir??Lt(r.dirChoice,r.name,s);if(l===void 0)throw new t({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(r.dirChoice)}, which resolves to no path.`,hint:"This is a bug in the CLI: every dirChoice except `custom` must derive a path in `dirFor`, and `custom` must have asked the dir question. Pass --dir <path> to get past it."});return{user:r.user,name:r.name,purpose:r.purpose,preset:r.preset,model:r.model,baseUrl:r.baseUrl,system:r.system,web:r.web,...r.webBackend===void 0?{}:{webBackend:r.webBackend},...r.webKey===void 0||r.webKey===""?{}:{webKey:r.webKey},composio:r.composio,...r.composioKey===void 0||r.composioKey===""?{}:{composioKey:r.composioKey},telegram:r.telegram,...r.telegramToken===void 0||r.telegramToken===""?{}:{telegramToken:r.telegramToken},...r.telegramAllow===void 0||r.telegramAllow===""?{}:{telegramAllow:r.telegramAllow},whatsapp:r.whatsapp??"none",...r.whatsappNumber===void 0||r.whatsappNumber===""?{}:{whatsappNumber:r.whatsappNumber},schedules:r.schedules??"none",server:a,skills:r.skills,...r.skillsSearch===void 0||r.skillsSearch===""?{}:{skillsSearch:r.skillsSearch},...r.skillsPick===void 0||r.skillsPick===""?{}:{skillsPick:r.skillsPick},daemon:r.daemon,...a==="local"?{serverToken:Yo(l,s.agentDirBase)?Ns(s.agentDirBase,Et):Et()}:{},...n===void 0?{}:{apiKeyEnv:n},...r.apiKey===void 0||r.apiKey===""?{}:{apiKey:r.apiKey},...r.dirChoice===void 0?{}:{dirChoice:r.dirChoice},dir:l}}function Yo(e,s){let r=$n(e),i=$n(s);return r===i||r.startsWith(i+Xo)}function Et(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((s)=>s.toString(16).padStart(2,"0")).join("")}function Te(e,s){let r=s.map((i)=>bn(e,i.relPath)).filter((i)=>Do(i));if(r.length>0)throw new t({code:"cli_init_target_exists",message:`${r.length} of the files init would write already exist: ${r.join(", ")}`,hint:"Nothing is overwritten and there is no --force — replacing a personalised workspace is exactly the loss this command exists to prevent. Point init at a fresh directory, or delete the files first if they really are disposable."});for(let i of s){let n=bn(e,i.relPath);Ho(Vo(n),{recursive:!0}),Go(n,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function He(e,s){let r=J(e,{...s===void 0?{}:{env:{...process.env,...s}}}),i=pe(r.manifest.model.main.id,r.manifest.model.main.capabilities),{workspace:n,warnings:a}=lt(r,i.promptStyle),l=JA(n,r.manifest.context.rules);if(l!==void 0&&r.manifest.context.rules.onExceed==="fail")throw l;return{distilled:a.some((c)=>c.code==="soul_distilled")}}var At=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."}]]),En=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 Ot(e){let s=HA(e.step,e.fallback);return s.ok?s.value:e.fallback}function Qo(e,s){let r=En.get(e.step);return{step:e.step,prompt:e.prompt,fallback:Ot(e),optional:e.optional===!0,secret:gn.has(e.step),...s===void 0?{}:{requires:s},...e.options===void 0?{}:{choices:e.options.filter((i)=>r?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var It=64;function Ct(e){let s=new Map,r=new Set,i=(a,l)=>{let c={...a},f=[];for(let g=0;g<It;g+=1){let m=rt(c,e);if(m===void 0)break;let p=Ot(m);if(!At.has(m.step)&&!s.has(m.step))s.set(m.step,Qo(m,l));for(let h of m.options??[]){if(h.value===p)continue;if(En.get(m.step)?.has(h.value)===!0)continue;f.push({seed:{...c,[m.step]:h.value},opened:{step:m.step,value:h.value}})}c[m.step]=p}return f},n=[...i({})];for(let a=0;a<It&&n.length>0;a+=1){let l=n.splice(0,n.length);for(let c of l){let f=`${c.opened.step}=${c.opened.value}`;if(r.has(f))continue;r.add(f),n.push(...i(c.seed,c.opened))}}return[...s.values()].sort((a,l)=>hr.indexOf(a.step)-hr.indexOf(l.step))}function jt(e){let s={};for(let[c,f]of Object.entries(e.answers)){let g=c;if(!(g in De))throw new t({code:"provision_unknown_answer",message:`"${c}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:c});let m=At.get(g);if(m!==void 0)throw new t({code:m.code,message:`"${c}" cannot be set over the API.`,hint:m.hint,field:c});let p=En.get(g)?.get(f.trim().toLowerCase());if(p!==void 0)throw new t({code:p.code,message:`${c} is ${JSON.stringify(f)}, which this runtime cannot do over the API.`,hint:p.hint,field:c});let h=HA(g,f);if(!h.ok)throw new t({code:"provision_answer_invalid",message:`${c} is ${JSON.stringify(f)}, which ${h.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:c});s[g]=h.value}kn(s,"this is the provisioning API",e.defaults);let r=Sn(s,e.defaults),i=nA(r.name),n=Lt("sandbox",r.name,e.defaults);if(n===void 0)throw new t({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(r.name)}.`,hint:'This is a bug in the CLI: `dirFor("sandbox", …)` must always resolve a path. It returns undefined only when the name is missing, which `complete()` has already refused.',field:"name"});let a=$n(n),l=yr({...r,dir:a});return Te(a,l),{agentId:i,dir:a,manifestPath:bn(a,"agent.yaml"),files:l.map((c)=>c.relPath)}}function si(e){if(e.web!=="search")return;return ro(e.webBackend??"tavily")?.apiKeyEnv}async function Wt(e){let s=await qt(e);if(s.kind==="aborted")return process.stdout.write(`nothing written
21
21
  `),o;return s.kind==="failed"?s.code:o}async function Tn(e){return qt(e)}async function qt(e){let s=ii(e),r=AA({json:!1,plain:e.plain===!0,oneShot:!1}),i=r.mode==="rich"&&e.yes!==!0,n={agentDirBase:ne()};if(i){let b=await di(s,n);if(b===void 0)return{kind:"aborted"};Object.assign(s,b)}else kn(s,e.yes===!0?"--yes was passed":r.because,n);let a=Sn(s,n),l=ti(process.cwd(),a.dir),c=Ms(l);if(c!==void 0)process.stderr.write(`${c}
22
- `);let f=de(l,"agent.yaml"),g=Qr(a);Ae(l,g);let m=a.apiKeyEnv,h=m!==void 0&&a.apiKey===void 0&&(process.env[m]===void 0||process.env[m]==="")&&m!==void 0?{[m]:"(pending)"}:void 0,w=!1;try{w=We(de(l,"agent.yaml"),h).distilled}catch(b){if(B(b))return process.stderr.write(`init wrote ${g.length} files to ${l}, but the result does not load:
22
+ `);let f=de(l,"agent.yaml"),g=yr(a);Te(l,g);let m=a.apiKeyEnv,h=m!==void 0&&a.apiKey===void 0&&(process.env[m]===void 0||process.env[m]==="")&&m!==void 0?{[m]:"(pending)"}:void 0,w=!1;try{w=He(de(l,"agent.yaml"),h).distilled}catch(b){if(B(b))return process.stderr.write(`init wrote ${g.length} files to ${l}, but the result does not load:
23
23
  ${b.format()}
24
24
  `),{kind:"failed",code:d};throw b}if(process.stdout.write(`wrote ${g.length} files to ${l} — validated ok
25
25
  `),a.skills==="find"){let b=(a.skillsPick??"").split(",").map((C)=>C.trim()).filter((C)=>C!=="");if(b.length>0)os(b,f,{...h===void 0?{}:{envOverlay:h}});else if(!i)await yt({answers:a,manifestPath:f,...h===void 0?{}:{envOverlay:h}})}let S;if(a.daemon==="service"){process.stdout.write(`
26
26
  `);let{outcome:b,host:C}=await Gn({...e.installServer===void 0?{}:{install:e.installServer}}),M=wt(b);if(M!==void 0)process.stderr.write(M);if(C?.baseUrl!==void 0){let v=await Dt(C,f);if(v.ok)S=C.baseUrl;else process.stderr.write(`pid ${C.pid} did not adopt ${nA(a.name)}${v.detail===void 0?"":`: ${v.detail}`}
27
27
  `)}}let E;if(a.whatsapp==="connected"&&(a.whatsappNumber??"")!==""&&i)E=S!==void 0?await Un({manifestPath:f,channelId:"wa"}):await xn({manifestPath:f,dir:l,number:a.whatsappNumber??"",channelId:"wa"});if(a.whatsapp==="connected"&&E!=="paired")process.stdout.write(`
28
- ${ji(nA(a.name))}`);return process.stdout.write(ui(a,l,w,S)),{kind:"ok",manifestPath:de(l,"agent.yaml")}}function ri(e){if(e===void 0)return[];if(Pt.some((s)=>s.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function ii(e){let s={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...ri(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,n]of r){if(n===void 0)continue;let a=HA(i,n);if(!a.ok)throw new t({code:"cli_init_flag_invalid",message:`${He[i]} is ${JSON.stringify(n)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});s[i]=a.value}return s}async function di(e,s){let[{render:r},{createElement:i},{WizardApp:n}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-aaggpzrr.js")]),a;Xn();let l=r(i(n,{title:`${A.name} ${j}`,given:e,defaults:s,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Pe()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function ui(e,s,r,i){let n=i!==void 0,l=ni(s)===ne()?Rn(s):de(s,"agent.yaml"),c=de(s,"agent.yaml"),f=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)f.push(`Add your key: edit ${de(s,".env")} and set ${e.apiKeyEnv}=`);let g=si(e);if(g!==void 0&&e.webKey===void 0)f.push(`Add your search key: edit ${de(s,".env")} and set ${g}= — web_fetch works without it, web_search does not`);if(vt(e)&&e.composioKey===void 0)f.push(`Add your Composio key: edit ${de(s,".env")} and set ${an}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)f.push(`Add your bot token: message @BotFather with /newbot, then edit ${de(s,".env")} and set ${io}=`);let m=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],p=m.length>0||e.server==="local",h=[...m,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(n)f.push(`open ${ZA(i,Rn(s))} — the web UI. The service is serving `+`${Rn(s)} now; ${h} ${m.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),f.push(`${A.slug} run ${l} — talks to it here, attached to that same service.`);else f.push(`${A.slug} run ${l}`);if(p&&!n){if(f.push(`${A.slug} serve ${l} — starts ${h}; \`run\` starts neither`),e.daemon==="service")f.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)f.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(vt(e))f.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.");f.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${l} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${l} <name>\` writes one.`),f.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${c}\` shows exactly what still reads as a template.`);let w=n?`
28
+ ${ji(nA(a.name))}`);return process.stdout.write(ui(a,l,w,S)),{kind:"ok",manifestPath:de(l,"agent.yaml")}}function ri(e){if(e===void 0)return[];if(Pt.some((s)=>s.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function ii(e){let s={},r=[["user",e.user],["name",e.name],["purpose",e.purpose],["preset",e.preset],["model",e.model],["baseUrl",e.baseUrl],["apiKeyEnv",e.apiKeyEnv],["system",e.system],["web",e.web],["webBackend",e.webBackend],["composio",e.composio],["telegram",e.telegram],["telegramAllow",e.telegramAllow],["whatsapp",e.whatsapp],["whatsappNumber",e.whatsappNumber],["server",e.server],["schedules",e.schedules],...ri(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,n]of r){if(n===void 0)continue;let a=HA(i,n);if(!a.ok)throw new t({code:"cli_init_flag_invalid",message:`${De[i]} is ${JSON.stringify(n)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});s[i]=a.value}return s}async function di(e,s){let[{render:r},{createElement:i},{WizardApp:n}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-k43w5pfv.js")]),a;Xn();let l=r(i(n,{title:`${A.name} ${j}`,given:e,defaults:s,onDone:(c)=>{a=c}}),{exitOnCtrlC:!1,...Pe()});return U(()=>l.unmount()),await l.waitUntilExit(),l.unmount(),a}function ui(e,s,r,i){let n=i!==void 0,l=ni(s)===ne()?Rn(s):de(s,"agent.yaml"),c=de(s,"agent.yaml"),f=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)f.push(`Add your key: edit ${de(s,".env")} and set ${e.apiKeyEnv}=`);let g=si(e);if(g!==void 0&&e.webKey===void 0)f.push(`Add your search key: edit ${de(s,".env")} and set ${g}= — web_fetch works without it, web_search does not`);if(vt(e)&&e.composioKey===void 0)f.push(`Add your Composio key: edit ${de(s,".env")} and set ${an}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)f.push(`Add your bot token: message @BotFather with /newbot, then edit ${de(s,".env")} and set ${io}=`);let m=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],p=m.length>0||e.server==="local",h=[...m,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(n)f.push(`open ${ZA(i,Rn(s))} — the web UI. The service is serving `+`${Rn(s)} now; ${h} ${m.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),f.push(`${A.slug} run ${l} — talks to it here, attached to that same service.`);else f.push(`${A.slug} run ${l}`);if(p&&!n){if(f.push(`${A.slug} serve ${l} — starts ${h}; \`run\` starts neither`),e.daemon==="service")f.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)f.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(vt(e))f.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.");f.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${l} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${A.slug} sources search <what it should do>\` finds one, \`${A.slug} skills new ${l} <name>\` writes one.`),f.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${c}\` shows exactly what still reads as a template.`);let w=n?`
29
29
  it is running in the background now — \`${A.slug} status\` at any time,
30
30
  \`${A.slug} restart ${l}\` after editing it, and \`${A.slug} stop\` turns everything off.
31
31
  `:"";return`${r?`
@@ -33,7 +33,7 @@ this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
33
33
  frontier-class model, and activates automatically if you upgrade.
34
34
  `:""}${w}
35
35
  `+f.map((E,b)=>` ${b+1}. ${E}
36
- `).join("")}var qe=16;function Be(e=process.stdin){let s=[],r=[],i=(n)=>{let a=typeof n==="string"?n:n.toString("utf8");if(r.push(a),r.length>qe)r.splice(0,r.length-qe);if(s.push(...xs(a)),s.length>qe)s.splice(0,s.length-qe)};return e.on("data",i),{correct:(n,a)=>Ks(n,a,s),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Bt=[{id:"vscode",name:"VS Code's integrated terminal",how:"write",configPath:"Library/Application Support/Code/User/keybindings.json",line:'{ "key": "shift+enter", "command": "workbench.action.terminal.sendSequence", "args": { "text": "\\u001b[13;2u" } }',marker:"workbench.action.terminal.sendSequence"},{id:"ghostty",name:"Ghostty",how:"write",configPath:".config/ghostty/config",line:"keybind = shift+enter=text:\\x1b[13;2u",marker:"shift+enter=text:"},{id:"kitty",name:"kitty",how:"write",configPath:".config/kitty/kitty.conf",line:"map shift+enter send_text all \\x1b[13;2u",marker:"map shift+enter send_text"},{id:"wezterm",name:"WezTerm",how:"write",configPath:".wezterm.lua",line:"-- shift+enter: { key = 'Enter', mods = 'SHIFT', action = wezterm.action.SendString '\\x1b[13;2u' },",marker:"mods = 'SHIFT', action = wezterm.action.SendString"},{id:"warp",name:"Warp",how:"explain",reason:"Option is resolved to a character before the keyboard protocol sees it, so ⌥ plus a letter arrives as text like `®` unless Warp is told otherwise",steps:["Settings → Features → Keys → tick “Left and Right Option Key is Meta”","That is only needed for ⌥ plus a *letter*. ⌥ and cmd with arrows already work, and so does shift+⏎",`Every letter chord here has a control-key twin that needs none of this — \`${A.slug} keys\` shows exactly what your terminal sends`]},{id:"iterm2",name:"iTerm2",how:"explain",reason:"its preferences are a binary plist it rewrites on quit, so an edit made underneath it is discarded",steps:["Settings → Profiles → Keys → Key Mappings","Press +, then press shift and return together to capture the key","Set Action to “Send Hex Codes”","Enter: 0x1b 0x5b 0x31 0x33 0x3b 0x32 0x75"]},{id:"apple",name:"Terminal.app",how:"explain",reason:"its key bindings live in the same binary preferences file, and it caches them while running",steps:["Settings → Profiles → Keyboard","Press +, choose Return as the key and tick Shift","Set Action to “Send Text” and enter: \\033[13;2u"]}];function Xe(e){let s=e.TERM_PROGRAM??"";if(s==="vscode")return"vscode";if(s==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(s==="WarpTerminal")return"warp";if(s==="iTerm.app")return"iterm2";if(s==="Apple_Terminal")return"apple";return"unknown"}function ze(e){return Bt.find((s)=>s.id===e)}function Vt(){return Bt}function Jt(e,s){return s.marker!==void 0&&e.includes(s.marker)}function zt(e,s){let r=s.line;if(r===void 0)return;if(s.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
36
+ `).join("")}var We=16;function qe(e=process.stdin){let s=[],r=[],i=(n)=>{let a=typeof n==="string"?n:n.toString("utf8");if(r.push(a),r.length>We)r.splice(0,r.length-We);if(s.push(...xs(a)),s.length>We)s.splice(0,s.length-We)};return e.on("data",i),{correct:(n,a)=>Ks(n,a,s),takeRaw:()=>r.shift(),close:()=>{e.off("data",i)}}}var Bt=[{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 Be(e){let s=e.TERM_PROGRAM??"";if(s==="vscode")return"vscode";if(s==="ghostty"||e.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(e.KITTY_WINDOW_ID!==void 0||e.TERM==="xterm-kitty")return"kitty";if(e.WEZTERM_PANE!==void 0)return"wezterm";if(s==="WarpTerminal")return"warp";if(s==="iTerm.app")return"iterm2";if(s==="Apple_Terminal")return"apple";return"unknown"}function Xe(e){return Bt.find((s)=>s.id===e)}function Vt(){return Bt}function Jt(e,s){return s.marker!==void 0&&e.includes(s.marker)}function zt(e,s){let r=s.line;if(r===void 0)return;if(s.id!=="vscode"){let c=e.trimEnd();return c===""?`${r}
37
37
  `:`${c}
38
38
  ${r}
39
39
  `}let i=e.trim();if(i===""||i==="[]")return`[
@@ -41,7 +41,7 @@ ${r}
41
41
  ]
42
42
  `;let n=i.indexOf("[");if(n===-1)return;let l=i.slice(n+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,n+1)}
43
43
  ${r}${l}
44
- ${i.slice(n+1)}`}async function Yt(e={}){let s=AA({plain:!1,json:!1,oneShot:!1});if(s.mode!=="rich")throw new t({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${s.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let r=Pe(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,n=Xe(process.env),a=ze(n)?.name??n,[{render:l},{createElement:c},{KeyProbe:f}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-mr7cgsfy.js")]),g=()=>{},m=new Promise((w)=>{g=w}),p=Be();U(()=>{p.close()}),BA(),process.stdout.write(wA);let h=l(c(f,{columns:_e(process.stdout.columns,be),asked:i,terminal:a,takeRaw:p.takeRaw,correctKeys:p.correct,onDone:g}),{exitOnCtrlC:!1,...r});return U(()=>h.unmount()),await m,h.unmount(),p.close(),Je(),await cA(),o}var mi=24,In=22;function On(e){let s=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${s===""?"":` ${s}`}`}function Qt(e){let s=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?s:`-${e.short}, ${s}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(mi-1)} ${e.help}${i}`}var is=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
44
+ ${i.slice(n+1)}`}async function Yt(e={}){let s=AA({plain:!1,json:!1,oneShot:!1});if(s.mode!=="rich")throw new t({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${s.because}). Run it in the terminal whose keys you want to inspect; there is no scripted form, because the answer is a property of that terminal.`});let r=Pe(e.noEnhancedKeys),i=r.kittyKeyboard!==void 0,n=Be(process.env),a=Xe(n)?.name??n,[{render:l},{createElement:c},{KeyProbe:f}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-6v095zeb.js")]),g=()=>{},m=new Promise((w)=>{g=w}),p=qe();U(()=>{p.close()}),BA(),process.stdout.write(wA);let h=l(c(f,{columns:_e(process.stdout.columns,be),asked:i,terminal:a,takeRaw:p.takeRaw,correctKeys:p.correct,onDone:g}),{exitOnCtrlC:!1,...r});return U(()=>h.unmount()),await m,h.unmount(),p.close(),Je(),await cA(),o}var mi=24,In=22;function On(e){let s=e.args.map((r)=>{let i=r.variadic===!0?`${r.name}...`:r.name;return r.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${s===""?"":` ${s}`}`}function Qt(e){let s=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,r=e.short===void 0?s:`-${e.short}, ${s}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${r.padEnd(mi-1)} ${e.help}${i}`}var is=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
45
45
  delivery reads the channel back out of the key.`;function fi(e){let s=[];for(let r of e.args){if(r.choices===void 0||r.choices.length===0)continue;let i=Math.max(...r.choices.map((n)=>n.value.length))+2;s.push("",`${r.name}:`);for(let n of r.choices)s.push(` ${n.value.padEnd(i)}${n.help}`)}return s}function _n(e){if(e!==void 0){let r=[e.summary,"","usage:",` ${On(e)} [flags]`,...fi(e),"","flags:",...nn(e).map(Qt)];if(e.flags.some((i)=>i.name==="session"))r.push("",is);return`${r.join(`
46
46
  `)}
47
47
  `}let s=Math.max(...eA.map((r)=>On(r).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...eA.map((r)=>` ${On(r).padEnd(s)}${r.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...tn.map(Qt),"",is,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd(In)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(In)}set to anything to force plain output`,` ${"DEBUG".padEnd(In)}print stack traces on failure`].join(`
@@ -61,12 +61,12 @@ ${ie("SCORE",6)} ${ie("LEXICAL",7)} ${ie("COVER",5)} ${ie("SOURCE",c)} ${ie(
61
61
  ${l.length-a.length} shown below the threshold; a turn would not inject those.
62
62
  `);if(n.carried!==void 0&&l.some((f)=>f.passage.source===n.carried))process.stdout.write(`
63
63
  ${n.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
64
- `);return o}finally{await s.stop("cli-exit")}}function Si(e){let s=e.replace(/\s+/g," ").trim();return s.length<=ms?s:`${s.slice(0,ms-1)}…`}function ie(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function fs(e,s){return e.passage.source===s?`${e.passage.source} *`:e.passage.source}var Ei=["context_length","context_window","max_context_length","max_model_len"],Ri=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let s=e.prompt_tokens_details;return Qe(s)?s.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function Qe(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Nn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function hs(e,s){let r=Qe(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let n=s.toLowerCase();for(let a of i){if(!Qe(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===n||l.endsWith(`/${n}`)||n.endsWith(`/${l}`)))continue;for(let f of Ei){let g=Nn(a[f]);if(g!==void 0)return{technique:"metadata",tokens:g,bound:"ceiling",detail:`GET /models published ${f}: ${g}`}}return}return}function jn(e){let s=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],r=[];for(let i of s){let n=i.exec(e);if(n?.[1]===void 0)continue;let a=Nn(Number(n[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function ys(e){if(!Qe(e))return;let s=Nn(e.prompt_tokens)??0;for(let[r,i]of Ri){let n=i(e);if(typeof n==="number"&&Number.isFinite(n))return{cached:n,promptTokens:s,field:r}}return{cached:void 0,promptTokens:s,field:void 0}}function ws(e,s,r){if(e===void 0||s===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(s.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=s.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${s.promptTokens} prompt tokens, via ${s.field}`};return{supported:!1,detail:`${s.field} came back 0 on an identical repeat of a ${r}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function Oe(e){let s=e.filter((i)=>i.bound==="ceiling");return(s.length>0?s:e).reduce((i,n)=>i===void 0||n.tokens>i.tokens?n:i,void 0)}function bs(e,s,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${s.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
65
- `)}function $s(e,s,r){return`measured ${s} against ${e} — ${r}`}function vs(e,s){let r=Math.max(1,e),i=0,n=0;while(r<s)i+=r,n+=1,r*=2;return i+=s,n+=1,{requests:n,tokens:i}}var xi=2000000000,Ss=1024,Rs=8192,Ps=2097152;function Ts(e){return"context ".repeat(Math.max(1,e))}async function Ce(e){let s=await e.text();try{return{text:s,json:JSON.parse(s)}}catch{return{text:s,json:void 0}}}function Is(e,s){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let n=i.message;if(typeof n==="string")return n}if(typeof r.message==="string")return r.message}return s}async function Ti(e,s,r){try{let i=await s(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:n}=await Ce(i),a=hs(n,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function Ii(e,s,r){try{let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:xi})}),{text:n,json:a}=await Ce(i);if(i.ok)return r.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let l=Is(a,n.slice(0,400)),c=jn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let f=/max_?tokens/i.test(l);return{window:f?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:f?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 Es(e,s,r){let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:n}=await Ce(i),a=typeof n==="object"&&n!==null?n.usage:void 0;return ys(a)}async function Oi(e,s,r){let i=`${Ts(Ss)}
66
- Reply with the single character x.`;try{let n=await Es(e,s,i),a=await Es(e,s,i);return ws(n,a,Ss)}catch(n){return r.push(`the caching probe failed: ${n instanceof Error?n.message:String(n)}`),{supported:void 0,detail:"the probe did not complete"}}}async function _i(e,s,r){let i=Rs,n=0;while(i<=Ps){let a;try{a=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ts(i)}],max_tokens:1})})}catch(g){r.push(`the search stopped at ${i}: ${g instanceof Error?g.message:String(g)}`);break}if(a.ok){let{json:g}=await Ce(a),m=typeof g==="object"&&g!==null?g.usage:void 0,p=typeof m==="object"&&m!==null?m.prompt_tokens:void 0;n=typeof p==="number"&&Number.isFinite(p)?p:n,i*=2;continue}let{text:l,json:c}=await Ce(a),f=jn(Is(c,l.slice(0,400)));if(f!==void 0)return{technique:"search",tokens:f,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${f}`};break}if(n===0)return;return{technique:"search",tokens:n,bound:"floor",detail:`accepted a prompt the endpoint counted at ${n} tokens; nothing above it named a number`}}function Ci(e,s){let r=Oe(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,n=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[_(` ${e.role} · ${e.modelId}`),u([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:n},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...s===void 0?[]:[{label:"price",value:`$${s}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((l)=>` · ${l}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",bs(e.modelId,r.tokens,e.outputCeiling).split(`
64
+ `);return o}finally{await s.stop("cli-exit")}}function Si(e){let s=e.replace(/\s+/g," ").trim();return s.length<=ms?s:`${s.slice(0,ms-1)}…`}function ie(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function fs(e,s){return e.passage.source===s?`${e.passage.source} *`:e.passage.source}var Ei=["context_length","context_window","max_context_length","max_model_len"],Ri=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let s=e.prompt_tokens_details;return ze(s)?s.cached_tokens:void 0}],["cache_read_input_tokens",(e)=>e.cache_read_input_tokens]];function ze(e){return typeof e==="object"&&e!==null&&!Array.isArray(e)}function Nn(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function hs(e,s){let r=ze(e)?e.data:void 0,i=Array.isArray(r)?r:Array.isArray(e)?e:void 0;if(i===void 0)return;let n=s.toLowerCase();for(let a of i){if(!ze(a))continue;let l=typeof a.id==="string"?a.id.toLowerCase():void 0;if(l===void 0)continue;if(!(l===n||l.endsWith(`/${n}`)||n.endsWith(`/${l}`)))continue;for(let f of Ei){let g=Nn(a[f]);if(g!==void 0)return{technique:"metadata",tokens:g,bound:"ceiling",detail:`GET /models published ${f}: ${g}`}}return}return}function jn(e){let s=[/(?:max_?tokens|context[\s_]?(?:length|window))[^[\]]{0,40}\[\s*\d[\d_,]*\s*,\s*(\d[\d_,]*)\s*\]/i,/maximum context length is (\d[\d_,]*)/i,/max_?tokens[^.\d]{0,40}?(\d[\d_,]*)/i,/context (?:length|window)(?: of)? (?:is )?(\d[\d_,]*)/i,/maximum (?:sequence|model) length (?:is )?(\d[\d_,]*)/i],r=[];for(let i of s){let n=i.exec(e);if(n?.[1]===void 0)continue;let a=Nn(Number(n[1].replaceAll(/[,_]/g,"")));if(a!==void 0)r.push(a)}if(r.length===0)return;return Math.max(...r)}function ys(e){if(!ze(e))return;let s=Nn(e.prompt_tokens)??0;for(let[r,i]of Ri){let n=i(e);if(typeof n==="number"&&Number.isFinite(n))return{cached:n,promptTokens:s,field:r}}return{cached:void 0,promptTokens:s,field:void 0}}function ws(e,s,r){if(e===void 0||s===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(s.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=s.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${s.promptTokens} prompt tokens, via ${s.field}`};return{supported:!1,detail:`${s.field} came back 0 on an identical repeat of a ${r}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function Ae(e){let s=e.filter((i)=>i.bound==="ceiling");return(s.length>0?s:e).reduce((i,n)=>i===void 0||n.tokens>i.tokens?n:i,void 0)}function bs(e,s,r){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${s.toLocaleString("en-US").replaceAll(",","_")},`,...r===void 0?[]:[` maxOutput: ${r.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
65
+ `)}function $s(e,s,r){return`measured ${s} against ${e} — ${r}`}function vs(e,s){let r=Math.max(1,e),i=0,n=0;while(r<s)i+=r,n+=1,r*=2;return i+=s,n+=1,{requests:n,tokens:i}}var xi=2000000000,Ss=1024,Rs=8192,Ps=2097152;function Ts(e){return"context ".repeat(Math.max(1,e))}async function Oe(e){let s=await e.text();try{return{text:s,json:JSON.parse(s)}}catch{return{text:s,json:void 0}}}function Is(e,s){if(typeof e==="object"&&e!==null){let r=e,i=r.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let n=i.message;if(typeof n==="string")return n}if(typeof r.message==="string")return r.message}return s}async function Ti(e,s,r){try{let i=await s(e.models,{headers:e.headers});if(!i.ok){r.push(`GET /models answered ${i.status}`);return}let{json:n}=await Oe(i),a=hs(n,e.modelId);if(a===void 0)r.push("GET /models published no context length");return a}catch(i){r.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function Ii(e,s,r){try{let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:xi})}),{text:n,json:a}=await Oe(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=Is(a,n.slice(0,400)),c=jn(l);if(c===void 0)return r.push(`the refusal named no number: ${l.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let f=/max_?tokens/i.test(l);return{window:f?void 0:{technique:"refusal",tokens:c,bound:"ceiling",detail:`refused an over-range request naming ${c}`},outputCeiling:f?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 Es(e,s,r){let i=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:r}],max_tokens:1})});if(!i.ok)return;let{json:n}=await Oe(i),a=typeof n==="object"&&n!==null?n.usage:void 0;return ys(a)}async function Oi(e,s,r){let i=`${Ts(Ss)}
66
+ Reply with the single character x.`;try{let n=await Es(e,s,i),a=await Es(e,s,i);return ws(n,a,Ss)}catch(n){return r.push(`the caching probe failed: ${n instanceof Error?n.message:String(n)}`),{supported:void 0,detail:"the probe did not complete"}}}async function _i(e,s,r){let i=Rs,n=0;while(i<=Ps){let a;try{a=await s(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:Ts(i)}],max_tokens:1})})}catch(g){r.push(`the search stopped at ${i}: ${g instanceof Error?g.message:String(g)}`);break}if(a.ok){let{json:g}=await Oe(a),m=typeof g==="object"&&g!==null?g.usage:void 0,p=typeof m==="object"&&m!==null?m.prompt_tokens:void 0;n=typeof p==="number"&&Number.isFinite(p)?p:n,i*=2;continue}let{text:l,json:c}=await Oe(a),f=jn(Is(c,l.slice(0,400)));if(f!==void 0)return{technique:"search",tokens:f,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${f}`};break}if(n===0)return;return{technique:"search",tokens:n,bound:"floor",detail:`accepted a prompt the endpoint counted at ${n} tokens; nothing above it named a number`}}function Ci(e,s){let r=Ae(e.findings),i=r===void 0?"nothing measured — every technique came back empty":`${r.tokens} (${r.bound}) · ${r.detail}`,n=r===void 0?"":r.tokens===e.declared?"matches what is configured":r.bound==="ceiling"&&r.tokens>e.declared?`configured value is ${e.declared}, which is ${(r.tokens-e.declared).toLocaleString("en-US")} tokens short`:`configured value is ${e.declared}`,a=e.cache.supported===void 0?`unknown — ${e.cache.detail}`:e.cache.supported?`yes — ${e.cache.detail}`:`no — ${e.cache.detail}`;return[_(` ${e.role} · ${e.modelId}`),u([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:n},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...s===void 0?[]:[{label:"price",value:`$${s}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((l)=>` · ${l}`)],...r===void 0||r.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",bs(e.modelId,r.tokens,e.outputCeiling).split(`
67
67
  `).map((l)=>` ${l}`).join(`
68
68
  `)]].join(`
69
- `)}async function Os(e){let s=e.fetch??globalThis.fetch;try{let r=J(e.manifestPath,{env:R([e.manifestPath])}),{manifest:i}=r,n=yA(i).filter((f)=>f.role===f.configuredAs),a=!1;if(e.window){let f=vs(Rs,Ps),g=f.tokens*n.length,m=e.price===void 0?"":` ≈ $${(g/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${f.requests} requests per role, about ${g.toLocaleString("en-US")} input tokens in total${m}.
69
+ `)}async function Os(e){let s=e.fetch??globalThis.fetch;try{let r=J(e.manifestPath,{env:R([e.manifestPath])}),{manifest:i}=r,n=QA(i).filter((f)=>f.role===f.configuredAs),a=!1;if(e.window){let f=vs(Rs,Ps),g=f.tokens*n.length,m=e.price===void 0?"":` ≈ $${(g/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${f.requests} requests per role, about ${g.toLocaleString("en-US")} input tokens in total${m}.
70
70
  That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
71
71
  Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
72
72
  `),a=e.yes||await bt("spend it?"),process.stdout.write(a?`
@@ -77,8 +77,8 @@ Skipping the search. The free techniques below still run — re-run with --windo
77
77
  `);continue}let m={chat:ao(g.baseUrl),models:ei(g.baseUrl),headers:Ai(g.apiKeyEnv,r.env,`model.${f.role}`),modelId:g.id},p=[],h=[],w=await Ti(m,s,p);if(w!==void 0)h.push(w);let S=await Ii(m,s,p);if(S.window!==void 0)h.push(S.window);let E=await Oi(m,s,p);if(a){let b=await _i(m,s,p);if(b!==void 0)h.push(b)}l.push({role:f.role,modelId:g.id,baseUrl:g.baseUrl,declared:f.window.contextWindow,declaredSource:f.window.source,findings:h,cache:E,outputCeiling:S.outputCeiling,failures:p})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:l},null,2)}
78
78
  `),o;let c=e.write?await Ni(r.path,l):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${l.length} role${l.length===1?"":"s"}`,...l.map((f)=>Ci(f,e.price)),"",...e.write?[...c.written.length===0?[]:[" written to the manifest:",...c.written.map((f)=>` ${f}`)],...c.refused.length===0?[]:[" not written:",...c.refused.map((f)=>` ${f}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Li(l)],""].join(`
79
79
  `)),o}catch(r){if(B(r))return process.stderr.write(`${r.format()}
80
- `),d;throw r}}async function Ni(e,s){let r=[],i=[];for(let n of s){let a=Oe(n.findings);if(a===void 0){i.push(`${n.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${n.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===n.declared){i.push(`${n.role}: already ${a.tokens}, nothing to change`);continue}await Ve({file:e,path:["model",n.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${n.role}: ${n.declared} → ${a.tokens}`)}return{written:r,refused:i}}function Li(e){let s=e.filter((a)=>Oe(a.findings)?.bound==="ceiling");if(s.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=s[0],i=r===void 0?void 0:Oe(r.findings);if(r===void 0||i===void 0)return"";let n=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${$s(n,new Date().toISOString().slice(0,10),i.detail)}`].join(`
81
- `)}import{existsSync as Gs,rmSync as Qi}from"node:fs";import{resolve as na}from"node:path";var Mi={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function _s(e){if(e===null||typeof e!=="object")return!1;let s=e.kind;return s==="network"||s==="env"||s==="fs"||s==="exec"||s==="store"}async function Cs(e,s={}){let r=[],i=[],n=s.hostVersion??ve,a=(h,w,S)=>{r.push({level:"error",check:h,message:w,hint:S})},l=(h,w,S)=>{r.push({level:"warning",check:h,message:w,hint:S})};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(sr(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=sr(n,e.dispachApi);if(c===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!c)l("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${n}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")l("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[h,w]of(e.permissions??[]).entries())if(!_s(w))a("permissions",`\`permissions[${h}]\` 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 f=s.config??{};if(e.configSchema!==void 0){let h=e.configSchema.safeParse(f);if(h.success)f=h.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 g={defineChannel:(h)=>i.push(`channel:${h}`),defineToolProvider:(h)=>i.push(`toolProvider:${h}`),defineModelTransport:(h)=>i.push(`modelTransport:${h}`),defineMediaProvider:(h)=>i.push(`mediaProvider:${h}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(h)=>i.push(`middleware:${h.name}`),defineRoute:(h)=>i.push(`route:${h.method} ${h.path}`),config:f,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Mi,events:new ir({runtimeId:"conformance"})},m=performance.now();try{await e.setup(g)}catch(h){a("setup",`\`setup\` threw: ${h instanceof Error?h.message:String(h)}`,"`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 p=Math.round((performance.now()-m)*100)/100;if(p>ar)a("setup budget",`\`setup\` took ${p} ms against a ${ar} 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((h)=>h.level!=="error"),findings:r,registered:i,setupMs:p,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(_s)}}}import{existsSync as we,mkdirSync as Di,readdirSync as Hi,readFileSync as Mn,renameSync as js,rmSync as ge,writeFileSync as Gi}from"node:fs";import{join as X}from"node:path";var Fs=".origin.json";function Bi(e){let s=X(e,Fs);if(!we(s))return;try{return JSON.parse(Mn(s,"utf8"))}catch{return}}function Dn(e){let s=oe(e),r;try{r=Hi(s)}catch{return[]}let i=[];for(let n of r.sort()){if(n.startsWith(".")||n.endsWith(".partial"))continue;let a=X(s,n);if(!we(X(a,"package.json"))&&!we(X(a,"index.js")))continue;let l=Bi(a);i.push({name:n,dir:a,...l===void 0?{}:{origin:l}})}return i}function Ls(e){let s=X(e,"package.json");if(!we(s))return X(e,"index.js");try{let r=JSON.parse(Mn(s,"utf8"));if(typeof r.main==="string"&&r.main!=="")return X(e,r.main)}catch{}return X(e,"index.js")}function Us(e){let s=X(e,"package.json");if(!we(s))return;let r;try{r=JSON.parse(Mn(s,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(r.dependencies??{});if(i.length===0)return;if(we(X(e,"node_modules")))return;let n=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${n}${i.length>4?", …":""}) and ships no node_modules`}function Ds(e,s){let i=((s??e).split("/").filter((n)=>n.length>0).pop()??"").replace(/\.git$/,"");if(!Tt(i))throw new t({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function Hs(e,s={}){let r=s.git??xr,i=mr(e.name,s.env),n=`${i}.partial`;Di(oe(s.env),{recursive:!0}),ge(n,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,n]);if(a.code!==0)throw ge(n,{recursive:!0,force:!0}),Xi(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],n),c=l.code===0?l.stdout.trim():"unknown",f=e.path===void 0?n:X(n,e.path);if(!we(f))throw ge(n,{recursive:!0,force:!0}),new t({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${c}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ge(X(f,".git"),{recursive:!0,force:!0});try{await s.inspect?.(f)}catch(m){throw ge(n,{recursive:!0,force:!0}),m}if(ge(i,{recursive:!0,force:!0}),f===n)js(n,i);else js(f,i),ge(n,{recursive:!0,force:!0});let g={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:c,fetchedAt:new Date().toISOString()};return Gi(X(i,Fs),`${JSON.stringify(g,null,4)}
80
+ `),d;throw r}}async function Ni(e,s){let r=[],i=[];for(let n of s){let a=Ae(n.findings);if(a===void 0){i.push(`${n.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${n.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===n.declared){i.push(`${n.role}: already ${a.tokens}, nothing to change`);continue}await Ve({file:e,path:["model",n.role,"capabilities","contextWindow"],value:a.tokens}),r.push(`${n.role}: ${n.declared} → ${a.tokens}`)}return{written:r,refused:i}}function Li(e){let s=e.filter((a)=>Ae(a.findings)?.bound==="ceiling");if(s.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let r=s[0],i=r===void 0?void 0:Ae(r.findings);if(r===void 0||i===void 0)return"";let n=new URL(r.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${$s(n,new Date().toISOString().slice(0,10),i.detail)}`].join(`
81
+ `)}import{existsSync as Gs,rmSync as Qi}from"node:fs";import{resolve as na}from"node:path";var Mi={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function _s(e){if(e===null||typeof e!=="object")return!1;let s=e.kind;return s==="network"||s==="env"||s==="fs"||s==="exec"||s==="store"}async function Cs(e,s={}){let r=[],i=[],n=s.hostVersion??ve,a=(h,w,S)=>{r.push({level:"error",check:h,message:w,hint:S})},l=(h,w,S)=>{r.push({level:"warning",check:h,message:w,hint:S})};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(sr(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=sr(n,e.dispachApi);if(c===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!c)l("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${n}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")l("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[h,w]of(e.permissions??[]).entries())if(!_s(w))a("permissions",`\`permissions[${h}]\` 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 f=s.config??{};if(e.configSchema!==void 0){let h=e.configSchema.safeParse(f);if(h.success)f=h.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 g={defineChannel:(h)=>i.push(`channel:${h}`),defineToolProvider:(h)=>i.push(`toolProvider:${h}`),defineModelTransport:(h)=>i.push(`modelTransport:${h}`),defineMediaProvider:(h)=>i.push(`mediaProvider:${h}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(h)=>i.push(`middleware:${h.name}`),defineRoute:(h)=>i.push(`route:${h.method} ${h.path}`),config:f,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Mi,events:new ir({runtimeId:"conformance"})},m=performance.now();try{await e.setup(g)}catch(h){a("setup",`\`setup\` threw: ${h instanceof Error?h.message:String(h)}`,"`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 p=Math.round((performance.now()-m)*100)/100;if(p>ar)a("setup budget",`\`setup\` took ${p} ms against a ${ar} 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((h)=>h.level!=="error"),findings:r,registered:i,setupMs:p,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(_s)}}}import{existsSync as ye,mkdirSync as Di,readdirSync as Hi,readFileSync as Mn,renameSync as js,rmSync as ge,writeFileSync as Gi}from"node:fs";import{join as X}from"node:path";var Fs=".origin.json";function Bi(e){let s=X(e,Fs);if(!ye(s))return;try{return JSON.parse(Mn(s,"utf8"))}catch{return}}function Dn(e){let s=oe(e),r;try{r=Hi(s)}catch{return[]}let i=[];for(let n of r.sort()){if(n.startsWith(".")||n.endsWith(".partial"))continue;let a=X(s,n);if(!ye(X(a,"package.json"))&&!ye(X(a,"index.js")))continue;let l=Bi(a);i.push({name:n,dir:a,...l===void 0?{}:{origin:l}})}return i}function Ls(e){let s=X(e,"package.json");if(!ye(s))return X(e,"index.js");try{let r=JSON.parse(Mn(s,"utf8"));if(typeof r.main==="string"&&r.main!=="")return X(e,r.main)}catch{}return X(e,"index.js")}function Us(e){let s=X(e,"package.json");if(!ye(s))return;let r;try{r=JSON.parse(Mn(s,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(r.dependencies??{});if(i.length===0)return;if(ye(X(e,"node_modules")))return;let n=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${n}${i.length>4?", …":""}) and ships no node_modules`}function Ds(e,s){let i=((s??e).split("/").filter((n)=>n.length>0).pop()??"").replace(/\.git$/,"");if(!Tt(i))throw new t({code:"plugin_name_invalid",message:`${JSON.stringify(i||e)} is not a usable plugin directory name`,hint:"A plugin is installed into one lowercase path segment — letters, digits and single hyphens — because that segment is what the manifest's `plugins:` entry names. Pass `--name <name>` to choose it."});return i}async function Hs(e,s={}){let r=s.git??xr,i=mr(e.name,s.env),n=`${i}.partial`;Di(oe(s.env),{recursive:!0}),ge(n,{recursive:!0,force:!0});let a=await r(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,n]);if(a.code!==0)throw ge(n,{recursive:!0,force:!0}),Xi(e,a.stderr,a.timedOut===!0);let l=await r(["rev-parse","--short","HEAD"],n),c=l.code===0?l.stdout.trim():"unknown",f=e.path===void 0?n:X(n,e.path);if(!ye(f))throw ge(n,{recursive:!0,force:!0}),new t({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${c}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});ge(X(f,".git"),{recursive:!0,force:!0});try{await s.inspect?.(f)}catch(m){throw ge(n,{recursive:!0,force:!0}),m}if(ge(i,{recursive:!0,force:!0}),f===n)js(n,i);else js(f,i),ge(n,{recursive:!0,force:!0});let g={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:c,fetchedAt:new Date().toISOString()};return Gi(X(i,Fs),`${JSON.stringify(g,null,4)}
82
82
  `),{dir:i,commit:c}}function Xi(e,s,r){let i=s.trim().split(`
83
83
  `).slice(-3).join(" ");if(r)return new t({code:"plugin_fetch_timeout",message:`${e.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${e.name} is untouched.`});return new t({code:"plugin_fetch_failed",message:`${e.name}: could not clone ${e.url}${i.length===0?"":` — ${i}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function Ws(e){switch(e.action){case"list":return await ta(e);case"add":return await ra(e);case"remove":return await da(e);default:throw new t({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(e.action)} is not an action`,hint:`Actions are list, add and remove — \`${A.slug} plugins list <agent>\`.`})}}async function ta(e){let s=await Ie.create({agents:[e.manifestPath],toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(e.env),scriptRunner:le(),channels:se,env:R([e.manifestPath]),store:F(e.env),lease:!1});U(()=>s.stop("cli-exit"));let r=[...s.plugins.values()].flat(),i=Dn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:r,installed:i,available:Hr},null,2)}
84
84
  `),o;if(r.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
@@ -133,7 +133,7 @@ Remove it from those agents first, or delete the directory by hand.
133
133
  `),o;return Qi(n,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${n}.
134
134
  `),o}function la(e,s,r){let i=[];for(let n of Z(r)){if(n.manifestPath===s)continue;try{if((G(n.manifestPath).plugins??[]).map((c)=>typeof c==="string"?c:c.spec).includes(e))i.push(n.ref)}catch{}}return i}import{existsSync as wa,readdirSync as Zs,rmSync as qn,statSync as dr}from"node:fs";import{homedir as ba}from"node:os";import{join as ur}from"node:path";function Bs(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let s=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${s} — removing its data would take that agent's sessions and memory too.`,hint:`Change one manifest's id and run \`memory rebuild\` for it, or pass --files-only to delete just the ${e.ref} directory and leave the store alone.`}]}function Vs(e){let s=[];if(e.running!==void 0)s.push({kind:"stop",detail:`stop pid ${e.running.pid} (${e.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!e.filesOnly&&e.service!==void 0)s.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let r=e.footprint;if(s.push({kind:"store",detail:`delete ${K(r.sessions,"conversation")}, ${K(r.messages,"message")}, ${K(r.passages,"memory passage")}`}),e.logs.length>0)s.push({kind:"logs",detail:`delete ${K(e.logs.length,"log file")}`})}return s.push({kind:"directory",detail:`delete ${e.dir}`}),s}function Xs(e){let s=e.footprint,r=[{label:"directory",value:`${e.dir}`,note:`${K(e.files.count,"file")}, ${XA(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:`${K(s.sessions,"conversation")}, ${K(s.passages,"memory passage")}, and the logs`,note:"--files-only"});else r.push({label:"sessions",value:`${K(s.sessions,"conversation")}, ${K(s.messages,"message")}, ${K(s.turns,"turn")}`},{label:"memory",value:`${K(s.passages,"passage")} from ${K(s.memorySources,"source")}`},{label:"outbox",value:s.outbox===0?"nothing queued":`${K(s.outbox,"delivery")}${s.outboxPending===0?"":`, ${s.outboxPending} not yet sent`}`,...s.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:s.schedules===0?"none":K(s.schedules,"schedule"),...s.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${K(e.logs.length,"file")}, ${XA(e.logs.reduce((i,n)=>i+n.bytes,0))}`},{label:"service",value:e.service??"not installed"});return r.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),u(r)}function zs(e){if(e.length===0)return"";return e.map((s)=>{let r=s.footprint,i=[];if(r.sessions>0)i.push(`${K(r.sessions,"conversation")}, ${K(r.messages,"message")}`);if(r.passages>0)i.push(`${K(r.passages,"memory passage")}`);if(r.outbox>0)i.push(`${K(r.outbox,"queued delivery")}`);if(r.schedules>0)i.push(`${K(r.schedules,"schedule")}`);if(r.lease)i.push("a stale lease");if(s.logs.length>0)i.push(`${K(s.logs.length,"log file")}, ${XA(s.logs.reduce((n,a)=>n+a.bytes,0))}`);return` ${s.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
135
135
  `)}function K(e,s){return`${e} ${s}${e===1?"":"s"}`}import{homedir as ca}from"node:os";var Ys=12000,ua=250;async function rn(e){if(e.manifestPath!==void 0)return await ma(e,e.manifestPath);return await fa(e)}async function ma(e,s){let r=ya(s),i=[];if(e.dryRun===!0){let c=await Ye(r,e.store);return process.stdout.write(`would stop 1 agent:
136
- ${y(`${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`}`)}
136
+ ${Q(`${r} — ${c===void 0?"not running; would be switched off for the next start":c.baseUrl===void 0?`pid ${c.pid} (${c.mode}), which serves no HTTP — would be signalled`:`pid ${c.pid} (${c.mode}) at ${c.baseUrl}, which would drop it and keep serving`}`)}
137
137
  `),o}await $o(r,!1,e.reason,e.store),i.push("switched off for the next start");let n=await Ye(r,e.store),a=!0;if(n===void 0)i.push("nothing was running");else if(n.baseUrl===void 0){let c=await Ze(n.pid,"SIGTERM");a=c||await Ze(n.pid,"SIGKILL",!0),i.push(c?`pid ${n.pid} stopped cleanly`:a?`pid ${n.pid} had to be killed`:`pid ${n.pid} would not stop — check it by hand`)}else{let c=await aA(n,`/v1/agents/${encodeURIComponent(r)}/stop`,e.reason===void 0?{}:{reason:e.reason},s);if(c.ok)i.push(`pid ${n.pid} dropped it and kept serving`);else if(c.status===409)a=!1,i.push(c.detail??"a turn is running");else if(c.status===401)a=!1,i.push(`pid ${n.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${n.pid} at ${n.baseUrl} could not be reached${c.detail===void 0?"":`: ${c.detail}`}`)}let l={agentId:r,service:!1,...n===void 0?{}:{pid:n.pid,mode:n.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[l]},null,2)}
138
138
  `);else process.stdout.write(`${u([{label:r,value:a?"stopped":"NOT FULLY STOPPED",note:l.note}])}
139
139
  `),process.stdout.write(`
@@ -141,7 +141,7 @@ Stays off across restarts. \`${A.slug} start ${r}\` switches it back on.
141
141
  `);return a?o:d}async function fa(e){let s=e.platform??process.platform,r=s==="darwin"?$t(s,{home:ca(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await pa(r,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
142
142
  `:`Nothing is running — no service is installed and no process holds an agent.
143
143
  `),o;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
144
- ${i.map((a)=>y(ga(a))).join(`
144
+ ${i.map((a)=>Q(ga(a))).join(`
145
145
  `)}
146
146
  `),o;let n=[];for(let a of i)n.push(await ha(a,r));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:n},null,2)}
147
147
  `);else{let a=n.map((l)=>({label:Qs(l.agentId),value:l.stopped?"stopped":"STILL RUNNING",note:l.note}));if(process.stdout.write(`${u(a)}
@@ -155,7 +155,7 @@ cleanup, so a command the agent had left running in the background may still be
155
155
  `)}return n.every((a)=>a.stopped)?o:d}async function pa(e,s){let r=`${A.slug}.agent.`,i=new Map;for(let n of e?.labels(r)??[]){let a=n.slice(r.length);i.set(a,{agentId:a,service:!0})}try{let n=await ue.open({path:s??F()});for(let a of await n.leases.all()){if(a.pid===process.pid||!V(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await n.close()}catch{}return[...i.values()].sort((n,a)=>n.agentId.localeCompare(a.agentId))}async function ha(e,s){let r=[];if(e.service&&s!==void 0)try{s.stop(Wo(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(!V(e.pid))return{...e,stopped:!0,note:r.join(" · ")||`pid ${e.pid} exited`};if(await Ze(e.pid,"SIGTERM"))return r.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:r.join(" · ")};let n=await Ze(e.pid,"SIGKILL",!0);return r.push(n?`pid ${e.pid} did not stop in ${Math.round(Ys/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:n,forced:!0,note:r.join(" · ")}}async function Ze(e,s,r=!1){try{process.kill(r?-e:e,s)}catch(n){if(n.code==="ESRCH")return!0;if(r)try{process.kill(e,s)}catch{return!V(e)}}let i=Date.now()+(s==="SIGKILL"?3000:Ys);while(Date.now()<i){if(!V(e))return!0;await new Promise((n)=>setTimeout(n,ua))}return!V(e)}function ga(e){let s=[];if(e.service)s.push("background service");if(e.pid!==void 0)s.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${Qs(e.agentId)} — ${s.join(", ")}`}function Qs(e){return e===PA?"(host, no agents)":e}function ya(e){let s=G(e);if(s.id===void 0||s.id==="")throw new t({code:"cli_stop_agent_id_missing",message:`${e} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${A.slug} stop\` with no argument to stop everything.`});return s.id}async function fr(e){let s=await ue.open({path:e.store??F()});try{if(e.prune===!0)return await ka(e,s);if(e.all===!0)return await va(e,s);if(e.ref===void 0)throw new t({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${A.slug} remove <name>\` takes a sandbox agent's name — the ones \`${A.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await $a(e.ref,e,s)}finally{await s.close()}}async function $a(e,s,r){let i=await wr(e,s,r),n=Bs(i);if(n.length>0){let c=n[0];throw new t({code:c.code,message:c.message,hint:c.hint})}let a=Vs(i),l=`${_(`removing ${e} will:`,!0)}
156
156
  ${Xs(i)}
157
157
 
158
- ${a.map((c)=>y(c.detail)).join(`
158
+ ${a.map((c)=>Q(c.detail)).join(`
159
159
  `)}
160
160
  `;if(s.dryRun===!0)return process.stdout.write(s.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
161
161
  `:`${l}
@@ -173,7 +173,7 @@ ${u(i)}
173
173
  Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
174
174
  `);return o}async function va(e,s){let r=Z();if(r.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
175
175
  `),o;if(process.stdout.write(`${_(`removing every agent in ${ne()}:`,!0)}
176
- ${r.map((n)=>y(`${n.ref}${n.id===void 0||n.id===n.ref?"":` (id ${n.id})`}`)).join(`
176
+ ${r.map((n)=>Q(`${n.ref}${n.id===void 0||n.id===n.ref?"":` (id ${n.id})`}`)).join(`
177
177
  `)}
178
178
  `),e.dryRun===!0)return process.stdout.write(`
179
179
  Nothing was deleted — this was --dry-run.
@@ -191,26 +191,26 @@ Nothing was deleted.
191
191
  `:`
192
192
  pruned ${n.length} agent id(s).
193
193
  ${u(a)}
194
- `),o}async function wr(e,s,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new t({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${ne()} 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=Z(),n=i.find((h)=>h.ref===e);if(n===void 0){let h=i.map((w)=>w.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${h.length===0?", which is empty":""}.`,hint:h.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${h.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=n.id;if(a===void 0)try{a=G(n.manifestPath).id}catch{}let l=s.filesOnly===!0||a===void 0,c=a??e,f=await r.agentFootprint(c),g=f.lease?await r.leases.get(c):void 0,m=br(s),p=Wo(A.slug,c);return{ref:e,agentId:c,manifestPath:n.manifestPath,dir:n.dir,files:Sa(n.dir),footprint:f,logs:$r(c),sharesIdWith:i.filter((h)=>h.ref!==e&&(h.id??"")===c).map((h)=>h.ref),...g!==void 0&&V(g.pid)?{running:{pid:g.pid,mode:g.mode}}:{},...m?.state(p).installed===!0?{service:p}:{},filesOnly:l}}function br(e){let s=e.platform??process.platform;if(s!=="darwin")return;return $t(s,{home:ba(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Sa(e){let s=0,r=0,i=(n)=>{let a;try{a=Zs(n)}catch{return}for(let l of a){let c=ur(n,l);try{let f=dr(c);if(f.isDirectory()){i(c);continue}s+=1,r+=f.size}catch{}}};return i(e),{count:s,bytes:r}}function $r(e){let s=cn(e),r=[];for(let i of[s.out,s.err])try{if(!wa(i))continue;r.push({path:i,bytes:dr(i).size})}catch{}return r}function Ea(){let e;try{e=Zs(ur(Se(),"logs"))}catch{return[]}let s=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))s.add(r.slice(0,-i.length));return[...s]}async function Bn(e,s,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,s)}async function kr(e){if(e.manifestPath===void 0)return await LA({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let s=ye(e.manifestPath),r=await Fn(e.manifestPath,e.store),i,n,a=o;switch(r.kind){case"reloaded":i="reloaded",n=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",n=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",n=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=d;break;case"failed":i="not reloaded",n=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=d;break;case"no-host":{let l=await je(e.store);if(l===void 0)throw new t({code:"cli_restart_nothing_running",message:`Nothing is hosting ${s}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${s}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${s}\` reloads it in place.`});let c=await Dt(l,e.manifestPath,e.store);if(c.ok)i="started",n=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",n=`pid ${l.pid} did not adopt it${c.detail===void 0?"":`: ${c.detail}`}`,a=d;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:s,result:r,ok:a===o},null,2)}
194
+ `),o}async function wr(e,s,r){if(e.includes("/")||e.endsWith(".yaml")||e.endsWith(".yml"))throw new t({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${e}" is a path.`,hint:`An agent outside ${ne()} 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=Z(),n=i.find((h)=>h.ref===e);if(n===void 0){let h=i.map((w)=>w.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${h.length===0?", which is empty":""}.`,hint:h.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${h.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=n.id;if(a===void 0)try{a=G(n.manifestPath).id}catch{}let l=s.filesOnly===!0||a===void 0,c=a??e,f=await r.agentFootprint(c),g=f.lease?await r.leases.get(c):void 0,m=br(s),p=Wo(A.slug,c);return{ref:e,agentId:c,manifestPath:n.manifestPath,dir:n.dir,files:Sa(n.dir),footprint:f,logs:$r(c),sharesIdWith:i.filter((h)=>h.ref!==e&&(h.id??"")===c).map((h)=>h.ref),...g!==void 0&&V(g.pid)?{running:{pid:g.pid,mode:g.mode}}:{},...m?.state(p).installed===!0?{service:p}:{},filesOnly:l}}function br(e){let s=e.platform??process.platform;if(s!=="darwin")return;return $t(s,{home:ba(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Sa(e){let s=0,r=0,i=(n)=>{let a;try{a=Zs(n)}catch{return}for(let l of a){let c=ur(n,l);try{let f=dr(c);if(f.isDirectory()){i(c);continue}s+=1,r+=f.size}catch{}}};return i(e),{count:s,bytes:r}}function $r(e){let s=cn(e),r=[];for(let i of[s.out,s.err])try{if(!wa(i))continue;r.push({path:i,bytes:dr(i).size})}catch{}return r}function Ea(){let e;try{e=Zs(ur(Se(),"logs"))}catch{return[]}let s=new Set;for(let r of e)for(let i of[".out.log",".err.log"])if(r.endsWith(i))s.add(r.slice(0,-i.length));return[...s]}async function Bn(e,s,r){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(r,s)}async function kr(e){if(e.manifestPath===void 0)return await LA({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let s=Qe(e.manifestPath),r=await Fn(e.manifestPath,e.store),i,n,a=o;switch(r.kind){case"reloaded":i="reloaded",n=`pid ${r.pid} rebuilt it from disk${r.adopted.length>0?` · adopted ${r.adopted.join(", ")}`:""}`;break;case"pending":i="reload pending",n=`pid ${r.pid} applies it when its ${r.running} running turn(s) finish`;break;case"busy":i="not reloaded",n=`pid ${r.pid} has a turn in flight — try again when it finishes`,a=d;break;case"failed":i="not reloaded",n=`pid ${r.pid} answered ${r.status}${r.detail===void 0?"":`: ${r.detail}`}${r.hint===void 0?"":` — ${r.hint}`}`,a=d;break;case"no-host":{let l=await je(e.store);if(l===void 0)throw new t({code:"cli_restart_nothing_running",message:`Nothing is hosting ${s}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${s}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${s}\` reloads it in place.`});let c=await Dt(l,e.manifestPath,e.store);if(c.ok)i="started",n=`nothing was hosting it — adopted by pid ${l.pid}`;else i="not started",n=`pid ${l.pid} did not adopt it${c.detail===void 0?"":`: ${c.detail}`}`,a=d;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:s,result:r,ok:a===o},null,2)}
195
195
  `);else process.stdout.write(`${u([{label:s,value:i,note:n}])}
196
- `);return a}import{randomBytes as zn}from"node:crypto";import{existsSync as _a}from"node:fs";import{createInterface as Nr}from"node:readline";class $e extends Error{code;hint;field;status;request;constructor(e,s={}){super(e.hint===void 0?e.message:`${e.message}
197
- hint: ${e.hint}`);if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.status=s.status,this.request=s.method===void 0||s.path===void 0?void 0:{method:s.method,path:s.path},s.cause!==void 0)this.cause=s.cause}}function Ra(e,s){let r=e instanceof Error?e.message:String(e);return new $e({code:"transport_failed",message:`${s.method} ${s.path} did not reach ${s.baseUrl}: ${r}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...s,cause:e})}async function Pa(e,s){let r;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")r={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new $e(r??{code:`http_${e.status}`,message:`${s.method} ${s.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...s})}var Rr=new Set(xA);async function*Pr(e){for await(let s of gr(xa(e))){if(s.event===void 0||s.data==="")continue;let r;try{r=JSON.parse(s.data)}catch{continue}yield{name:s.event,data:r}}}async function*xa(e){let s=e.getReader();try{while(!0){let{done:r,value:i}=await s.read();if(r)return;if(i!==void 0)yield i}}finally{s.releaseLock()}}async function*Ta(e){for await(let{name:s,data:r}of Pr(e)){if(Rr.has(s)){yield{kind:"event",event:r};continue}let i=r??{};switch(s){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Ia(e){for await(let{name:s,data:r}of Pr(e)){if(Rr.has(s)){yield{kind:"event",event:r};continue}if(s==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*Aa(e,s={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&s.allowTruncated!==!0)throw new $e({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 $e({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 Tr(e){let s=e.baseUrl.length;while(s>0&&e.baseUrl[s-1]==="/")s-=1;let r=e.baseUrl.slice(0,s),i=e.fetch??fetch,n=(m={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...m});async function a(m,p,h={}){let w;try{w=await i(`${r}${p}`,{method:m,headers:n({...h.body===void 0?{}:{"content-type":"application/json"},...h.accept===void 0?{}:{accept:h.accept},...h.headers}),...h.body===void 0?{}:{body:JSON.stringify(h.body)},...h.signal===void 0?{}:{signal:h.signal}})}catch(S){throw Ra(S,{method:m,path:p,baseUrl:r})}if(!w.ok)throw await Pa(w,{method:m,path:p});return w}async function l(m,p,h){return await(await a(m,p,h??{})).json()}async function c(m,p){let h=await a("GET",m,{accept:"text/event-stream",...p===void 0?{}:{signal:p}});if(h.body===null)throw new $e({code:"no_response_body",message:`GET ${m} returned ${h.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:h.status,method:"GET",path:m});return h.body}function f(m,p,h,w={}){let S=(b)=>{let C=new URLSearchParams;if(b?.chunks===!0)C.set("chunks","true");if(b?.children===!0)C.set("children","true");let M=C.toString();return M===""?"":`?${M}`},E={turnId:p,sessionKey:h,replayed:w.replayed===!0,async*stream(b){let C=await c(`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}/stream${S(b)}`,b?.signal);yield*Ta(C)},async*tokens(b){yield*Aa(E.stream({chunks:!0,...b,children:!1}),{...b?.allowTruncated===void 0?{}:{allowTruncated:b.allowTruncated}})},async text(){for await(let b of E.stream()){if(b.kind==="ended")break;if(b.kind==="unavailable")break;if(b.kind==="event"&&b.event.type==="turn.end")break}return(await E.get()).text},get:()=>l("GET",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}/stop`)}};return E}function g(m){let p=(h)=>`/v1/agents/${encodeURIComponent(m)}${h}`;return{id:m,async send(h,w){let S=await l("POST",p("/messages"),{body:{text:h,...w?.sessionKey===void 0?{}:{sessionKey:w.sessionKey},...w?.deliver===void 0?{}:{deliver:w.deliver},...w?.from===void 0?{}:{from:w.from},...w?.images===void 0?{}:{images:w.images},...w?.runtimeNote===void 0?{}:{runtimeNote:w.runtimeNote},...w?.chunks===!0?{chunks:!0}:{},...w?.role===void 0?{}:{role:w.role}},...w?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":w.idempotencyKey}},...w?.signal===void 0?{}:{signal:w.signal}});return f(m,S.turnId,S.sessionKey,{replayed:S.replayed===!0})},turn:(h)=>f(m,h,""),describe:()=>l("GET",p("")),tools:()=>l("GET",p("/tools")),skills:()=>l("GET",p("/skills")),sessions:()=>l("GET",p("/sessions")),messages:(h,w)=>{let S=new URLSearchParams;if(w?.before!==void 0)S.set("before",String(w.before));if(w?.limit!==void 0)S.set("limit",String(w.limit));let E=S.size===0?"":`?${S.toString()}`;return l("GET",p(`/sessions/${encodeURIComponent(h)}/messages${E}`))},clearSession:(h)=>l("DELETE",p(`/sessions/${encodeURIComponent(h)}`)),reload:()=>l("POST",p("/reload"),{body:{}}),usage:(h)=>l("GET",p(`/usage${Er(h)}`)),turns:(h)=>{let w=new URLSearchParams;if(h?.limit!==void 0)w.set("limit",String(h.limit));if(h?.before!==void 0)w.set("before",String(h.before));let S=w.size===0?"":`?${w.toString()}`;return l("GET",p(`/turns${S}`))},secrets:async()=>(await l("GET",p("/secrets"))).secrets,setSecrets:(h)=>l("PUT",p("/secrets"),{body:{values:h}}),schedules:async()=>(await l("GET",p("/schedules"))).schedules,approvals:async()=>(await l("GET",p("/approvals"))).approvals,createSchedule:(h)=>l("POST",p("/schedules"),{body:h}),updateSchedule:(h,w)=>l("PATCH",p(`/schedules/${encodeURIComponent(h)}`),{body:w}),deleteSchedule:async(h)=>{await l("DELETE",p(`/schedules/${encodeURIComponent(h)}`))},runSchedule:(h)=>l("POST",p(`/schedules/${encodeURIComponent(h)}/run`),{body:{}}),config:()=>l("GET",p("/config")),setConfig:(h,w,S)=>l("PATCH",p("/config"),{body:{path:h,value:w,...S?.confirm===void 0?{}:{confirm:S.confirm}}}),removeConfig:(h,w)=>l("PATCH",p("/config"),{body:{path:h,remove:!0,...w?.confirm===void 0?{}:{confirm:w.confirm}}}),setChannel:(h,w)=>l("PATCH",p(`/channels/${encodeURIComponent(h)}`),{body:{...w}}),unpairChannel:(h)=>l("POST",p(`/channels/${encodeURIComponent(h)}/unpair`)),session:(h)=>l("GET",p(`/sessions/${encodeURIComponent(h)}`)),setPhase:(h,w)=>l("POST",p(`/sessions/${encodeURIComponent(h)}/phase`),{body:{phase:w}}),setRecall:(h,w)=>l("POST",p(`/sessions/${encodeURIComponent(h)}/recall`),{body:{recall:w}}),approve:async(h,w)=>{await l("POST",p(`/approvals/${encodeURIComponent(h)}`),{body:{granted:w}})},stop:(h)=>l("POST",p("/stop"),{body:h===void 0?{}:{reason:h}}),start:()=>l("POST",p("/start"),{body:{}}),assign:(h)=>l("PUT",p("/assignee"),{body:{participantId:h}}),unassign:()=>l("DELETE",p("/assignee")),exportBundle:(h)=>l("GET",p(`/export${h===void 0?"":`?paths=${encodeURIComponent(h.join(","))}`}`)),importBundle:(h,w)=>l("POST",p("/import"),{body:{bundle:h,...w===void 0?{}:{mode:w}}}),context:(h)=>{let w=new URLSearchParams;if(h?.sessionKey!==void 0)w.set("sessionKey",h.sessionKey);if(h?.input!==void 0)w.set("input",h.input);let S=w.size===0?"":`?${w.toString()}`;return l("GET",p(`/context${S}`))}}}return{agent:g,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(m){if(m instanceof $e&&m.status===503)return!1;throw m}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(m)=>l("POST","/v1/keys",{body:m}),revokeKey:(m)=>l("DELETE",`/v1/keys/${encodeURIComponent(m)}`),createAgent:(m)=>l("POST","/v1/agents",{body:{answers:m}}),usage:(m)=>l("GET",`/v1/usage${Er(m)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(m)=>l("POST","/v1/participants",{body:m}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(m)=>l("POST","/v1/conversations",{body:m}),conversation:(m)=>l("GET",`/v1/conversations/${encodeURIComponent(m)}`),setMembers:(m,p)=>l("PATCH",`/v1/conversations/${encodeURIComponent(m)}/members`,{body:p}),postMessage:(m,p)=>l("POST",`/v1/conversations/${encodeURIComponent(m)}/messages`,{body:p}),conversationMessages:(m,p={})=>{let h=new URLSearchParams;if(p.after!==void 0)h.set("after",String(p.after));if(p.limit!==void 0)h.set("limit",String(p.limit));let w=h.size===0?"":`?${h}`;return l("GET",`/v1/conversations/${encodeURIComponent(m)}/messages${w}`)},setPresence:(m,p)=>l("PUT",`/v1/participants/${encodeURIComponent(m)}/presence`,{body:{presence:p}}),actions:async(m={})=>(await l("GET",`/v1/actions${m.status===void 0?"":`?status=${m.status}`}`)).actions,decideAction:(m,p)=>l("POST",`/v1/actions/${encodeURIComponent(m)}`,{body:{approve:p}}),addNote:(m)=>l("POST","/v1/memory/notes",{body:m}),notes:async(m)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(m)}`)).notes,deleteNote:(m)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(m)}`),memoryReads:async(m)=>(await l("GET",`/v1/participants/${encodeURIComponent(m)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(m,p)=>l("PUT",`/v1/projects/${encodeURIComponent(m)}`,{body:p}),deleteProject:(m)=>l("DELETE",`/v1/projects/${encodeURIComponent(m)}`),setSpaceWriter:(m)=>l("PUT","/v1/memory/space/writer",{body:{writer:m}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(m)=>l("POST","/v1/webhooks",{body:m}),deleteWebhook:(m)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(m)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(m)=>l("POST","/v1/agents",{body:m}),async*events(m){let p=new URLSearchParams;if(m?.agentId!==void 0)p.set("agentId",m.agentId);if(m?.types!==void 0&&m.types.length>0)p.set("types",m.types.join(","));if(m?.chunks===!0)p.set("chunks","true");let h=p.size===0?"":`?${p.toString()}`,w=await c(`/v1/events${h}`,m?.signal);yield*Ia(w)}}}function Er(e){let s=new URLSearchParams;if(e?.by!==void 0)s.set("by",e.by.join(","));if(e?.from!==void 0)s.set("from",e.from);if(e?.to!==void 0)s.set("to",e.to);return s.size===0?"":`?${s.toString()}`}function Ne(e,s){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let n=ci(i,s);if(n==="")continue;r.push({role:i.role,text:n})}return r}function Ir(e){let s=e.ref??"<your agent>",r=`${A.slug} run ${s} --session ${e.sessionKey}`;return`
196
+ `);return a}import{randomBytes as zn}from"node:crypto";import{existsSync as _a}from"node:fs";import{createInterface as Nr}from"node:readline";class we extends Error{code;hint;field;status;request;constructor(e,s={}){super(e.hint===void 0?e.message:`${e.message}
197
+ hint: ${e.hint}`);if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.status=s.status,this.request=s.method===void 0||s.path===void 0?void 0:{method:s.method,path:s.path},s.cause!==void 0)this.cause=s.cause}}function Ra(e,s){let r=e instanceof Error?e.message:String(e);return new we({code:"transport_failed",message:`${s.method} ${s.path} did not reach ${s.baseUrl}: ${r}`,hint:"Check the base URL, that the server is running, and that nothing between you and it is refusing the connection. `GET /v1/health` needs no token and is the cheapest probe."},{...s,cause:e})}async function Pa(e,s){let r;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")r={code:i.error.code,message:i.error.message,...i.error.hint===void 0?{}:{hint:i.error.hint},...i.error.field===void 0?{}:{field:i.error.field}}}catch{}return new we(r??{code:`http_${e.status}`,message:`${s.method} ${s.path} returned ${e.status} with no error body.`,hint:"This is not a response this server produces, so something between you and it answered — a proxy, a gateway, or a load balancer. Check the URL and what is in front of it."},{status:e.status,...s})}var Rr=new Set(xA);async function*Pr(e){for await(let s of gr(xa(e))){if(s.event===void 0||s.data==="")continue;let r;try{r=JSON.parse(s.data)}catch{continue}yield{name:s.event,data:r}}}async function*xa(e){let s=e.getReader();try{while(!0){let{done:r,value:i}=await s.read();if(r)return;if(i!==void 0)yield i}}finally{s.releaseLock()}}async function*Ta(e){for await(let{name:s,data:r}of Pr(e)){if(Rr.has(s)){yield{kind:"event",event:r};continue}let i=r??{};switch(s){case"turn.accepted":yield{kind:"accepted",turnId:String(i.turnId??""),sessionKey:String(i.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:i.state==="ended"?"ended":"running",events:Number(i.events??0),truncated:i.truncated===!0,dropped:Number(i.dropped??0),chunks:i.chunks==="start"||i.chunks==="partial"?i.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(i.turnId??""),status:String(i.status??"unknown"),steps:typeof i.steps==="number"?i.steps:void 0,errorCode:typeof i.errorCode==="string"?i.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(i.turnId??""),reason:String(i.reason??"not observable from this process")};break;default:break}}}async function*Ia(e){for await(let{name:s,data:r}of Pr(e)){if(Rr.has(s)){yield{kind:"event",event:r};continue}if(s==="stream.subscribed"){let i=r??{};yield{kind:"subscribed",report:{agentId:typeof i.agentId==="string"?i.agentId:null,types:Array.isArray(i.types)?i.types:null,chunks:i.chunks===!0,implied:typeof i.implied==="string"?i.implied:void 0}}}}}async function*Aa(e,s={}){for await(let r of e){if(r.kind==="replay"&&r.report.truncated&&s.allowTruncated!==!0)throw new we({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 we({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 Tr(e){let s=e.baseUrl.length;while(s>0&&e.baseUrl[s-1]==="/")s-=1;let r=e.baseUrl.slice(0,s),i=e.fetch??fetch,n=(m={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...m});async function a(m,p,h={}){let w;try{w=await i(`${r}${p}`,{method:m,headers:n({...h.body===void 0?{}:{"content-type":"application/json"},...h.accept===void 0?{}:{accept:h.accept},...h.headers}),...h.body===void 0?{}:{body:JSON.stringify(h.body)},...h.signal===void 0?{}:{signal:h.signal}})}catch(S){throw Ra(S,{method:m,path:p,baseUrl:r})}if(!w.ok)throw await Pa(w,{method:m,path:p});return w}async function l(m,p,h){return await(await a(m,p,h??{})).json()}async function c(m,p){let h=await a("GET",m,{accept:"text/event-stream",...p===void 0?{}:{signal:p}});if(h.body===null)throw new we({code:"no_response_body",message:`GET ${m} returned ${h.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:h.status,method:"GET",path:m});return h.body}function f(m,p,h,w={}){let S=(b)=>{let C=new URLSearchParams;if(b?.chunks===!0)C.set("chunks","true");if(b?.children===!0)C.set("children","true");let M=C.toString();return M===""?"":`?${M}`},E={turnId:p,sessionKey:h,replayed:w.replayed===!0,async*stream(b){let C=await c(`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}/stream${S(b)}`,b?.signal);yield*Ta(C)},async*tokens(b){yield*Aa(E.stream({chunks:!0,...b,children:!1}),{...b?.allowTruncated===void 0?{}:{allowTruncated:b.allowTruncated}})},async text(){for await(let b of E.stream()){if(b.kind==="ended")break;if(b.kind==="unavailable")break;if(b.kind==="event"&&b.event.type==="turn.end")break}return(await E.get()).text},get:()=>l("GET",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}`),async stop(){await a("POST",`/v1/agents/${encodeURIComponent(m)}/turns/${encodeURIComponent(p)}/stop`)}};return E}function g(m){let p=(h)=>`/v1/agents/${encodeURIComponent(m)}${h}`;return{id:m,async send(h,w){let S=await l("POST",p("/messages"),{body:{text:h,...w?.sessionKey===void 0?{}:{sessionKey:w.sessionKey},...w?.deliver===void 0?{}:{deliver:w.deliver},...w?.from===void 0?{}:{from:w.from},...w?.images===void 0?{}:{images:w.images},...w?.runtimeNote===void 0?{}:{runtimeNote:w.runtimeNote},...w?.chunks===!0?{chunks:!0}:{},...w?.role===void 0?{}:{role:w.role}},...w?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":w.idempotencyKey}},...w?.signal===void 0?{}:{signal:w.signal}});return f(m,S.turnId,S.sessionKey,{replayed:S.replayed===!0})},turn:(h)=>f(m,h,""),describe:()=>l("GET",p("")),tools:()=>l("GET",p("/tools")),skills:()=>l("GET",p("/skills")),sessions:()=>l("GET",p("/sessions")),messages:(h,w)=>{let S=new URLSearchParams;if(w?.before!==void 0)S.set("before",String(w.before));if(w?.limit!==void 0)S.set("limit",String(w.limit));let E=S.size===0?"":`?${S.toString()}`;return l("GET",p(`/sessions/${encodeURIComponent(h)}/messages${E}`))},clearSession:(h)=>l("DELETE",p(`/sessions/${encodeURIComponent(h)}`)),reload:()=>l("POST",p("/reload"),{body:{}}),usage:(h)=>l("GET",p(`/usage${Er(h)}`)),turns:(h)=>{let w=new URLSearchParams;if(h?.limit!==void 0)w.set("limit",String(h.limit));if(h?.before!==void 0)w.set("before",String(h.before));let S=w.size===0?"":`?${w.toString()}`;return l("GET",p(`/turns${S}`))},secrets:async()=>(await l("GET",p("/secrets"))).secrets,setSecrets:(h)=>l("PUT",p("/secrets"),{body:{values:h}}),schedules:async()=>(await l("GET",p("/schedules"))).schedules,approvals:async()=>(await l("GET",p("/approvals"))).approvals,createSchedule:(h)=>l("POST",p("/schedules"),{body:h}),updateSchedule:(h,w)=>l("PATCH",p(`/schedules/${encodeURIComponent(h)}`),{body:w}),deleteSchedule:async(h)=>{await l("DELETE",p(`/schedules/${encodeURIComponent(h)}`))},runSchedule:(h)=>l("POST",p(`/schedules/${encodeURIComponent(h)}/run`),{body:{}}),config:()=>l("GET",p("/config")),setConfig:(h,w,S)=>l("PATCH",p("/config"),{body:{path:h,value:w,...S?.confirm===void 0?{}:{confirm:S.confirm}}}),removeConfig:(h,w)=>l("PATCH",p("/config"),{body:{path:h,remove:!0,...w?.confirm===void 0?{}:{confirm:w.confirm}}}),setChannel:(h,w)=>l("PATCH",p(`/channels/${encodeURIComponent(h)}`),{body:{...w}}),unpairChannel:(h)=>l("POST",p(`/channels/${encodeURIComponent(h)}/unpair`)),session:(h)=>l("GET",p(`/sessions/${encodeURIComponent(h)}`)),setPhase:(h,w)=>l("POST",p(`/sessions/${encodeURIComponent(h)}/phase`),{body:{phase:w}}),setRecall:(h,w)=>l("POST",p(`/sessions/${encodeURIComponent(h)}/recall`),{body:{recall:w}}),approve:async(h,w)=>{await l("POST",p(`/approvals/${encodeURIComponent(h)}`),{body:{granted:w}})},stop:(h)=>l("POST",p("/stop"),{body:h===void 0?{}:{reason:h}}),start:()=>l("POST",p("/start"),{body:{}}),assign:(h)=>l("PUT",p("/assignee"),{body:{participantId:h}}),unassign:()=>l("DELETE",p("/assignee")),exportBundle:(h)=>l("GET",p(`/export${h===void 0?"":`?paths=${encodeURIComponent(h.join(","))}`}`)),importBundle:(h,w)=>l("POST",p("/import"),{body:{bundle:h,...w===void 0?{}:{mode:w}}}),context:(h)=>{let w=new URLSearchParams;if(h?.sessionKey!==void 0)w.set("sessionKey",h.sessionKey);if(h?.input!==void 0)w.set("input",h.input);let S=w.size===0?"":`?${w.toString()}`;return l("GET",p(`/context${S}`))}}}return{agent:g,agents:()=>l("GET","/v1/agents"),health:()=>l("GET","/v1/health"),async ready(){try{return await a("GET","/v1/ready"),!0}catch(m){if(m instanceof we&&m.status===503)return!1;throw m}},provision:()=>l("GET","/v1/provision"),keys:()=>l("GET","/v1/keys"),createKey:(m)=>l("POST","/v1/keys",{body:m}),revokeKey:(m)=>l("DELETE",`/v1/keys/${encodeURIComponent(m)}`),createAgent:(m)=>l("POST","/v1/agents",{body:{answers:m}}),usage:(m)=>l("GET",`/v1/usage${Er(m)}`),activity:()=>l("GET","/v1/activity"),participants:async()=>(await l("GET","/v1/participants")).participants,registerParticipant:(m)=>l("POST","/v1/participants",{body:m}),conversations:async()=>(await l("GET","/v1/conversations")).conversations,createConversation:(m)=>l("POST","/v1/conversations",{body:m}),conversation:(m)=>l("GET",`/v1/conversations/${encodeURIComponent(m)}`),setMembers:(m,p)=>l("PATCH",`/v1/conversations/${encodeURIComponent(m)}/members`,{body:p}),postMessage:(m,p)=>l("POST",`/v1/conversations/${encodeURIComponent(m)}/messages`,{body:p}),conversationMessages:(m,p={})=>{let h=new URLSearchParams;if(p.after!==void 0)h.set("after",String(p.after));if(p.limit!==void 0)h.set("limit",String(p.limit));let w=h.size===0?"":`?${h}`;return l("GET",`/v1/conversations/${encodeURIComponent(m)}/messages${w}`)},setPresence:(m,p)=>l("PUT",`/v1/participants/${encodeURIComponent(m)}/presence`,{body:{presence:p}}),actions:async(m={})=>(await l("GET",`/v1/actions${m.status===void 0?"":`?status=${m.status}`}`)).actions,decideAction:(m,p)=>l("POST",`/v1/actions/${encodeURIComponent(m)}`,{body:{approve:p}}),addNote:(m)=>l("POST","/v1/memory/notes",{body:m}),notes:async(m)=>(await l("GET",`/v1/memory/notes?scope=${encodeURIComponent(m)}`)).notes,deleteNote:(m)=>l("DELETE",`/v1/memory/notes/${encodeURIComponent(m)}`),memoryReads:async(m)=>(await l("GET",`/v1/participants/${encodeURIComponent(m)}/memory/reads`)).reads,projects:async()=>(await l("GET","/v1/projects")).projects,putProject:(m,p)=>l("PUT",`/v1/projects/${encodeURIComponent(m)}`,{body:p}),deleteProject:(m)=>l("DELETE",`/v1/projects/${encodeURIComponent(m)}`),setSpaceWriter:(m)=>l("PUT","/v1/memory/space/writer",{body:{writer:m}}),webhooks:async()=>(await l("GET","/v1/webhooks")).webhooks,createWebhook:(m)=>l("POST","/v1/webhooks",{body:m}),deleteWebhook:(m)=>l("DELETE",`/v1/webhooks/${encodeURIComponent(m)}`),templates:async()=>(await l("GET","/v1/templates")).templates,createAgentFromTemplate:(m)=>l("POST","/v1/agents",{body:m}),async*events(m){let p=new URLSearchParams;if(m?.agentId!==void 0)p.set("agentId",m.agentId);if(m?.types!==void 0&&m.types.length>0)p.set("types",m.types.join(","));if(m?.chunks===!0)p.set("chunks","true");let h=p.size===0?"":`?${p.toString()}`,w=await c(`/v1/events${h}`,m?.signal);yield*Ia(w)}}}function Er(e){let s=new URLSearchParams;if(e?.by!==void 0)s.set("by",e.by.join(","));if(e?.from!==void 0)s.set("from",e.from);if(e?.to!==void 0)s.set("to",e.to);return s.size===0?"":`?${s.toString()}`}function Ce(e,s){let r=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let n=ci(i,s);if(n==="")continue;r.push({role:i.role,text:n})}return r}function Ir(e){let s=e.ref??"<your agent>",r=`${A.slug} run ${s} --session ${e.sessionKey}`;return`
198
198
  ${ea}Resume this session with:
199
199
  ${r}${wo}
200
- `}function Jn(e,s){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return s===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${s}, still in the store. /sessions goes back to it.`}}function Oa(e){return e==="nlt"?lr():cr()}function Or(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(s)=>e.bus.on("*",s,{chunks:!0}),send:(s,r)=>e.send(s,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,tools:async()=>qo(e.agent),context:e.context,close:async()=>{}}}function _r(e){let s=e.client.agent(e.agentId),r=new Set,i=new AbortController,n,a=()=>{if(n!==void 0)return;n=(async()=>{for await(let l of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(l.kind!=="event"||l.event===void 0)continue;for(let c of r)c(l.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(l)=>(r.add(l),a(),()=>r.delete(l)),send:async(l,c)=>{let f=!1,g,m=()=>{if(f=!0,g!==void 0)s.turn(g).stop().catch(()=>{})};c.signal.addEventListener("abort",m,{once:!0});let p,h=new Promise((w)=>{let S=(E)=>{if(g!==void 0&&E.turnId!==void 0&&E.turnId!==g)return;if(E.type==="error"){p=E.data;return}if(E.type!=="turn.end")return;r.delete(S),w({text:"",reason:E.data.reason,steps:E.data.steps,durationMs:E.data.durationMs,tokens:E.data.tokens,...p===void 0?{}:{error:p}})};r.add(S),a()});try{if(g=(await s.send(l,{sessionKey:c.sessionKey})).turnId,f)s.turn(g).stop().catch(()=>{});return await h}finally{c.signal.removeEventListener("abort",m)}},streamFilter:()=>Oa(e.description.dialect),history:async(l)=>{let c=await s.messages(l);return Ne([...c.messages].reverse().map((f)=>({role:f.role,content:f.content,...f.origin===void 0?{}:{origin:f.origin}})),e.description.dialect)},sessions:()=>s.sessions(),clearSession:async(l)=>{await s.clearSession(l)},tools:async()=>{let l=await s.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:l.map((c)=>({slug:c.slug,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},summary:c.summary}))}},context:async(l)=>{let c=await s.context({sessionKey:l});return{...c,windowSource:"as the host resolved it",...c.lastCompaction===void 0&&c.compactions!==void 0?{lastCompaction:c.compactions===0?void 0:`${c.compactions} stage${c.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await s.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Cr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function Ca(e,s,r,i,n,a=[],l){let c=e.describe(),[f,g]=await Promise.all([e.turns(s,1),e.store.messages.count(e.id,s)]),m=[`${A.name} ${j} · ${c.id} · ${c.model}`,`session ${s} · ${g} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],p=Jn(n,l);if(p!==void 0)m.push(p);if(f[0]?.errorCode==="turn_abandoned")m.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let h of[...e.warnings,...e.tools.warnings])m.push(`note: ${h.message}
200
+ `}function Jn(e,s){switch(e){case"first":return;case"restart":return"restarted — the configuration on disk is now the one in force; the conversation continues from the store.";case"switch":return"switched conversation — the one you left is still in the store, under its own key.";case"new":return s===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${s}, still in the store. /sessions goes back to it.`}}function Oa(e){return e==="nlt"?lr():cr()}function Or(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(s)=>e.bus.on("*",s,{chunks:!0}),send:(s,r)=>e.send(s,{...r,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,tools:async()=>qo(e.agent),context:e.context,close:async()=>{}}}function _r(e){let s=e.client.agent(e.agentId),r=new Set,i=new AbortController,n,a=()=>{if(n!==void 0)return;n=(async()=>{for await(let l of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(l.kind!=="event"||l.event===void 0)continue;for(let c of r)c(l.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(l)=>(r.add(l),a(),()=>r.delete(l)),send:async(l,c)=>{let f=!1,g,m=()=>{if(f=!0,g!==void 0)s.turn(g).stop().catch(()=>{})};c.signal.addEventListener("abort",m,{once:!0});let p,h=new Promise((w)=>{let S=(E)=>{if(g!==void 0&&E.turnId!==void 0&&E.turnId!==g)return;if(E.type==="error"){p=E.data;return}if(E.type!=="turn.end")return;r.delete(S),w({text:"",reason:E.data.reason,steps:E.data.steps,durationMs:E.data.durationMs,tokens:E.data.tokens,...p===void 0?{}:{error:p}})};r.add(S),a()});try{if(g=(await s.send(l,{sessionKey:c.sessionKey})).turnId,f)s.turn(g).stop().catch(()=>{});return await h}finally{c.signal.removeEventListener("abort",m)}},streamFilter:()=>Oa(e.description.dialect),history:async(l)=>{let c=await s.messages(l);return Ce([...c.messages].reverse().map((f)=>({role:f.role,content:f.content,...f.origin===void 0?{}:{origin:f.origin}})),e.description.dialect)},sessions:()=>s.sessions(),clearSession:async(l)=>{await s.clearSession(l)},tools:async()=>{let l=await s.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:l.map((c)=>({slug:c.slug,mutating:c.mutating,trust:c.trust,...c.trustReason===void 0?{}:{trustReason:c.trustReason},summary:c.summary}))}},context:async(l)=>{let c=await s.context({sessionKey:l});return{...c,windowSource:"as the host resolved it",...c.lastCompaction===void 0&&c.compactions!==void 0?{lastCompaction:c.compactions===0?void 0:`${c.compactions} stage${c.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await s.reload()).adopted,close:async()=>{i.abort(),r.clear()}}}function Cr(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function Ca(e,s,r,i,n,a=[],l){let c=e.describe(),[f,g]=await Promise.all([e.turns(s,1),e.store.messages.count(e.id,s)]),m=[`${A.name} ${j} · ${c.id} · ${c.model}`,`session ${s} · ${g} message(s) · window ${c.window} · store ${r}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],p=Jn(n,l);if(p!==void 0)m.push(p);if(f[0]?.errorCode==="turn_abandoned")m.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let h of[...e.warnings,...e.tools.warnings])m.push(`note: ${h.message}
201
201
  ${h.hint}`);if(a.length>0)m.push(`note: ${a.join(", ")} in the .env here ${a.length===1?"was":"were"} ignored — this agent's own .env sets ${a.length===1?"it":"them"}.
202
202
  A .env in the directory you launched from configures that project, not an agent living somewhere else. Export the variable to override the agent's own file.`);return m}async function Qn(e){let s=e.once!==void 0,r=AA({json:!1,plain:e.plain===!0,oneShot:s}),{mode:i}=r;if(e.manifestPath===void 0){let E=await ja(i,r.because,e);if(typeof E==="number")return E;return Qn({...e,manifestPath:E})}let n=ai();if(e.store===void 0&&e.ephemeral!==!0&&_a(n))process.stdout.write(`note: a session store exists at ${n} from an earlier version — pass --store ${n} to keep using it; the default is now ${F()}
203
- `);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},f={current:e.sessionKey},g={current:!1},m={current:void 0},p=e.quiet===!0,h="first",w={current:void 0},S=e.ephemeral===!0?void 0:Cr(await Ye(ye(e.manifestPath),e.store));if(S!==void 0)return await Ka({...e,host:S,mode:i==="rich"?"rich":"plain",quiet:p,oneShot:s,reader:l,draft:c,session:f,random:zn});for(;;){let E=await Ie.create({agents:[e.manifestPath],toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,env:R([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??F()});a=E;let b=E.list()[0];if(b===void 0)throw Error("The manifest produced no agent.");if(f.current===void 0||f.current===""){let H=await jr({list:async()=>Mr(await b.store.sessions.list(b.id)),mode:i,asked:f.current,wantsContinue:e.continueSession===!0,random:zn});if(typeof H==="number")return await E.stop("cli-exit"),H;f.current=H.sessionKey,g.current=H.fresh}let C=f.current,M=b.roles.main.capabilities.thinking!=="none",v=e.noReasoning===!0?!1:M,x=p||s?[]:await Ca(b,C,E.store.location,h==="first"?E.boot.processMs:E.boot.bootMs,h,ks([e.manifestPath]),m.current),T=i==="rich"&&!p&&!s?Ne(await b.history(C),b.describe().dialect):[],N=Or({agent:b,bus:E.bus,send:(H,he)=>b.send(H,he),history:async(H)=>Ne(await b.history(H),b.describe().dialect),sessions:async()=>await b.store.sessions.list(b.id),clearSession:async(H)=>{await b.clearSession(H)},context:async(H)=>Ma(b,H),streamFilter:()=>b.streamFilter(),description:{agentId:b.id,name:b.describe().name,model:b.describe().model,dialect:b.describe().dialect,window:b.describe().window,catalogueTokens:b.describe().catalogueTokens,thinking:b.roles.main.capabilities.thinking,warnings:[...b.warnings,...b.tools.warnings]}}),L={...e,source:N,embedded:{agent:b,runtime:E},sessionKey:C,banner:x,prior:T,quiet:p,reader:l,draft:c,showReasoning:v,freshSession:g.current,switchTo:w,random:zn},I=i==="rich"?await Fr(L):await Lr(L);if(await E.stop(I===ke?"restart":"cli-exit"),I!==ke)return I;if(w.current===void 0)h="restart";else h=w.current.reason,m.current=C,f.current=w.current.key,w.current=void 0;g.current=!1}}function Na(e,s){let r=[];for(let i of e)FA({action:"install",manifestPath:s,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var ke=Symbol("restart");async function ja(e,s,r){let i=Z();if(i.length===0){if(e==="rich"){let m=await Tn({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
203
+ `);let a;U(()=>a?.stop("cli-exit"));let l={current:void 0},c={current:""},f={current:e.sessionKey},g={current:!1},m={current:void 0},p=e.quiet===!0,h="first",w={current:void 0},S=e.ephemeral===!0?void 0:Cr(await Ye(Qe(e.manifestPath),e.store));if(S!==void 0)return await Ka({...e,host:S,mode:i==="rich"?"rich":"plain",quiet:p,oneShot:s,reader:l,draft:c,session:f,random:zn});for(;;){let E=await Ie.create({agents:[e.manifestPath],toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,env:R([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??F()});a=E;let b=E.list()[0];if(b===void 0)throw Error("The manifest produced no agent.");if(f.current===void 0||f.current===""){let H=await jr({list:async()=>Mr(await b.store.sessions.list(b.id)),mode:i,asked:f.current,wantsContinue:e.continueSession===!0,random:zn});if(typeof H==="number")return await E.stop("cli-exit"),H;f.current=H.sessionKey,g.current=H.fresh}let C=f.current,M=b.roles.main.capabilities.thinking!=="none",v=e.noReasoning===!0?!1:M,x=p||s?[]:await Ca(b,C,E.store.location,h==="first"?E.boot.processMs:E.boot.bootMs,h,ks([e.manifestPath]),m.current),T=i==="rich"&&!p&&!s?Ce(await b.history(C),b.describe().dialect):[],N=Or({agent:b,bus:E.bus,send:(H,he)=>b.send(H,he),history:async(H)=>Ce(await b.history(H),b.describe().dialect),sessions:async()=>await b.store.sessions.list(b.id),clearSession:async(H)=>{await b.clearSession(H)},context:async(H)=>Ma(b,H),streamFilter:()=>b.streamFilter(),description:{agentId:b.id,name:b.describe().name,model:b.describe().model,dialect:b.describe().dialect,window:b.describe().window,catalogueTokens:b.describe().catalogueTokens,thinking:b.roles.main.capabilities.thinking,warnings:[...b.warnings,...b.tools.warnings]}}),L={...e,source:N,embedded:{agent:b,runtime:E},sessionKey:C,banner:x,prior:T,quiet:p,reader:l,draft:c,showReasoning:v,freshSession:g.current,switchTo:w,random:zn},I=i==="rich"?await Fr(L):await Lr(L);if(await E.stop(I===$e?"restart":"cli-exit"),I!==$e)return I;if(w.current===void 0)h="restart";else h=w.current.reason,m.current=C,f.current=w.current.key,w.current=void 0;g.current=!1}}function Na(e,s){let r=[];for(let i of e)FA({action:"install",manifestPath:s,name:`${i.source}/${i.skill}`,quiet:!0,collect:r});return r}var $e=Symbol("restart");async function ja(e,s,r){let i=Z();if(i.length===0){if(e==="rich"){let m=await Tn({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
204
204
  `),o;if(m.kind==="failed")return m.code;return m.manifestPath}throw new t({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${A.slug} init\`, or pass a path to an agent.yaml.`})}if(i.length===1&&i[0]!==void 0)return process.stdout.write(`running ${i[0].ref} — the only agent in the sandbox
205
205
  `),i[0].manifestPath;if(e!=="rich"){for(let m of i)process.stdout.write(`${m.ref} ${m.problem??m.modelId??"?"} ${m.dir}
206
206
  `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${s})
207
- `),d}let[{render:n},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-j6n1pda7.js")]),c={kind:"quit"};Xn();let f=n(a(l,{title:`${A.name} ${j}`,agents:i,onDone:(m)=>{c=m}}),{exitOnCtrlC:!1,...Pe(r.noEnhancedKeys)});U(()=>f.unmount()),await f.waitUntilExit(),f.unmount();let g=c;if(g.kind==="quit")return process.stdout.write(`nothing run
207
+ `),d}let[{render:n},{createElement:a},{Picker:l}]=await Promise.all([import("ink"),import("react"),import("./Picker-1wc5b3j6.js")]),c={kind:"quit"};Xn();let f=n(a(l,{title:`${A.name} ${j}`,agents:i,onDone:(m)=>{c=m}}),{exitOnCtrlC:!1,...Pe(r.noEnhancedKeys)});U(()=>f.unmount()),await f.waitUntilExit(),f.unmount();let g=c;if(g.kind==="quit")return process.stdout.write(`nothing run
208
208
  `),o;if(g.kind==="create"){let m=await Tn({plain:r.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
209
209
  `),o;if(m.kind==="failed")return m.code;return m.manifestPath}return g.manifestPath}async function jr(e){let s=()=>({sessionKey:Jo(e.random),fresh:!0});if(e.wantsContinue&&e.asked==="")throw new t({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(e.wantsContinue){let r=await e.list(),i=Fa(r);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
210
210
  `),s();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let r=await e.list();if(r.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
211
211
  `),s();if(e.mode!=="rich"){for(let n of[...r].sort(on))process.stdout.write(`${n.sessionKey} ${n.messages} ${n.turns} ${n.lastActivityAt}
212
212
  `);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
213
- `),d}let i=await La([...r].sort(on));return i===void 0?s():{sessionKey:i,fresh:!1}}return e.asked===void 0?s():{sessionKey:e.asked,fresh:!1}}function on(e,s){return Date.parse(s.lastActivityAt)-Date.parse(e.lastActivityAt)}function Fa(e){return[...e].sort(on)[0]}async function La(e){let[{render:s},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-6ac1574k.js")]),n;Xn();let a=s(r(i,{sessions:e.map((l)=>({sessionKey:l.sessionKey,messages:l.messages,turns:l.turns,lastActivityAt:l.lastActivityAt,phase:l.phase})),now:Date.now(),columns:_e(process.stdout.columns,be),maxRows:fn,onDone:(l)=>{n=l,a.unmount()}}),{exitOnCtrlC:!1,...Pe()});return U(()=>a.unmount()),await a.waitUntilExit(),n}function Ua(e,s,r,i,n){let a=e.describe(),l=[`${A.name} ${j} · ${a.agentId} · ${a.model}`,`session ${s} · window ${a.window} · attached to ${r.baseUrl} (pid ${r.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],c=Jn(i,n);if(c!==void 0)l.push(c);for(let f of a.warnings)l.push(`warning: ${f.message}`);return l}async function Ka(e){let s=e.manifestPath??"",r=ye(s),i=Nt(s),n=Tr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await n.agent(r).describe();if(a.status==="disabled")throw new t({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${r}\`, then run again.`});let l=_r({client:n,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),c={current:void 0},f="first",g={current:void 0},m={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let b=await jr({list:()=>Dr(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof b==="number")return b;e.session.current=b.sessionKey,m.current=b.fresh}let p=e.session.current??"",h=e.quiet||e.oneShot?[]:Ua(l,p,e.host,f,g.current),w=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(p):[],S={...e,source:l,sessionKey:p,banner:h,prior:w,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:m.current,switchTo:c,random:e.random},E=e.mode==="rich"?await Fr(S):await Lr(S);if(E!==ke)return await l.close(),E;if(c.current===void 0)f="restart";else f=c.current.reason,g.current=p,e.session.current=c.current.key,c.current=void 0;m.current=!1}}async function Fr(e){let[{render:s},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-w7520pb8.js")]),n=Be();U(()=>{n.close()}),BA(),ss(),process.stdout.write(`${wA}${Js}`);let a=!1,l=s(r(i,{source:e.source,onSwitch:(c,f)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=f},onNew:(c)=>{a=!0,e.switchTo.current={key:Jo(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await Dr(e.source)].sort(on).map((f)=>({sessionKey:f.sessionKey,messages:f.messages,turns:f.turns,lastActivityAt:f.lastActivityAt,phase:f.phase})),onRestart:(c)=>{a=!0,e.draft.current=c},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((c)=>c.message),initial:Ui(Fi(e.banner.slice(1)),e.prior),correctKeys:n.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>_t({onStatus:c}),install:async(c,f)=>Cn(Na(c,f))},status:()=>e.embedded===void 0?Gr(e.source):Kr(e.embedded),contextView:()=>Wr(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Pe(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),Je(),!a)process.stdout.write(Ir({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?ke:o}async function Lr(e){let{source:s,sessionKey:r,quiet:i}=e,n=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),n=x.endsWith(`
213
+ `),d}let i=await La([...r].sort(on));return i===void 0?s():{sessionKey:i,fresh:!1}}return e.asked===void 0?s():{sessionKey:e.asked,fresh:!1}}function on(e,s){return Date.parse(s.lastActivityAt)-Date.parse(e.lastActivityAt)}function Fa(e){return[...e].sort(on)[0]}async function La(e){let[{render:s},{createElement:r},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-msy4q87n.js")]),n;Xn();let a=s(r(i,{sessions:e.map((l)=>({sessionKey:l.sessionKey,messages:l.messages,turns:l.turns,lastActivityAt:l.lastActivityAt,phase:l.phase})),now:Date.now(),columns:_e(process.stdout.columns,be),maxRows:fn,onDone:(l)=>{n=l,a.unmount()}}),{exitOnCtrlC:!1,...Pe()});return U(()=>a.unmount()),await a.waitUntilExit(),n}function Ua(e,s,r,i,n){let a=e.describe(),l=[`${A.name} ${j} · ${a.agentId} · ${a.model}`,`session ${s} · window ${a.window} · attached to ${r.baseUrl} (pid ${r.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],c=Jn(i,n);if(c!==void 0)l.push(c);for(let f of a.warnings)l.push(`warning: ${f.message}`);return l}async function Ka(e){let s=e.manifestPath??"",r=Qe(s),i=Nt(s),n=Tr({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await n.agent(r).describe();if(a.status==="disabled")throw new t({code:"agent_disabled",message:`${r} was stopped while this run was attaching.`,hint:`Start it with \`${A.slug} start ${r}\`, then run again.`});let l=_r({client:n,agentId:r,host:e.host,description:{agentId:r,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),c={current:void 0},f="first",g={current:void 0},m={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let b=await jr({list:()=>Dr(l),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof b==="number")return b;e.session.current=b.sessionKey,m.current=b.fresh}let p=e.session.current??"",h=e.quiet||e.oneShot?[]:Ua(l,p,e.host,f,g.current),w=e.mode==="rich"&&!e.quiet&&!e.oneShot?await l.history(p):[],S={...e,source:l,sessionKey:p,banner:h,prior:w,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:m.current,switchTo:c,random:e.random},E=e.mode==="rich"?await Fr(S):await Lr(S);if(E!==$e)return await l.close(),E;if(c.current===void 0)f="restart";else f=c.current.reason,g.current=p,e.session.current=c.current.key,c.current=void 0;m.current=!1}}async function Fr(e){let[{render:s},{createElement:r},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-7mb3d8v1.js")]),n=qe();U(()=>{n.close()}),BA(),ss(),process.stdout.write(`${wA}${Js}`);let a=!1,l=s(r(i,{source:e.source,onSwitch:(c,f)=>{a=!0,e.switchTo.current={key:c,reason:"switch"},e.draft.current=f},onNew:(c)=>{a=!0,e.switchTo.current={key:Jo(e.random),reason:"new"},e.draft.current=c},sessions:async()=>[...await Dr(e.source)].sort(on).map((f)=>({sessionKey:f.sessionKey,messages:f.messages,turns:f.turns,lastActivityAt:f.lastActivityAt,phase:f.phase})),onRestart:(c)=>{a=!0,e.draft.current=c},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((c)=>c.message),initial:Ui(Fi(e.banner.slice(1)),e.prior),correctKeys:n.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(c)=>_t({onStatus:c}),install:async(c,f)=>Cn(Na(c,f))},status:()=>e.embedded===void 0?Gr(e.source):Kr(e.embedded),contextView:()=>Wr(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Pe(e.noEnhancedKeys)});if(U(()=>l.unmount()),await l.waitUntilExit(),Je(),!a)process.stdout.write(Ir({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?$e:o}async function Lr(e){let{source:s,sessionKey:r,quiet:i}=e,n=!0,a=(x)=>{if(x==="")return;process.stdout.write(x),n=x.endsWith(`
214
214
  `)},l=(x)=>{if(!n)a(`
215
215
  `);a(`${x}
216
216
  `)};if(e.banner.length>0)a(`${e.banner.join(`
@@ -231,7 +231,7 @@ ${T.error.code}: ${T.error.message}
231
231
  hint: ${T.error.hint}
232
232
  `);if(co(T.reason))b=d;if(!i&&T.reason==="final")a(` ${T.tokens.prompt} prompt · ${T.tokens.output} output · ${T.durationMs} ms
233
233
 
234
- `);await cA()},v=()=>C();process.on("SIGINT",v);try{if(e.once!==void 0)return await M(e.once),b;if(process.stdin.isTTY!==!0){let T=e.reader.current??Nr({input:process.stdin});e.reader.current=T;for await(let N of T){let L=N.trim();if(L==="")continue;let I=await w(L);if(I==="exit")break;if(I==="restart"){b=ke;break}if(I==="handled")continue;await M(L)}return b}let x=e.reader.current??Nr({input:process.stdin,output:process.stdout,prompt:Oo,terminal:!1});e.reader.current=x,x.prompt();for await(let T of x){let N=T.trim();if(N===""){x.prompt();continue}let L=await w(N);if(L==="exit")break;if(L==="restart"){b=ke;break}if(L==="handled"){x.prompt();continue}await M(N),x.prompt()}if(b!==ke)x.close(),e.reader.current=void 0;return b}finally{process.off("SIGINT",v),h()}}async function Kr(e){let{agent:s,runtime:r}=e,i=s.describe(),n=s.manifest,a=n.channels.filter((m)=>m.enabled).map((m)=>`${m.id} (${m.type})`).join(", "),l=a===""?"none — reached through this session and the HTTP API only":r.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,c=!n.server.enabled?"off":`enabled on ${n.server.host}:${n.server.port}, NOT bound here — \`serve\` binds it`,f=yA(n),g=f.filter((m)=>m.role!=="main"&&m.role===m.configuredAs);return u([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${n.tools.dialect} · ${i.window} token window (${it(f[0]?.window)})`},...g.map((m)=>({label:m.role,value:`${m.modelId} · ${m.window.contextWindow} token window (${it(m.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await Da(r,i.id)}])}function Mr(e){return e.filter((s)=>!gi(s.sessionKey))}async function Dr(e){return Mr(await e.sessions())}async function Gr(e){let s=e.describe(),r=e.host,[i,n]=await Promise.all([e.tools(),e.sessions()]);return u([{label:"agent",value:`${s.agentId} (${s.name})`},{label:"attached to",value:r===void 0?"a host":`${r.baseUrl} · pid ${r.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${s.model} · ${s.window} token window`},{label:"dialect",value:s.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${n.length} on this agent`},{label:"warnings",value:s.warnings.length===0?"none":s.warnings.map((a)=>a.message).join("; ")}])}async function Ma(e,s){let r=await e.previewContext({sessionKey:s}),[i]=yA(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:it(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 Wr(e,s){return Pi(await e.source.context(s))}async function Da(e,s){if(e.owned.includes(s))return"this session is serving this agent";let r=await e.store.leases.get(s);if(r!==void 0&&V(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${A.slug} daemon status ${s}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${A.slug} daemon install ${s}\` keeps it running without a terminal`}function ee(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function Ha(e,s){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-s;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let n=Math.round(r/3600000);return n<48?`in ${n}h`:`in ${Math.round(n/24)}d`}function Ga(e,s){if(e.lastFiredAt===void 0)return"never run";let r=et(e.lastFiredAt,s);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function Wa(e,s){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let r=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${ee("SCHEDULE",r)} ${ee("WHEN",i)} ${ee("NEXT",7)} LAST
234
+ `);await cA()},v=()=>C();process.on("SIGINT",v);try{if(e.once!==void 0)return await M(e.once),b;if(process.stdin.isTTY!==!0){let T=e.reader.current??Nr({input:process.stdin});e.reader.current=T;for await(let N of T){let L=N.trim();if(L==="")continue;let I=await w(L);if(I==="exit")break;if(I==="restart"){b=$e;break}if(I==="handled")continue;await M(L)}return b}let x=e.reader.current??Nr({input:process.stdin,output:process.stdout,prompt:Oo,terminal:!1});e.reader.current=x,x.prompt();for await(let T of x){let N=T.trim();if(N===""){x.prompt();continue}let L=await w(N);if(L==="exit")break;if(L==="restart"){b=$e;break}if(L==="handled"){x.prompt();continue}await M(N),x.prompt()}if(b!==$e)x.close(),e.reader.current=void 0;return b}finally{process.off("SIGINT",v),h()}}async function Kr(e){let{agent:s,runtime:r}=e,i=s.describe(),n=s.manifest,a=n.channels.filter((m)=>m.enabled).map((m)=>`${m.id} (${m.type})`).join(", "),l=a===""?"none — reached through this session and the HTTP API only":r.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,c=!n.server.enabled?"off":`enabled on ${n.server.host}:${n.server.port}, NOT bound here — \`serve\` binds it`,f=QA(n),g=f.filter((m)=>m.role!=="main"&&m.role===m.configuredAs);return u([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${n.tools.dialect} · ${i.window} token window (${it(f[0]?.window)})`},...g.map((m)=>({label:m.role,value:`${m.modelId} · ${m.window.contextWindow} token window (${it(m.window)})`})),{label:"channels",value:l},{label:"http api",value:c},{label:"store",value:r.store.location},{label:"background",value:await Da(r,i.id)}])}function Mr(e){return e.filter((s)=>!gi(s.sessionKey))}async function Dr(e){return Mr(await e.sessions())}async function Gr(e){let s=e.describe(),r=e.host,[i,n]=await Promise.all([e.tools(),e.sessions()]);return u([{label:"agent",value:`${s.agentId} (${s.name})`},{label:"attached to",value:r===void 0?"a host":`${r.baseUrl} · pid ${r.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${s.model} · ${s.window} token window`},{label:"dialect",value:s.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${n.length} on this agent`},{label:"warnings",value:s.warnings.length===0?"none":s.warnings.map((a)=>a.message).join("; ")}])}async function Ma(e,s){let r=await e.previewContext({sessionKey:s}),[i]=QA(e.manifest);return{slots:r.slots,history:r.history,cache:r.cache,total:r.total,window:r.window,windowSource:it(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 Wr(e,s){return Pi(await e.source.context(s))}async function Da(e,s){if(e.owned.includes(s))return"this session is serving this agent";let r=await e.store.leases.get(s);if(r!==void 0&&V(r.pid))return r.mode==="daemon"?`running as a background service · pid ${r.pid} · \`${A.slug} daemon status ${s}\``:`served by another session · pid ${r.pid} (${r.mode})`;return`not supervised — \`${A.slug} daemon install ${s}\` keeps it running without a terminal`}function ee(e,s){return e.length>=s?e:e+" ".repeat(s-e.length)}function Ha(e,s){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let r=Date.parse(e.nextRunAt)-s;if(r<=0)return"due";let i=Math.round(r/60000);if(i<60)return`in ${i}m`;let n=Math.round(r/3600000);return n<48?`in ${n}h`:`in ${Math.round(n/24)}d`}function Ga(e,s){if(e.lastFiredAt===void 0)return"never run";let r=et(e.lastFiredAt,s);if(e.lastStatus==="error")return`FAILED ${r}`;return`ok ${r}`}function Wa(e,s){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let r=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${ee("SCHEDULE",r)} ${ee("WHEN",i)} ${ee("NEXT",7)} LAST
235
235
  `);for(let a of e)process.stdout.write(`${ee(a.id,r)} ${ee(`${a.kind} ${a.expr}`,i)} ${ee(Ha(a,s),7)} ${Ga(a,s)}
236
236
  `);let n=e.filter((a)=>a.lastStatus==="error");if(n.length>0)process.stdout.write(`
237
237
  ${n.length} failing — \`schedules --id ${n[0]?.id}\` for the error
@@ -257,9 +257,9 @@ Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
257
257
  `)}if(e.recipients===!0){let a=Ba(await r.store.sessions.list(r.id),r.manifest.channels.map((l)=>l.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
258
258
  `),o;return Va(a,i),o}let n=await r.store.schedules.list(r.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:n},null,2)}
259
259
  `),o;if(e.id!==void 0){let a=n.find((l)=>l.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${r.id}
260
- `),d;return qa(a),o}if(e.enable===void 0&&e.disable===void 0)Wa(n,i);return o}import{rmSync as ed}from"node:fs";import{dirname as nd}from"node:path";import{readFileSync as Ja}from"node:fs";var Xa="server.tokenEnv";function Zn(e){let s=Ja(e,"utf8"),r=kA(e),i=new Map,n=new Set(Ht(s).filter((a)=>a.path===Xa).map((a)=>a.name));for(let a of Ht(s)){if(n.has(a.name))continue;let l=i.get(a.name)??[];l.push(a.path),i.set(a.name,l)}return[...i].map(([a,l])=>({name:a,set:Xt(r,a),usedBy:l}))}function Br(e,s){let r=Zn(e).map((l)=>l.name);for(let[l,c]of Object.entries(s)){if(!r.includes(l))throw new t({code:"secret_not_referenced",message:`"${l}" is not a variable this agent's manifest reads.`,hint:r.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${r.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${l}`});if(c==="")throw new t({code:"secret_value_empty",message:`An empty value for ${l} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${l}`})}let i=R([e]),n=[],a=[];for(let[l,c]of Object.entries(s))if(Ke(e,l,c),n.push(l),Xt(i,l))a.push(l);return{written:n,shadowed:a}}import{createHash as za}from"node:crypto";import{existsSync as xe,lstatSync as ot,mkdirSync as nt,readdirSync as Jr,readFileSync as mn,renameSync as Ya,rmSync as Xr,writeFileSync as Ue}from"node:fs";import{basename as Me,dirname as zr,join as z}from"node:path";var Fe="template.yaml",Yr=/^[a-z0-9][a-z0-9-]*$/;function at(e){let s;try{s=Jr(e)}catch{return[]}let r=[];for(let i of s.sort()){if(!Yr.test(i))continue;let n=z(e,i);if(!ot(n).isDirectory())continue;try{let a=pn(n);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((l)=>({name:l.name,...l.description===void 0?{}:{description:l.description},required:l.required,...l.default===void 0?{}:{default:l.default},secret:l.secret!==void 0}))})}catch(a){if(!B(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function pn(e){let s=z(e,Fe);if(!xe(s))throw new t({code:"template_spec_missing",message:`${Me(e)} has no ${Fe}.`,hint:`A template is an agent directory with a ${Fe} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return oi(mn(s,"utf8"),`${Me(e)}/${Fe}`)}function dt(e,s=""){let r=[];for(let i of Jr(z(e,s)).sort()){let n=s===""?i:`${s}/${i}`;if(n===Fe)continue;let a=z(e,n),l=ot(a);if(l.isSymbolicLink())throw new t({code:"template_symlink",message:`${n} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:n});if(l.isDirectory()){r.push(...dt(e,n));continue}let c=mn(a);if(c.includes(0))throw new t({code:"template_binary_file",message:`${n} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:n});r.push({relPath:n,contents:c.toString("utf8")})}return r}function eo(e){if(!Yr.test(e.template))throw tt(e.template,e.templatesDir);let s=z(e.templatesDir,e.template);if(!xe(s)||!ot(s).isDirectory())throw tt(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new t({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=nA(r),n=z(e.agentDirBase,i);if(xe(n))throw new t({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Sr({spec:pn(s),files:dt(s),id:i,name:r,vars:e.vars}),l=z(zr(e.agentDirBase),`.${Me(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);nt(l,{recursive:!0});try{Ae(l,a.files),so(l,{template:e.template,name:r,vars:to(pn(s),e.vars),files:Qa(a.files)});let c=z(l,"agent.yaml");for(let[m,p]of Object.entries(a.env))Ke(c,m,p);let f=a.files.find((m)=>m.relPath==="agent.yaml"),g={};for(let m of Ht(f?.contents??""))if(a.env[m.name]===void 0)g[m.name]="(pending)";We(c,g),nt(e.agentDirBase,{recursive:!0}),Ya(l,n)}catch(c){throw Xr(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:n,manifestPath:z(n,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function tt(e,s){let r=at(s).map((i)=>i.name);return new t({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:r.length===0?`This server has no templates. An operator adds one as a directory under ${s}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var no=".template.json";function dn(e){return za("sha256").update(e).digest("hex")}function Qa(e){return Object.fromEntries(e.map((s)=>[s.relPath,dn(s.contents)]))}function to(e,s){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(s).filter(([i])=>!r.has(i)))}function so(e,s){Ue(z(e,no),`${JSON.stringify({version:1,...s},null,2)}
261
- `,{mode:384})}function oo(e){let s=z(e.agentDir,no);if(!xe(s))throw new t({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0-pilot.5 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(mn(s,"utf8")),i=z(e.templatesDir,r.template);if(!xe(i))throw tt(r.template,e.templatesDir);let n=pn(i);for(let p of Object.keys(e.vars)){let h=n.vars.find((w)=>w.name===p);if(h?.secret!==void 0)throw new t({code:"template_var_secret",message:`"${p}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${h.secret}.`,field:`vars.${p}`})}let a={...r.vars,...e.vars},l=Sr({spec:n,files:dt(i),id:Me(e.agentDir),name:r.name,vars:{...Object.fromEntries(n.vars.filter((p)=>p.secret!==void 0&&p.required).map((p)=>[p.name,"(in .env)"])),...a}}),c=[],f=[],g=[],m={...r.files};try{for(let p of l.files){let h=z(e.agentDir,p.relPath),w=r.files[p.relPath];if(!xe(h)){if(w!==void 0){g.push({file:p.relPath,reason:"removed"});continue}nt(zr(h),{recursive:!0}),Ue(h,p.contents),c.push({path:h,before:void 0}),m[p.relPath]=dn(p.contents),f.push(p.relPath);continue}let S=mn(h,"utf8");if(Za(p.relPath,S)){g.push({file:p.relPath,reason:"memory"});continue}if(w===void 0||dn(S)!==w){g.push({file:p.relPath,reason:"edited"});continue}if(S===p.contents)continue;Ue(h,p.contents),c.push({path:h,before:S}),m[p.relPath]=dn(p.contents),f.push(p.relPath)}so(e.agentDir,{template:r.template,name:r.name,vars:to(n,a),files:m})}catch(p){throw Vr(c),p}return{rendered:f,skipped:g,undo:()=>{Vr(c),Ue(s,`${JSON.stringify(r,null,2)}
262
- `,{mode:384})}}}function Vr(e){for(let s of e)if(s.before===void 0)Xr(s.path,{force:!0});else Ue(s.path,s.before)}function Za(e,s){if(Me(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return Ft(e,s).frontmatter.eviction==="oldest"}catch{return!1}}function td(){return Ut.shape.server.parse({})}async function uo(e){let s=R(e.manifestPaths),r=sd(s),i=e.store??F(),n=await es(e.manifestPaths,s,i),a=n.filter((k)=>!k.enabled),l=n.filter((k)=>k.enabled),c=e.manifestPaths.length===0,f=[],g=[];for(let k of l)try{f.push({path:k.manifestPath,loaded:J(k.manifestPath,{env:s})})}catch(P){if(!c)throw P;g.push({path:k.manifestPath,detail:B(P)?P.message:String(P),...B(P)&&P.hint!==void 0?{hint:P.hint}:{}})}let m=f[0],p=m?.loaded,h=p?.manifest.server??td();for(let k of f.slice(1)){let P=k.loaded.manifest.server;for(let[O,q,De,Re]of[["server.port",h.port,P.port,e.port!==void 0],["server.host",h.host,P.host,e.host!==void 0],["server.tokenEnv",h.tokenEnv,P.tokenEnv,!1]]){if(Re||q===De)continue;throw new t({code:"serve_bind_conflict",message:`${m?.path??"the first manifest"} sets ${O} to ${String(q)} and ${k.path} sets it to ${String(De)}.`,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 w=e.port??h.port,S=e.port===void 0,E=e.host??h.host,b=p===void 0?s[h.tokenEnv]:p.env[h.tokenEnv],C=s[h.tokenEnv],M=f.every((k)=>Gt(nd(k.path),s)),v=b;if(M&&(C===void 0||C==="")){let k=ln(ne(s));if(k!==void 0)v=k;else if(b!==void 0&&b!=="")Zr(ne(s),b)}let x=s[`${A.envPrefix}SERVICE`]!==void 0,T=new QA({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)T.on("agent.channel.status",(k)=>{let P=k.data,O=P.input===void 0?"":P.input.kind==="pairing_code"?`
260
+ `),d;return qa(a),o}if(e.enable===void 0&&e.disable===void 0)Wa(n,i);return o}import{rmSync as ed}from"node:fs";import{dirname as nd}from"node:path";import{readFileSync as Ja}from"node:fs";var Xa="server.tokenEnv";function Zn(e){let s=Ja(e,"utf8"),r=kA(e),i=new Map,n=new Set(Ht(s).filter((a)=>a.path===Xa).map((a)=>a.name));for(let a of Ht(s)){if(n.has(a.name))continue;let l=i.get(a.name)??[];l.push(a.path),i.set(a.name,l)}return[...i].map(([a,l])=>({name:a,set:Xt(r,a),usedBy:l}))}function Br(e,s){let r=Zn(e).map((l)=>l.name);for(let[l,c]of Object.entries(s)){if(!r.includes(l))throw new t({code:"secret_not_referenced",message:`"${l}" is not a variable this agent's manifest reads.`,hint:r.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${r.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${l}`});if(c==="")throw new t({code:"secret_value_empty",message:`An empty value for ${l} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${l}`})}let i=R([e]),n=[],a=[];for(let[l,c]of Object.entries(s))if(Ke(e,l,c),n.push(l),Xt(i,l))a.push(l);return{written:n,shadowed:a}}import{createHash as za}from"node:crypto";import{existsSync as Re,lstatSync as ot,mkdirSync as nt,readdirSync as Jr,readFileSync as mn,renameSync as Ya,rmSync as Xr,writeFileSync as Fe}from"node:fs";import{basename as Ue,dirname as zr,join as z}from"node:path";var Ne="template.yaml",Yr=/^[a-z0-9][a-z0-9-]*$/;function at(e){let s;try{s=Jr(e)}catch{return[]}let r=[];for(let i of s.sort()){if(!Yr.test(i))continue;let n=z(e,i);if(!ot(n).isDirectory())continue;try{let a=pn(n);r.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((l)=>({name:l.name,...l.description===void 0?{}:{description:l.description},required:l.required,...l.default===void 0?{}:{default:l.default},secret:l.secret!==void 0}))})}catch(a){if(!B(a))throw a;r.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return r}function pn(e){let s=z(e,Ne);if(!Re(s))throw new t({code:"template_spec_missing",message:`${Ue(e)} has no ${Ne}.`,hint:`A template is an agent directory with a ${Ne} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return oi(mn(s,"utf8"),`${Ue(e)}/${Ne}`)}function dt(e,s=""){let r=[];for(let i of Jr(z(e,s)).sort()){let n=s===""?i:`${s}/${i}`;if(n===Ne)continue;let a=z(e,n),l=ot(a);if(l.isSymbolicLink())throw new t({code:"template_symlink",message:`${n} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:n});if(l.isDirectory()){r.push(...dt(e,n));continue}let c=mn(a);if(c.includes(0))throw new t({code:"template_binary_file",message:`${n} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:n});r.push({relPath:n,contents:c.toString("utf8")})}return r}function eo(e){if(!Yr.test(e.template))throw tt(e.template,e.templatesDir);let s=z(e.templatesDir,e.template);if(!Re(s)||!ot(s).isDirectory())throw tt(e.template,e.templatesDir);let r=e.name.trim();if(r==="")throw new t({code:"provision_name_required",message:"An agent made from a template needs a name.",hint:'Send { "template": "…", "name": "Acme store", "vars": {…} }. The id every route keys on is derived from the name, and a template can use it as {{agent.name}} and {{agent.id}}.',field:"name"});let i=nA(r),n=z(e.agentDirBase,i);if(Re(n))throw new t({code:"provision_agent_exists",message:`An agent directory named "${i}" already exists.`,hint:"The id is derived from the name, so pick a different name. Nothing is overwritten: replacing an agent's workspace is exactly the loss provisioning exists to prevent.",field:"name"});let a=Sr({spec:pn(s),files:dt(s),id:i,name:r,vars:e.vars}),l=z(zr(e.agentDirBase),`.${Ue(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);nt(l,{recursive:!0});try{Te(l,a.files),so(l,{template:e.template,name:r,vars:to(pn(s),e.vars),files:Qa(a.files)});let c=z(l,"agent.yaml");for(let[m,p]of Object.entries(a.env))Ke(c,m,p);let f=a.files.find((m)=>m.relPath==="agent.yaml"),g={};for(let m of Ht(f?.contents??""))if(a.env[m.name]===void 0)g[m.name]="(pending)";He(c,g),nt(e.agentDirBase,{recursive:!0}),Ya(l,n)}catch(c){throw Xr(l,{recursive:!0,force:!0}),c}return{agentId:i,dir:n,manifestPath:z(n,"agent.yaml"),files:[...a.files.map((c)=>c.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function tt(e,s){let r=at(s).map((i)=>i.name);return new t({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:r.length===0?`This server has no templates. An operator adds one as a directory under ${s}.`:`Templates here: ${r.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}var no=".template.json";function dn(e){return za("sha256").update(e).digest("hex")}function Qa(e){return Object.fromEntries(e.map((s)=>[s.relPath,dn(s.contents)]))}function to(e,s){let r=new Set(e.vars.filter((i)=>i.secret!==void 0).map((i)=>i.name));return Object.fromEntries(Object.entries(s).filter(([i])=>!r.has(i)))}function so(e,s){Fe(z(e,no),`${JSON.stringify({version:1,...s},null,2)}
261
+ `,{mode:384})}function oo(e){let s=z(e.agentDir,no);if(!Re(s))throw new t({code:"agent_not_from_template",message:"This agent has no record of the template it was made from.",hint:"Only an agent created with POST /v1/agents {template} on 0.2.0-pilot.5 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(mn(s,"utf8")),i=z(e.templatesDir,r.template);if(!Re(i))throw tt(r.template,e.templatesDir);let n=pn(i);for(let p of Object.keys(e.vars)){let h=n.vars.find((w)=>w.name===p);if(h?.secret!==void 0)throw new t({code:"template_var_secret",message:`"${p}" is a secret, and a secret is never rendered into a file.`,hint:`Set it with PUT /v1/agents/:id/secrets as ${h.secret}.`,field:`vars.${p}`})}let a={...r.vars,...e.vars},l=Sr({spec:n,files:dt(i),id:Ue(e.agentDir),name:r.name,vars:{...Object.fromEntries(n.vars.filter((p)=>p.secret!==void 0&&p.required).map((p)=>[p.name,"(in .env)"])),...a}}),c=[],f=[],g=[],m={...r.files};try{for(let p of l.files){let h=z(e.agentDir,p.relPath),w=r.files[p.relPath];if(!Re(h)){if(w!==void 0){g.push({file:p.relPath,reason:"removed"});continue}nt(zr(h),{recursive:!0}),Fe(h,p.contents),c.push({path:h,before:void 0}),m[p.relPath]=dn(p.contents),f.push(p.relPath);continue}let S=mn(h,"utf8");if(Za(p.relPath,S)){g.push({file:p.relPath,reason:"memory"});continue}if(w===void 0||dn(S)!==w){g.push({file:p.relPath,reason:"edited"});continue}if(S===p.contents)continue;Fe(h,p.contents),c.push({path:h,before:S}),m[p.relPath]=dn(p.contents),f.push(p.relPath)}so(e.agentDir,{template:r.template,name:r.name,vars:to(n,a),files:m})}catch(p){throw Vr(c),p}return{rendered:f,skipped:g,undo:()=>{Vr(c),Fe(s,`${JSON.stringify(r,null,2)}
262
+ `,{mode:384})}}}function Vr(e){for(let s of e)if(s.before===void 0)Xr(s.path,{force:!0});else Fe(s.path,s.before)}function Za(e,s){if(Ue(e)==="MEMORY.md")return!0;if(!e.endsWith(".md"))return!1;try{return Ft(e,s).frontmatter.eviction==="oldest"}catch{return!1}}function td(){return Ut.shape.server.parse({})}async function uo(e){let s=R(e.manifestPaths),r=sd(s),i=e.store??F(),n=await es(e.manifestPaths,s,i),a=n.filter((k)=>!k.enabled),l=n.filter((k)=>k.enabled),c=e.manifestPaths.length===0,f=[],g=[];for(let k of l)try{f.push({path:k.manifestPath,loaded:J(k.manifestPath,{env:s})})}catch(P){if(!c)throw P;g.push({path:k.manifestPath,detail:B(P)?P.message:String(P),...B(P)&&P.hint!==void 0?{hint:P.hint}:{}})}let m=f[0],p=m?.loaded,h=p?.manifest.server??td();for(let k of f.slice(1)){let P=k.loaded.manifest.server;for(let[O,q,Me,Ee]of[["server.port",h.port,P.port,e.port!==void 0],["server.host",h.host,P.host,e.host!==void 0],["server.tokenEnv",h.tokenEnv,P.tokenEnv,!1]]){if(Ee||q===Me)continue;throw new t({code:"serve_bind_conflict",message:`${m?.path??"the first manifest"} sets ${O} to ${String(q)} and ${k.path} sets it to ${String(Me)}.`,hint:"One process binds one socket with one token, so these have to agree. Make them match, or run the disagreeing agent in its own process — a second `serve` on its own port.",field:O})}}let w=e.port??h.port,S=e.port===void 0,E=e.host??h.host,b=p===void 0?s[h.tokenEnv]:p.env[h.tokenEnv],C=s[h.tokenEnv],M=f.every((k)=>Gt(nd(k.path),s)),v=b;if(M&&(C===void 0||C==="")){let k=ln(ne(s));if(k!==void 0)v=k;else if(b!==void 0&&b!=="")Zr(ne(s),b)}let x=s[`${A.envPrefix}SERVICE`]!==void 0,T=new yA({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)T.on("agent.channel.status",(k)=>{let P=k.data,O=P.input===void 0?"":P.input.kind==="pairing_code"?`
263
263
 
264
264
  ${P.input.payload}
265
265
  ${P.input.expiresAt===void 0?"":`
@@ -269,11 +269,11 @@ ${P.input.expiresAt===void 0?"":`
269
269
  `)}),T.on("error",(k)=>{let P=k.data,O=k.sessionKey===void 0?"":` [${k.sessionKey}]`;process.stderr.write(` turn failed${O}: ${P.code}: ${P.message}
270
270
  hint: ${P.hint}
271
271
  `)}),T.on("agent.channel.rejected",(k)=>{let P=k.data;process.stdout.write(` ${P.channelId}: ${P.reason} — ${P.detail}
272
- `)});let N=Ur(),L=(k)=>({agents:k,approve:N.approver,env:s,bus:T,toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),I;try{I=await Ie.create(L(f.map((k)=>k.path)))}catch(k){if(!c||f.length===0)throw k;let P=[];for(let O of f)try{await(await Ie.create({...L([O.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),P.push(O)}catch(q){g.push({path:O.path,detail:B(q)?q.message:String(q),...B(q)&&q.hint!==void 0?{hint:q.hint}:{}})}if(P.length===f.length)throw k;f.splice(0,f.length,...P),I=await Ie.create(L(P.map((O)=>O.path)))}gs();let H=rd(),he=await I.store.operatorKeys.liveCount(),re=he===0||e.claim===!0?qi():void 0,W,Ee=[];try{W=await id(w,S,(k)=>(Ee.push(k),zi({runtime:I,host:E,port:k,approvals:N,allowedOrigins:h.allowedOrigins,allowedHosts:h.allowedHosts,resolveAgent:(P)=>Vn(P,s),provision:{steps:()=>Ct({agentDirBase:ne(s)}),create:(P)=>jt({answers:P,defaults:{agentDirBase:ne(s)}}),templates:()=>at(yr(s)),createFromTemplate:(P)=>eo({...P,templatesDir:yr(s),agentDirBase:ne(s)}),rerender:(P)=>oo({...P,templatesDir:yr(s)})},secrets:{status:Zn,write:Br},remover:dd(s),home:Se(s),channels:{setEnabled:Hn,setCredential:Kn,unpair:Yn},...re===void 0?{}:{claim:re},...v===void 0||v===""?{}:{token:v}})))}catch(k){if(await I.stop("server failed to bind"),B(k))throw k;let P=Ee.length>1?` — also tried ${Ee.slice(1).join(", ")}`:"";throw new t({code:"server_bind_failed",message:`Could not bind ${E}:${w}${P}: ${k instanceof Error?k.message:String(k)}`,hint:S?`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 Ao=I.owned.length===0&&await As(I.store.leases,{runtimeId:I.runtimeId,mode:x?"daemon":"terminal"});await I.publishAddress(W.url);let ae=I.list(),ut=ae[0];if(ut!==void 0)process.title=ae.length===1?`${A.slug} ${ut.id}`:`${A.slug} ${ae.length} agents`;for(let k of ae)k.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:W.url,websocket:W.websocket,authenticated:v!==void 0&&v!=="",keys:he,...re===void 0?{}:{claim:re.token},agents:ae.map((k)=>({id:k.id,channels:I.channels.statusOf(k.id)})),declined:I.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:g.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
272
+ `)});let N=Ur(),L=(k)=>({agents:k,approve:N.approver,env:s,bus:T,toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,startChannels:!0,startSchedules:!0,store:i,mode:x?"daemon":"terminal"}),I;try{I=await Ie.create(L(f.map((k)=>k.path)))}catch(k){if(!c||f.length===0)throw k;let P=[];for(let O of f)try{await(await Ie.create({...L([O.path]),store:":memory:",startChannels:!1,startSchedules:!1})).stop(),P.push(O)}catch(q){g.push({path:O.path,detail:B(q)?q.message:String(q),...B(q)&&q.hint!==void 0?{hint:q.hint}:{}})}if(P.length===f.length)throw k;f.splice(0,f.length,...P),I=await Ie.create(L(P.map((O)=>O.path)))}gs();let H=rd(),he=await I.store.operatorKeys.liveCount(),re=he===0||e.claim===!0?qi():void 0,W,ke=[];try{W=await id(w,S,(k)=>(ke.push(k),zi({runtime:I,host:E,port:k,approvals:N,allowedOrigins:h.allowedOrigins,allowedHosts:h.allowedHosts,resolveAgent:(P)=>Vn(P,s),provision:{steps:()=>Ct({agentDirBase:ne(s)}),create:(P)=>jt({answers:P,defaults:{agentDirBase:ne(s)}}),templates:()=>at(Qr(s)),createFromTemplate:(P)=>eo({...P,templatesDir:Qr(s),agentDirBase:ne(s)}),rerender:(P)=>oo({...P,templatesDir:Qr(s)})},secrets:{status:Zn,write:Br},remover:dd(s),home:Se(s),channels:{setEnabled:Hn,setCredential:Kn,unpair:Yn},...re===void 0?{}:{claim:re},...v===void 0||v===""?{}:{token:v}})))}catch(k){if(await I.stop("server failed to bind"),B(k))throw k;let P=ke.length>1?` — also tried ${ke.slice(1).join(", ")}`:"";throw new t({code:"server_bind_failed",message:`Could not bind ${E}:${w}${P}: ${k instanceof Error?k.message:String(k)}`,hint:S?`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 Ao=I.owned.length===0&&await As(I.store.leases,{runtimeId:I.runtimeId,mode:x?"daemon":"terminal"});await I.publishAddress(W.url);let ae=I.list(),ut=ae[0];if(ut!==void 0)process.title=ae.length===1?`${A.slug} ${ut.id}`:`${A.slug} ${ae.length} agents`;for(let k of ae)k.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:W.url,websocket:W.websocket,authenticated:v!==void 0&&v!=="",keys:he,...re===void 0?{}:{claim:re.token},agents:ae.map((k)=>({id:k.id,channels:I.channels.statusOf(k.id)})),declined:I.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:g.map((k)=>({path:k.path,detail:k.detail,...k.hint===void 0?{}:{hint:k.hint}}))})}
273
273
  `);else{let k=`http://${An(E)}:${W.port}`,P=k===W.url?"":` (bound ${E} — every interface)`;if(process.stdout.write(`${A.name} serving on ${k}${P}
274
274
  `),W.port!==w)process.stdout.write(` moved from ${w} — something else is on it. \`--port ${w}\` would refuse instead of moving.
275
275
  `);process.stdout.write(` web UI ${k}/ · API reference ${k}/docs
276
- `);for(let O of ae){let q=I.channels.statusOf(O.id),De=q.length===0?"no channels":q.map((Te)=>`${Te.id} (${Te.type}${Te.status==="error"?", BROKEN":""})`).join(", "),Re=O.manifest.schedules.filter((Te)=>Te.enabled),No=O.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${O.manifest.schedules.length>Re.length?` (+${O.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${O.id} — ${De}${No}
276
+ `);for(let O of ae){let q=I.channels.statusOf(O.id),Me=q.length===0?"no channels":q.map((xe)=>`${xe.id} (${xe.type}${xe.status==="error"?", BROKEN":""})`).join(", "),Ee=O.manifest.schedules.filter((xe)=>xe.enabled),No=O.manifest.schedules.length===0?"":`, ${Ee.length} schedule${Ee.length===1?"":"s"}${O.manifest.schedules.length>Ee.length?` (+${O.manifest.schedules.length-Ee.length} disabled)`:""}`;process.stdout.write(` ${O.id} — ${Me}${No}
277
277
  `)}for(let O of a)process.stdout.write(` ${O.agentId} — stopped${O.reason===void 0?"":` (${O.reason})`}, \`${A.slug} start ${O.agentId}\`
278
278
  `);for(let O of g)if(process.stdout.write(` ${O.path} — NOT served: ${O.detail}
279
279
  `),O.hint!==void 0)process.stdout.write(` hint: ${O.hint}
@@ -329,15 +329,15 @@ The scaffold copies ${r}'s headings and its <rules> blocks verbatim, and leaves
329
329
 
330
330
  \`sources add <name> <url>\` to add one, or \`sources add ${Mt[0]?.name??"anthropic"} ${Mt[0]?.url??""}\` to put a built-in back.
331
331
  `),o;process.stdout.write(_("sources",!0));for(let i of r)process.stdout.write(`
332
- ${y(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
333
- `),process.stdout.write(Q(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(`
332
+ ${Q(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
333
+ `),process.stdout.write(y(u([{label:"url",value:i.url},...i.path===void 0?[]:[{label:"path",value:i.path}],...i.ref===void 0?[]:[{label:"branch",value:i.ref}],{label:"cached",value:i.cached?`${i.skills??"?"} skills at ${i.commit??"?"}, fetched ${i.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
334
334
  ${_("registry")}
335
- ${Q(Wn(e.env))}
335
+ ${y(Wn(e.env))}
336
336
  `),o}function xd(e){let[s,r]=e.rest;if(s===void 0)throw new t({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let i=r!==void 0,n=i?r:s,a=Ar(n),l=i?s:Td(a.url);if(!Tt(l))throw new t({code:"sources_name_invalid",message:`${JSON.stringify(l)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let c=Le(e.env).find((p)=>p.name===l);if(c!==void 0&&!i)throw new t({code:"sources_name_taken",message:`${l} is already a source, pointing at ${c.url}`,hint:`Give this one its own name: \`sources add <name> ${n}\`.`});let f=e.path??a.path,g=e.ref??a.ref,m={name:l,url:a.url,...f===void 0?{}:{path:f},...g===void 0?{}:{ref:g}};if(ts(m,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:m},null,2)}
337
337
  `),o;return process.stdout.write(`${u([{label:c===void 0?"added":"replaced",value:l},{label:"url",value:m.url},...m.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:m.path}],...m.ref===void 0?[]:[{label:"branch",value:m.ref}]])}
338
338
  `),process.stdout.write(`${_("next")}
339
- ${y(`sources update ${l}`)}
340
- ${y("sources search <what you need>")}
339
+ ${Q(`sources update ${l}`)}
340
+ ${Q("sources search <what you need>")}
341
341
  `),o}function Td(e){let s=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(s[s.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Id(e){let s=e.rest[0];if(s===void 0)throw new t({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let r=Le(e.env).map((n)=>n.name);if(!ns(s,e.env)){let n=Y(s,r);throw new t({code:"sources_unknown",message:`no source called ${s}`,hint:n===void 0?`Configured: ${r.join(", ")||"none"}.`:`Did you mean ${n}?`})}let i=Mt.some((n)=>n.name===s);return process.stdout.write(`removed ${s}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
342
342
  `),process.stdout.write(`
343
343
  The cached copy is left on disk; nothing already installed into an agent is touched.
@@ -346,15 +346,15 @@ ${y("sources search <what you need>")}
346
346
  \`sources add <url>\` to add one.
347
347
  `),o;let i=[],n=[];for(let a of r){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let l=await Rt(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:l.commit,skills:l.skills}),e.json!==!0)process.stdout.write(`${l.skills} skills at ${l.commit}${l.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
348
348
  `)}catch(l){let c=l instanceof Error?l.message:String(l);if(n.push({name:a.name,reason:c}),e.json!==!0)process.stdout.write(`failed
349
- `);if(e.json!==!0&&B(l))process.stdout.write(`${Q(l.message)}
350
- ${Q(l.hint,4)}
349
+ `);if(e.json!==!0&&B(l))process.stdout.write(`${y(l.message)}
350
+ ${y(l.hint,4)}
351
351
  `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:n},null,2)}
352
352
  `);return i.length===0?d:o}async function Od(e){let s=e.rest.join(" ").trim(),r=Le(e.env);if(r.length===0)return process.stdout.write(`no sources configured
353
353
 
354
354
  \`sources add <url>\` to add one.
355
355
  `),d;let i=r.filter((c)=>!gA(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 f=await Rt(c,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${f.skills} skills
356
356
  `)}catch(f){if(e.json!==!0){if(process.stdout.write(`failed
357
- `),B(f))process.stdout.write(`${Q(f.message)}
357
+ `),B(f))process.stdout.write(`${y(f.message)}
358
358
  `)}}}let n=r.flatMap((c)=>GA(c,e.env));if(n.length===0)return process.stdout.write(`
359
359
  nothing to search — no source has been fetched successfully
360
360
 
@@ -366,13 +366,13 @@ nothing in ${n.length} skills across ${r.length} sources matches ${JSON.stringif
366
366
  `),o;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:s,searched:n.length,results:a.map((c)=>({source:c.source,skill:c.skill,description:c.description,tokens:c.tokens,scripts:c.scripts.length,repoPath:c.repoPath,...c.problem===void 0?{}:{problem:c.problem}}))},null,2)}
367
367
  `),o;let l=a.slice(0,Rd);process.stdout.write(`
368
368
  ${_(s.length===0?`${n.length} skills`:`${a.length} of ${n.length} skills match ${JSON.stringify(s)}`,!0)}
369
- `);for(let c of l){process.stdout.write(`${y(`${c.source}/${c.skill}`)} ${c.tokens} tokens${c.scripts.length===0?"":`, ${c.scripts.length} runnable file${c.scripts.length===1?"":"s"}`}${c.problem===void 0?"":" — will not load"}
370
- `);let f=c.problem??c.description;process.stdout.write(`${Q(f.length>160?`${f.slice(0,157)}…`:f,4)}
369
+ `);for(let c of l){process.stdout.write(`${Q(`${c.source}/${c.skill}`)} ${c.tokens} tokens${c.scripts.length===0?"":`, ${c.scripts.length} runnable file${c.scripts.length===1?"":"s"}`}${c.problem===void 0?"":" — will not load"}
370
+ `);let f=c.problem??c.description;process.stdout.write(`${y(f.length>160?`${f.slice(0,157)}…`:f,4)}
371
371
  `)}if(a.length>l.length)process.stdout.write(`
372
- ${Q(`… and ${a.length-l.length} more; narrow the query or use --json`)}
372
+ ${y(`… and ${a.length-l.length} more; narrow the query or use --json`)}
373
373
  `);return process.stdout.write(`
374
374
  ${_("install")}
375
- ${Q(`skills install <agent> ${l[0]?.source}/${l[0]?.skill}`)}
375
+ ${y(`skills install <agent> ${l[0]?.source}/${l[0]?.skill}`)}
376
376
  `),o}function _d(e,s){let r=new Map,i=s.map((n)=>{let a=`${n.source}/${n.skill}`;return r.set(a,n),{name:a,dir:n.dir,tokens:n.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:n.description,metadata:{}}}});return Kt(e,i).filter((n)=>n.score>0).map((n)=>r.get(n.skill.name)).filter((n)=>n!==void 0)}async function vo(e){let s=Cd(e.manifestPath),r=await er(s,e.store),i=[];if(r?.enabled===!0)i.push("was already switched on");await $o(s,!0,void 0,e.store);let n=await je(e.store),a=!1;if(n===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(n.baseUrl===void 0)i.push(`pid ${n.pid} is a ${n.mode} session, which serves no HTTP to adopt into`);else{let l=await aA(n,`/v1/agents/${encodeURIComponent(s)}/start`,{},e.manifestPath);if(l.ok)a=!0,i.push(`adopted by pid ${n.pid}, live now`);else if(l.status===501)i.push(`pid ${n.pid} cannot look up manifests — restart it to pick this up`);else if(l.status===401)i.push(`pid ${n.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${n.pid} could not adopt it${l.detail===void 0?"":`: ${l.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:s,enabled:!0,running:a,...n===void 0?{}:{pid:n.pid,mode:n.mode},note:i.join(" · ")}]},null,2)}
377
377
  `);else if(process.stdout.write(`${u([{label:s,value:a?"running":"switched on",note:i.join(" · ")}])}
378
378
  `),!a&&n!==void 0&&n.baseUrl!==void 0)process.stdout.write(`
@@ -381,39 +381,39 @@ Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
381
381
  `),o;let i=await LA({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${u(wn(s))}
382
382
  `);let n=[];for(let[a,l]of r)for(let c of l.values())n.push({label:`${a} / ${c.id}`,value:c.status,note:c.input!==void 0?`${c.detail??"enter this code"}: ${c.input.payload}`:c.detail??""});if(n.length>0)process.stdout.write(`
383
383
  ${u(n)}
384
- `);return i}import{copyFileSync as Nd,existsSync as jd,mkdirSync as Fd,readFileSync as Ld,writeFileSync as Ud}from"node:fs";import{dirname as Kd,join as So}from"node:path";async function Eo(e){let s=e.env??R([]),r=e.home??s.HOME??"",i=Xe(s),n=ze(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:n?.how??"unknown",configPath:n?.configPath===void 0?void 0:So(r,n.configPath),line:n?.line,steps:n?.steps},null,2)}
384
+ `);return i}import{copyFileSync as Nd,existsSync as jd,mkdirSync as Fd,readFileSync as Ld,writeFileSync as Ud}from"node:fs";import{dirname as Kd,join as So}from"node:path";async function Eo(e){let s=e.env??R([]),r=e.home??s.HOME??"",i=Be(s),n=Xe(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:n?.how??"unknown",configPath:n?.configPath===void 0?void 0:So(r,n.configPath),line:n?.line,steps:n?.steps},null,2)}
385
385
  `),n===void 0?d:o;if(process.stdout.write(`${_("shift+enter",!0)}
386
- ${Q("⌥ 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.")}
386
+ ${y("⌥ or ⇧ ⏎ already puts a new line in a message, everywhere, with no setup. This command is for shift+⏎, which a terminal can only send once it has been given a key binding.")}
387
387
  `),n===void 0)return process.stdout.write(`
388
388
  ${_("this terminal was not recognised")}
389
- ${Q(`TERM_PROGRAM=${s.TERM_PROGRAM??"(unset)"} TERM=${s.TERM??"(unset)"}`)}
390
- ${Q(`known: ${Vt().map((a)=>a.name).join(", ")}`)}
391
- ${y("⌥⏎ works here regardless — nothing needs configuring for it")}
389
+ ${y(`TERM_PROGRAM=${s.TERM_PROGRAM??"(unset)"} TERM=${s.TERM??"(unset)"}`)}
390
+ ${y(`known: ${Vt().map((a)=>a.name).join(", ")}`)}
391
+ ${Q("⌥⏎ works here regardless — nothing needs configuring for it")}
392
392
  `),d;if(process.stdout.write(`
393
393
  ${_(n.name)}
394
- `),n.how!=="write"){process.stdout.write(`${Q(n.how==="unverified"?`no verified recipe for this one — ${n.reason??"nobody has checked it"}`:`this one has to be done by hand — ${n.reason??"its settings are not a text file"}`)}
394
+ `),n.how!=="write"){process.stdout.write(`${y(n.how==="unverified"?`no verified recipe for this one — ${n.reason??"nobody has checked it"}`:`this one has to be done by hand — ${n.reason??"its settings are not a text file"}`)}
395
395
 
396
- `);for(let[a,l]of(n.steps??[]).entries())process.stdout.write(`${Q(`${a+1}. ${l}`)}
396
+ `);for(let[a,l]of(n.steps??[]).entries())process.stdout.write(`${y(`${a+1}. ${l}`)}
397
397
  `);return process.stdout.write(n.how==="unverified"?`
398
- ${y("⌥⏎ works here today — nothing has to be configured for it")}
398
+ ${Q("⌥⏎ works here today — nothing has to be configured for it")}
399
399
  `:`
400
- ${y("then restart the terminal and press shift+⏎ in a session to check it")}
401
- `),o}return await Md(n,{...e,env:s,home:r})}async function Md(e,s){let r=So(s.home,e.configPath??""),i=jd(r)?Ld(r,"utf8"):"";if(Jt(i,e))return process.stdout.write(`${Q("already configured — a binding for shift+enter is present")}
402
- ${Q($A(r,s.home),4)}
403
- `),o;let n=zt(i,e);if(n===void 0)return process.stdout.write(`${Q("this file is not in a shape this command can edit safely:")}
404
- ${Q($A(r,s.home),4)}
405
- ${y("add the line below by hand:")}
406
- ${Q(e.line??"",4)}
400
+ ${Q("then restart the terminal and press shift+⏎ in a session to check it")}
401
+ `),o}return await Md(n,{...e,env:s,home:r})}async function Md(e,s){let r=So(s.home,e.configPath??""),i=jd(r)?Ld(r,"utf8"):"";if(Jt(i,e))return process.stdout.write(`${y("already configured — a binding for shift+enter is present")}
402
+ ${y($A(r,s.home),4)}
403
+ `),o;let n=zt(i,e);if(n===void 0)return process.stdout.write(`${y("this file is not in a shape this command can edit safely:")}
404
+ ${y($A(r,s.home),4)}
405
+ ${Q("add the line below by hand:")}
406
+ ${y(e.line??"",4)}
407
407
  `),d;if(process.stdout.write(`${u([{label:"file",value:$A(r,s.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
408
408
  `),s.dryRun===!0)return process.stdout.write(`
409
- ${y("--dry-run: nothing was written")}
409
+ ${Q("--dry-run: nothing was written")}
410
410
  `),o;if(s.yes!==!0){if(!(s.confirm===void 0?!1:await s.confirm("write this change?")))return process.stdout.write(`
411
- ${y("nothing was written")}
411
+ ${Q("nothing was written")}
412
412
  `),o}try{if(Fd(Kd(r),{recursive:!0}),i!=="")Nd(r,`${r}.${A.slug}-backup`);Ud(r,n,"utf8")}catch(a){return process.stderr.write(`could not write ${r}: ${a instanceof Error?a.message:String(a)}
413
413
  `),d}return process.stdout.write(`
414
414
  ${_("done")}
415
- ${i===""?"":`${Q(`a copy of the old file is at ${$A(`${r}.${A.slug}-backup`,s.home)}`)}
416
- `}${y("restart the terminal, then press shift+⏎ in a session to check it")}
415
+ ${i===""?"":`${y(`a copy of the old file is at ${$A(`${r}.${A.slug}-backup`,s.home)}`)}
416
+ `}${Q("restart the terminal, then press shift+⏎ in a session to check it")}
417
417
  `),o}async function Ro(e){return e.warm===!0?await Dd(e):await Hd(e)}async function Dd(e){let s=J(e.manifestPath,{env:R([e.manifestPath])}),r=uA(s.manifest.tools).selections,i=s.manifest.tools.pinned;if(r.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
418
418
  `),o;if(i.length===0)return process.stdout.write(`nothing to warm — ${r.map((c)=>c.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
419
419
  `),o;let n=[],a=new Set;for(let c of r){let f=te[c.id];if(f===void 0)return d;let g;try{let m=f({dir:s.dir,env:s.env,config:c.config,agentId:s.manifest.id});if(m.refresh===void 0){for(let p of await m.resolve(i))a.add(p.spec.slug);if(e.json!==!0)process.stdout.write(`${c.id}: nothing to warm — it resolves without a cache.
@@ -426,8 +426,8 @@ ${i===""?"":`${Q(`a copy of the old file is at ${$A(`${r}.${A.slug}-backup`,s.ho
426
426
  `)}let l=i.filter((c)=>!a.has(c));for(let c of l)process.stdout.write(` missing: ${c} — no configured provider has a tool with that slug
427
427
  `);return l.length>0?d:o}async function Hd(e){let s=await Ie.create({agents:[e.manifestPath],toolProviders:te,modelTransports:me,mediaProviders:ce,builtInPlugins:fe,pluginRoot:oe(),scriptRunner:le(),channels:se,env:R([e.manifestPath])});try{let r=s.list()[0];if(r===void 0)throw Error("The manifest produced no agent.");let i=qo(r);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
428
428
  `:`${St(i)}
429
- `),o}finally{await s.stop("cli-exit")}}import{dirname as Po,isAbsolute as Gd,resolve as hn}from"node:path";async function xo(e){try{let s=G(e.manifestPath),r=await fo({refs:s.plugins??[],agentId:s.id??e.manifestPath,paths:{workspace:Po(hn(e.manifestPath)),state:Po(hn(e.manifestPath)),manifest:hn(e.manifestPath)},env:R([e.manifestPath]),bus:new QA({runtimeId:"validate"}),builtIn:fe,pluginRoot:oe(),base:{toolProviders:te,modelTransports:me,mediaProviders:ce,channels:se}}),i=J(e.manifestPath,{env:R([e.manifestPath])}),{manifest:n}=i,a=pe(n.model.main.id,n.model.main.capabilities),{workspace:l,warnings:c}=lt(i,a.promptStyle),f=ho(Bo(i,{channels:r.channels})),g=await un(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let v of g.providers)await v.stop?.();let m=go(n,{env:i.env,transports:new Map([...st,...Object.entries(r.modelTransports)])});xt(n,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let p=JA(l,n.context.rules);if(p!==void 0&&n.context.rules.onExceed==="fail")throw p;let h=[...c,...r.failed,...g.warnings,...g.registry.warnings,...f,...Io(n),...lo(n),...p===void 0?[]:[p.toDetail()]],w=n.knowledge===void 0?void 0:po({dir:Gd(n.knowledge.dir)?n.knowledge.dir:hn(i.dir,n.knowledge.dir),maxActive:n.knowledge.maxActive,budget:n.knowledge.budget,style:a.promptStyle}),S=["static","volatile","reminder"].map((v)=>{let x=l.files.filter((T)=>T.tier===v).map((T)=>T.name);if(x.length===0)return;return`${v}=${x.join(",")} (${l.tokens[v]}/${n.context.budgets[v]})`}).filter((v)=>v!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:n.id,model:n.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((v)=>({name:v.name,tier:v.tier,editable:v.editable,tokens:v.tokens,budget:v.budget})),tokens:l.tokens},knowledge:w===void 0?[]:w.entries.map((v)=>({name:v.name,keywords:v.keywords,tokens:v.tokens})),warnings:h},null,2)}
430
- `),o;let E=yA(n),b=E.map((v)=>v.role===v.configuredAs?`${v.role}=${v.modelId}`:`${v.role}=→main`).join(" "),C=E.filter((v)=>v.role===v.configuredAs),M=Yi({manifestPath:e.manifestPath,rawModelId:s.modelId,apiKeyEnv:n.model.main.apiKeyEnv}).flatMap((v)=>{let x=Ki(v.origin);return x===void 0?[]:[` env ${v.variable} — ${x}
429
+ `),o}finally{await s.stop("cli-exit")}}import{dirname as Po,isAbsolute as Gd,resolve as hn}from"node:path";async function xo(e){try{let s=G(e.manifestPath),r=await fo({refs:s.plugins??[],agentId:s.id??e.manifestPath,paths:{workspace:Po(hn(e.manifestPath)),state:Po(hn(e.manifestPath)),manifest:hn(e.manifestPath)},env:R([e.manifestPath]),bus:new yA({runtimeId:"validate"}),builtIn:fe,pluginRoot:oe(),base:{toolProviders:te,modelTransports:me,mediaProviders:ce,channels:se}}),i=J(e.manifestPath,{env:R([e.manifestPath])}),{manifest:n}=i,a=pe(n.model.main.id,n.model.main.capabilities),{workspace:l,warnings:c}=lt(i,a.promptStyle),f=ho(Bo(i,{channels:r.channels})),g=await un(i,{toolProviders:r.toolProviders,modelTransports:r.modelTransports,mediaProviders:r.mediaProviders,channels:r.channels,scriptRunner:r.scriptRunner,middleware:r.middleware});for(let v of g.providers)await v.stop?.();let m=go(n,{env:i.env,transports:new Map([...st,...Object.entries(r.modelTransports)])});xt(n,{env:i.env,providers:new Map(Object.entries(r.mediaProviders))});let p=JA(l,n.context.rules);if(p!==void 0&&n.context.rules.onExceed==="fail")throw p;let h=[...c,...r.failed,...g.warnings,...g.registry.warnings,...f,...Io(n),...lo(n),...p===void 0?[]:[p.toDetail()]],w=n.knowledge===void 0?void 0:po({dir:Gd(n.knowledge.dir)?n.knowledge.dir:hn(i.dir,n.knowledge.dir),maxActive:n.knowledge.maxActive,budget:n.knowledge.budget,style:a.promptStyle}),S=["static","volatile","reminder"].map((v)=>{let x=l.files.filter((T)=>T.tier===v).map((T)=>T.name);if(x.length===0)return;return`${v}=${x.join(",")} (${l.tokens[v]}/${n.context.budgets[v]})`}).filter((v)=>v!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:n.id,model:n.model.main.id,window:i.window,capabilities:a,workspace:{files:l.files.map((v)=>({name:v.name,tier:v.tier,editable:v.editable,tokens:v.tokens,budget:v.budget})),tokens:l.tokens},knowledge:w===void 0?[]:w.entries.map((v)=>({name:v.name,keywords:v.keywords,tokens:v.tokens})),warnings:h},null,2)}
430
+ `),o;let E=QA(n),b=E.map((v)=>v.role===v.configuredAs?`${v.role}=${v.modelId}`:`${v.role}=→main`).join(" "),C=E.filter((v)=>v.role===v.configuredAs),M=Yi({manifestPath:e.manifestPath,rawModelId:s.modelId,apiKeyEnv:n.model.main.apiKeyEnv}).flatMap((v)=>{let x=Ki(v.origin);return x===void 0?[]:[` env ${v.variable} — ${x}
431
431
  `]}).join("");return process.stdout.write(`ok ${i.path}
432
432
  id ${n.id}${n.name===void 0?"":` (${n.name})`}
433
433
  models ${b}
@@ -467,7 +467,7 @@ ${l.length} finding(s)
467
467
  `),KA().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
468
468
  `)}else process.stderr.write(`${String(e)}
469
469
  `);return d}async function Bd(e){let s=Zi(e);switch(s.kind){case"version":return process.stdout.write(`${j}
470
- `),o;case"help":return process.stdout.write(_n(s.command)),o;case"usage":return process.stdout.write(_n()),d;case"command":break}let{command:r,positionals:i,flags:n}=s.parsed,a=i[0],l=()=>Ge(a),c=r.flags.some((m)=>m.name==="store")?n.str("store"):void 0,f=await zo({needsServer:r.needsServer,disabled:n.bool("no-bootstrap"),install:()=>Zo(),...c===void 0?{}:{store:c}}),g=wt(f);if(g!==void 0)process.stderr.write(g);switch(r.name){case"init":{let m=n.str("dir"),p=n.str("user"),h=n.str("name"),w=n.str("purpose"),S=n.str("preset"),E=n.str("model"),b=n.str("base-url"),C=n.str("api-key-env"),M=n.str("system"),v=n.str("web"),x=n.str("web-backend"),T=n.str("composio"),N=n.str("telegram"),L=n.str("telegram-allow"),I=n.str("whatsapp"),H=n.str("whatsapp-number"),he=n.str("server"),re=n.str("schedules"),W=n.str("skills"),Ee=n.str("daemon");return await Wt({...m===void 0?{}:{dir:m},...p===void 0?{}:{user:p},...h===void 0?{}:{name:h},...w===void 0?{}:{purpose:w},...S===void 0?{}:{preset:S},...E===void 0?{}:{model:E},...b===void 0?{}:{baseUrl:b},...C===void 0?{}:{apiKeyEnv:C},...M===void 0?{}:{system:M},...v===void 0?{}:{web:v},...x===void 0?{}:{webBackend:x},...T===void 0?{}:{composio:T},...N===void 0?{}:{telegram:N},...re===void 0?{}:{schedules:re},...L===void 0?{}:{telegramAllow:L},...I===void 0?{}:{whatsapp:I},...H===void 0?{}:{whatsappNumber:H},...he===void 0?{}:{server:he},...W===void 0?{}:{skills:W},...Ee===void 0?{}:{daemon:Ee},yes:n.bool("yes"),plain:n.bool("plain"),installServer:Zo})}case"run":{let m=n.str("session"),p=n.str("input"),h=n.str("store");return await Qn({...i[0]===void 0?{}:{manifestPath:l()},...m===void 0?{}:{sessionKey:m},continueSession:n.bool("continue"),...p===void 0?{}:{once:p},...h===void 0?{}:{store:h},ephemeral:n.bool("ephemeral"),quiet:n.bool("quiet"),showReasoning:n.bool("show-reasoning"),noReasoning:n.bool("no-reasoning"),...n.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:n.bool("plain")})}case"schedules":{let m=n.str("store"),p=n.str("id"),h=n.str("enable"),w=n.str("disable");return await qr({manifestPath:l(),...m===void 0?{}:{store:m},...p===void 0?{}:{id:p},...h===void 0?{}:{enable:h},...w===void 0?{}:{disable:w},recipients:n.bool("recipients"),json:n.bool("json")})}case"sessions":{let m=n.str("session"),p=n.str("store"),h=n.num("limit");return await mo({manifestPath:l(),...m===void 0?{}:{sessionKey:m},...p===void 0?{}:{store:p},...h===void 0?{}:{limit:h},json:n.bool("json"),clear:n.bool("clear"),turns:n.bool("turns")})}case"memory":{let m=n.num("limit"),p=n.str("store");return await ps({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...m===void 0?{}:{limit:m},...p===void 0?{}:{store:p},all:n.bool("all"),json:n.bool("json")})}case"config":{let{configCommand:m,readAction:p}=await import("./config-cba40q0x.js"),h=p(a,i[1]);return await m({action:h.action,...h.ref===void 0?{}:{ref:h.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...n.str("channel")===void 0?{}:{channel:n.str("channel")},remove:n.bool("remove"),yes:n.bool("yes"),...n.str("store")===void 0?{}:{store:n.str("store")}})}case"validate":return await xo({manifestPath:l(),json:n.bool("json")});case"workspace":return To({manifestPath:l(),json:n.bool("json"),strict:n.bool("strict")});case"soul":{let m=n.str("out");return yo({action:a,file:i[1],...m===void 0?{}:{out:m}})}case"skills":{if(i.length===0)return await rs({plain:n.bool("plain"),json:n.bool("json")});let m=i[2];return FA({action:a,manifestPath:Ge(i[1]??""),...m===void 0?{}:{name:m},json:n.bool("json"),strict:n.bool("strict")})}case"sources":{let m=n.str("path"),p=n.str("ref");return await bo({action:a,rest:i.slice(1),...m===void 0?{}:{path:m},...p===void 0?{}:{ref:p},json:n.bool("json")})}case"channels":{let m=$i("channels",a),p=m.ref??i[1]??"",{channelsCommand:h}=await import("./channels-473gvnrt.js");return await h({...m.action===void 0?{}:{action:m.action},manifestPath:Ge(p),...i[2]===void 0?{}:{channelId:i[2]},json:n.bool("json"),installServer:Zo})}case"plugins":{let m=n.str("ref"),p=n.str("name");return await Ws({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...m===void 0?{}:{ref:m},...p===void 0?{}:{name:p},json:n.bool("json")})}case"agents":{let m=n.str("store");return await pt({manifestPaths:i.map((p)=>Ge(p)),...m===void 0?{}:{store:m},json:n.bool("json")})}case"restart":{let m=n.str("store");return await kr({...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{store:m},json:n.bool("json")})}case"status":{let m=n.str("store");return await ko({...m===void 0?{}:{store:m},json:n.bool("json")})}case"logs":{let m=n.num("lines"),p=n.str("store");return await LA({action:"logs",...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),...p===void 0?{}:{store:p},json:n.bool("json")})}case"serve":{let m=n.num("port"),p=n.str("host"),h=n.str("store");return await uo({manifestPaths:i.map((w)=>Ge(w)),...m===void 0?{}:{port:m},...p===void 0?{}:{host:p},...h===void 0?{}:{store:h},claim:n.bool("claim"),json:n.bool("json")})}case"keys":return await Yt({noEnhancedKeys:n.bool("no-enhanced-keys")});case"terminal-setup":return await Eo({dryRun:n.bool("dry-run"),yes:n.bool("yes"),json:n.bool("json"),confirm:bt});case"remove":return await fr({...a===void 0?{}:{ref:a},dryRun:n.bool("dry-run"),filesOnly:n.bool("files-only"),prune:n.bool("prune"),all:n.bool("all"),yes:n.bool("yes"),json:n.bool("json"),...n.str("store")===void 0?{}:{store:n.str("store")},confirm:Ji});case"stop":{let m=n.str("reason");return await rn({...a===void 0?{}:{manifestPath:l()},dryRun:n.bool("dry-run"),...m===void 0?{}:{reason:m},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"start":return await vo({manifestPath:l(),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")});case"web":{let{webCommand:m}=await import("./web-v93ey21m.js");return await m({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:n.bool("no-open"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"credential":{let{credentialCommand:m}=await import("./credential-5g1zskdk.js");return await m({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...n.str("label")===void 0?{}:{label:n.str("label")},...n.str("agents")===void 0?{}:{agents:n.str("agents")},...n.str("sessions")===void 0?{}:{sessions:n.str("sessions")},...n.str("can")===void 0?{}:{can:n.str("can")},...n.str("expires")===void 0?{}:{expires:n.str("expires")},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"daemon":{let m=n.num("lines");return await LA({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),dryRun:n.bool("dry-run"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"model":{let m=n.num("price");return await Os({manifestPath:Ge(i[1]),window:n.bool("window"),...m===void 0?{}:{price:m},write:n.bool("write"),yes:n.bool("yes"),json:n.bool("json")})}case"tools":return await Ro({manifestPath:l(),warm:n.bool("warm"),json:n.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}us();cs();ds();await Bd(process.argv.slice(2)).catch(qd).then((e)=>rr(e));
470
+ `),o;case"help":return process.stdout.write(_n(s.command)),o;case"usage":return process.stdout.write(_n()),d;case"command":break}let{command:r,positionals:i,flags:n}=s.parsed,a=i[0],l=()=>Ge(a),c=r.flags.some((m)=>m.name==="store")?n.str("store"):void 0,f=await zo({needsServer:r.needsServer,disabled:n.bool("no-bootstrap"),install:()=>Zo(),...c===void 0?{}:{store:c}}),g=wt(f);if(g!==void 0)process.stderr.write(g);switch(r.name){case"init":{let m=n.str("dir"),p=n.str("user"),h=n.str("name"),w=n.str("purpose"),S=n.str("preset"),E=n.str("model"),b=n.str("base-url"),C=n.str("api-key-env"),M=n.str("system"),v=n.str("web"),x=n.str("web-backend"),T=n.str("composio"),N=n.str("telegram"),L=n.str("telegram-allow"),I=n.str("whatsapp"),H=n.str("whatsapp-number"),he=n.str("server"),re=n.str("schedules"),W=n.str("skills"),ke=n.str("daemon");return await Wt({...m===void 0?{}:{dir:m},...p===void 0?{}:{user:p},...h===void 0?{}:{name:h},...w===void 0?{}:{purpose:w},...S===void 0?{}:{preset:S},...E===void 0?{}:{model:E},...b===void 0?{}:{baseUrl:b},...C===void 0?{}:{apiKeyEnv:C},...M===void 0?{}:{system:M},...v===void 0?{}:{web:v},...x===void 0?{}:{webBackend:x},...T===void 0?{}:{composio:T},...N===void 0?{}:{telegram:N},...re===void 0?{}:{schedules:re},...L===void 0?{}:{telegramAllow:L},...I===void 0?{}:{whatsapp:I},...H===void 0?{}:{whatsappNumber:H},...he===void 0?{}:{server:he},...W===void 0?{}:{skills:W},...ke===void 0?{}:{daemon:ke},yes:n.bool("yes"),plain:n.bool("plain"),installServer:Zo})}case"run":{let m=n.str("session"),p=n.str("input"),h=n.str("store");return await Qn({...i[0]===void 0?{}:{manifestPath:l()},...m===void 0?{}:{sessionKey:m},continueSession:n.bool("continue"),...p===void 0?{}:{once:p},...h===void 0?{}:{store:h},ephemeral:n.bool("ephemeral"),quiet:n.bool("quiet"),showReasoning:n.bool("show-reasoning"),noReasoning:n.bool("no-reasoning"),...n.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:n.bool("plain")})}case"schedules":{let m=n.str("store"),p=n.str("id"),h=n.str("enable"),w=n.str("disable");return await qr({manifestPath:l(),...m===void 0?{}:{store:m},...p===void 0?{}:{id:p},...h===void 0?{}:{enable:h},...w===void 0?{}:{disable:w},recipients:n.bool("recipients"),json:n.bool("json")})}case"sessions":{let m=n.str("session"),p=n.str("store"),h=n.num("limit");return await mo({manifestPath:l(),...m===void 0?{}:{sessionKey:m},...p===void 0?{}:{store:p},...h===void 0?{}:{limit:h},json:n.bool("json"),clear:n.bool("clear"),turns:n.bool("turns")})}case"memory":{let m=n.num("limit"),p=n.str("store");return await ps({action:a,manifestPath:Ge(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...m===void 0?{}:{limit:m},...p===void 0?{}:{store:p},all:n.bool("all"),json:n.bool("json")})}case"config":{let{configCommand:m,readAction:p}=await import("./config-d1xb6rwr.js"),h=p(a,i[1]);return await m({action:h.action,...h.ref===void 0?{}:{ref:h.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...n.str("channel")===void 0?{}:{channel:n.str("channel")},remove:n.bool("remove"),yes:n.bool("yes"),...n.str("store")===void 0?{}:{store:n.str("store")}})}case"validate":return await xo({manifestPath:l(),json:n.bool("json")});case"workspace":return To({manifestPath:l(),json:n.bool("json"),strict:n.bool("strict")});case"soul":{let m=n.str("out");return yo({action:a,file:i[1],...m===void 0?{}:{out:m}})}case"skills":{if(i.length===0)return await rs({plain:n.bool("plain"),json:n.bool("json")});let m=i[2];return FA({action:a,manifestPath:Ge(i[1]??""),...m===void 0?{}:{name:m},json:n.bool("json"),strict:n.bool("strict")})}case"sources":{let m=n.str("path"),p=n.str("ref");return await bo({action:a,rest:i.slice(1),...m===void 0?{}:{path:m},...p===void 0?{}:{ref:p},json:n.bool("json")})}case"channels":{let m=$i("channels",a),p=m.ref??i[1]??"",{channelsCommand:h}=await import("./channels-x2d7g01r.js");return await h({...m.action===void 0?{}:{action:m.action},manifestPath:Ge(p),...i[2]===void 0?{}:{channelId:i[2]},json:n.bool("json"),installServer:Zo})}case"plugins":{let m=n.str("ref"),p=n.str("name");return await Ws({action:a,manifestPath:Ge(i[1]??""),rest:i.slice(2),...m===void 0?{}:{ref:m},...p===void 0?{}:{name:p},json:n.bool("json")})}case"agents":{let m=n.str("store");return await pt({manifestPaths:i.map((p)=>Ge(p)),...m===void 0?{}:{store:m},json:n.bool("json")})}case"restart":{let m=n.str("store");return await kr({...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{store:m},json:n.bool("json")})}case"status":{let m=n.str("store");return await ko({...m===void 0?{}:{store:m},json:n.bool("json")})}case"logs":{let m=n.num("lines"),p=n.str("store");return await LA({action:"logs",...a===void 0?{}:{manifestPath:l()},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),...p===void 0?{}:{store:p},json:n.bool("json")})}case"serve":{let m=n.num("port"),p=n.str("host"),h=n.str("store");return await uo({manifestPaths:i.map((w)=>Ge(w)),...m===void 0?{}:{port:m},...p===void 0?{}:{host:p},...h===void 0?{}:{store:h},claim:n.bool("claim"),json:n.bool("json")})}case"keys":return await Yt({noEnhancedKeys:n.bool("no-enhanced-keys")});case"terminal-setup":return await Eo({dryRun:n.bool("dry-run"),yes:n.bool("yes"),json:n.bool("json"),confirm:bt});case"remove":return await fr({...a===void 0?{}:{ref:a},dryRun:n.bool("dry-run"),filesOnly:n.bool("files-only"),prune:n.bool("prune"),all:n.bool("all"),yes:n.bool("yes"),json:n.bool("json"),...n.str("store")===void 0?{}:{store:n.str("store")},confirm:Ji});case"stop":{let m=n.str("reason");return await rn({...a===void 0?{}:{manifestPath:l()},dryRun:n.bool("dry-run"),...m===void 0?{}:{reason:m},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"start":return await vo({manifestPath:l(),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")});case"web":{let{webCommand:m}=await import("./web-memgad0h.js");return await m({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},noOpen:n.bool("no-open"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"credential":{let{credentialCommand:m}=await import("./credential-ghqxh2eg.js");return await m({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...n.str("label")===void 0?{}:{label:n.str("label")},...n.str("agents")===void 0?{}:{agents:n.str("agents")},...n.str("sessions")===void 0?{}:{sessions:n.str("sessions")},...n.str("can")===void 0?{}:{can:n.str("can")},...n.str("expires")===void 0?{}:{expires:n.str("expires")},...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"daemon":{let m=n.num("lines");return await LA({action:a,...i[1]===void 0?{}:{manifestPath:Ge(i[1])},...m===void 0?{}:{lines:m},follow:n.bool("follow"),truncate:n.bool("truncate"),dryRun:n.bool("dry-run"),...n.str("store")===void 0?{}:{store:n.str("store")},json:n.bool("json")})}case"model":{let m=n.num("price");return await Os({manifestPath:Ge(i[1]),window:n.bool("window"),...m===void 0?{}:{price:m},write:n.bool("write"),yes:n.bool("yes"),json:n.bool("json")})}case"tools":return await Ro({manifestPath:l(),warm:n.bool("warm"),json:n.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${r.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}us();cs();ds();await Bd(process.argv.slice(2)).catch(qd).then((e)=>rr(e));
471
471
 
472
- //# debugId=FCD7A98AA5EE144B64756E2164756E21
472
+ //# debugId=763E60EB85D3422864756E2164756E21
473
473
  //# sourceMappingURL=index.js.map