dispach 0.1.2 → 0.2.0-pilot.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (247) hide show
  1. package/README.md +196 -118
  2. package/dist/APEv2Parser-2wqk09q7.js +5 -0
  3. package/dist/APEv2Parser-2wqk09q7.js.map +9 -0
  4. package/dist/AiffParser-zw4g2bdd.js +5 -0
  5. package/dist/AiffParser-zw4g2bdd.js.map +12 -0
  6. package/dist/App-ez7ve0yp.js +11 -0
  7. package/dist/{App-b1yrwrcq.js.map → App-ez7ve0yp.js.map} +6 -7
  8. package/dist/AsfParser-2hfcf5z2.js +5 -0
  9. package/dist/AsfParser-2hfcf5z2.js.map +14 -0
  10. package/dist/ConfigEditor-aamadrx3.js +6 -0
  11. package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-aamadrx3.js.map} +2 -2
  12. package/dist/DsdiffParser-n8smktvb.js +5 -0
  13. package/dist/DsdiffParser-n8smktvb.js.map +11 -0
  14. package/dist/DsfParser-npmjp4vr.js +5 -0
  15. package/dist/DsfParser-npmjp4vr.js.map +11 -0
  16. package/dist/FlacParser-xpbs2zmb.js +5 -0
  17. package/dist/FlacParser-xpbs2zmb.js.map +9 -0
  18. package/dist/KeyProbe-4fp152yv.js +5 -0
  19. package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-4fp152yv.js.map} +2 -2
  20. package/dist/MP4Parser-es3afcmw.js +5 -0
  21. package/dist/MP4Parser-es3afcmw.js.map +12 -0
  22. package/dist/MatroskaParser-kxysj649.js +5 -0
  23. package/dist/MatroskaParser-kxysj649.js.map +13 -0
  24. package/dist/MpegParser-b3rr7b0f.js +5 -0
  25. package/dist/MpegParser-b3rr7b0f.js.map +13 -0
  26. package/dist/MusepackParser-sgjzmq0r.js +5 -0
  27. package/dist/MusepackParser-sgjzmq0r.js.map +16 -0
  28. package/dist/OggParser-x8h54ynf.js +5 -0
  29. package/dist/OggParser-x8h54ynf.js.map +18 -0
  30. package/dist/Picker-rq015kzc.js +5 -0
  31. package/dist/{Picker-hfeh1g6m.js.map → Picker-rq015kzc.js.map} +2 -2
  32. package/dist/SessionPicker-03zyvd2f.js +5 -0
  33. package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-03zyvd2f.js.map} +2 -2
  34. package/dist/SkillBrowser-8s8rjv98.js +5 -0
  35. package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-8s8rjv98.js.map} +2 -2
  36. package/dist/WavPackParser-w515nnw2.js +5 -0
  37. package/dist/WavPackParser-w515nnw2.js.map +11 -0
  38. package/dist/WaveParser-sb0w9m20.js +5 -0
  39. package/dist/WaveParser-sb0w9m20.js.map +13 -0
  40. package/dist/WizardApp-wr1tftcr.js +5 -0
  41. package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-wr1tftcr.js.map} +3 -3
  42. package/dist/agents.d.ts +19 -3
  43. package/dist/agents.d.ts.map +1 -1
  44. package/dist/channels-gx951qdp.js +31 -0
  45. package/dist/channels-gx951qdp.js.map +10 -0
  46. package/dist/channels.d.ts +26 -0
  47. package/dist/channels.d.ts.map +1 -0
  48. package/dist/client.js +11 -11
  49. package/dist/client.js.map +3 -3
  50. package/dist/config-wvjeejgd.js +24 -0
  51. package/dist/{config-g7za9x13.js.map → config-wvjeejgd.js.map} +2 -2
  52. package/dist/credential-10dn3fxj.js +19 -0
  53. package/dist/{credential-npr6z8c8.js.map → credential-10dn3fxj.js.map} +1 -1
  54. package/dist/daemon.d.ts.map +1 -1
  55. package/dist/index-10009hp8.js +11 -0
  56. package/dist/index-10009hp8.js.map +11 -0
  57. package/dist/index-1xwrkwh5.js +14 -0
  58. package/dist/index-1xwrkwh5.js.map +50 -0
  59. package/dist/index-34p39yfc.js +47 -0
  60. package/dist/index-34p39yfc.js.map +15 -0
  61. package/dist/index-3y96s740.js +6 -0
  62. package/dist/{index-hwpvhaza.js.map → index-3y96s740.js.map} +1 -1
  63. package/dist/index-4ybeefmn.js +6 -0
  64. package/dist/index-4ybeefmn.js.map +11 -0
  65. package/dist/index-59z88wrb.js +6 -0
  66. package/dist/{index-h9mw7b9d.js.map → index-59z88wrb.js.map} +2 -2
  67. package/dist/index-5fwzn21m.js +6 -0
  68. package/dist/{index-gz9x25tz.js.map → index-5fwzn21m.js.map} +2 -2
  69. package/dist/index-6dvnfk8y.js +6 -0
  70. package/dist/index-6dvnfk8y.js.map +10 -0
  71. package/dist/index-6p70fnb7.js +153 -0
  72. package/dist/index-6p70fnb7.js.map +20 -0
  73. package/dist/index-6s471ydn.js +12 -0
  74. package/dist/{index-j55s3ehk.js.map → index-6s471ydn.js.map} +2 -2
  75. package/dist/index-87wcawta.js +6 -0
  76. package/dist/{index-0d93hyfc.js.map → index-87wcawta.js.map} +2 -2
  77. package/dist/index-92gfcbw0.js +6 -0
  78. package/dist/index-92gfcbw0.js.map +9 -0
  79. package/dist/index-a0h0p20f.js +991 -0
  80. package/dist/{index-tv4yv7d2.js.map → index-a0h0p20f.js.map} +27 -23
  81. package/dist/index-bamw24xc.js +6 -0
  82. package/dist/{index-6q4wf8e3.js.map → index-bamw24xc.js.map} +1 -1
  83. package/dist/index-c8ge88a9.js +12 -0
  84. package/dist/{index-258d8bzg.js.map → index-c8ge88a9.js.map} +4 -3
  85. package/dist/index-cb2q8nae.js +6 -0
  86. package/dist/index-cb2q8nae.js.map +13 -0
  87. package/dist/index-ct6bw0a6.js +6 -0
  88. package/dist/{index-4z7axw4r.js.map → index-ct6bw0a6.js.map} +1 -1
  89. package/dist/index-cz6yjxyz.js +10 -0
  90. package/dist/index-cz6yjxyz.js.map +42 -0
  91. package/dist/index-d0c5abkw.js +6 -0
  92. package/dist/{index-vgc3y3rm.js.map → index-d0c5abkw.js.map} +3 -3
  93. package/dist/index-d0vagham.js +31 -0
  94. package/dist/index-d0vagham.js.map +188 -0
  95. package/dist/index-d0zxvr99.js +90 -0
  96. package/dist/index-d0zxvr99.js.map +13 -0
  97. package/dist/{index-s9mbq7h6.js → index-d9c97ver.js} +4 -4
  98. package/dist/{index-s9mbq7h6.js.map → index-d9c97ver.js.map} +1 -1
  99. package/dist/index-e508e0vt.js +6 -0
  100. package/dist/{index-tf71ap9v.js.map → index-e508e0vt.js.map} +1 -1
  101. package/dist/index-esq0knqx.js +6 -0
  102. package/dist/index-esq0knqx.js.map +10 -0
  103. package/dist/index-featyhps.js +6 -0
  104. package/dist/index-featyhps.js.map +10 -0
  105. package/dist/index-fnq44zdt.js +45 -0
  106. package/dist/index-fnq44zdt.js.map +74 -0
  107. package/dist/index-gmn80dwc.js +7 -0
  108. package/dist/{index-02dn6m2j.js.map → index-gmn80dwc.js.map} +2 -2
  109. package/dist/index-gwhx69qs.js +66 -0
  110. package/dist/index-gwhx69qs.js.map +12 -0
  111. package/dist/index-kjgzhf3w.js +9 -0
  112. package/dist/{index-6p999cx4.js.map → index-kjgzhf3w.js.map} +4 -6
  113. package/dist/index-m68cd91a.js +12 -0
  114. package/dist/index-m68cd91a.js.map +23 -0
  115. package/dist/{index-3g3ny01d.js → index-mhmgw54j.js} +4 -4
  116. package/dist/{index-3g3ny01d.js.map → index-mhmgw54j.js.map} +1 -1
  117. package/dist/{index-gme2egyq.js → index-qm612hwa.js} +4 -4
  118. package/dist/{index-gme2egyq.js.map → index-qm612hwa.js.map} +1 -1
  119. package/dist/{index-j7gyr5nx.js → index-qwntpbwe.js} +7 -7
  120. package/dist/{index-j7gyr5nx.js.map → index-qwntpbwe.js.map} +1 -1
  121. package/dist/index-qx3xdk4x.js +6 -0
  122. package/dist/{index-d4x6yvqh.js.map → index-qx3xdk4x.js.map} +3 -4
  123. package/dist/{index-4cf6v9nb.js → index-rh0meegk.js} +4 -4
  124. package/dist/{index-4cf6v9nb.js.map → index-rh0meegk.js.map} +1 -1
  125. package/dist/index-ryb159ff.js +9 -0
  126. package/dist/{index-ff514z3y.js.map → index-ryb159ff.js.map} +3 -5
  127. package/dist/{index-ammv5st7.js → index-s6zfpyqa.js} +6 -6
  128. package/dist/{index-ammv5st7.js.map → index-s6zfpyqa.js.map} +1 -1
  129. package/dist/index-s9va2kmc.js +429 -0
  130. package/dist/index-s9va2kmc.js.map +11 -0
  131. package/dist/index-v5dmsgpx.js +7 -0
  132. package/dist/index-v5dmsgpx.js.map +11 -0
  133. package/dist/index-vaj3mn3a.js +6 -0
  134. package/dist/index-vaj3mn3a.js.map +14 -0
  135. package/dist/index-vy0rbzws.js +6 -0
  136. package/dist/{index-fex44816.js.map → index-vy0rbzws.js.map} +2 -2
  137. package/dist/index-w0s77wfx.js +6 -0
  138. package/dist/{index-v8e92nfw.js.map → index-w0s77wfx.js.map} +1 -1
  139. package/dist/index-wx1jzjzr.js +6 -0
  140. package/dist/{index-qdbq8crg.js.map → index-wx1jzjzr.js.map} +2 -2
  141. package/dist/index-xbn26c8g.js +126 -0
  142. package/dist/index-xbn26c8g.js.map +14 -0
  143. package/dist/index-ytvwyp6k.js +6 -0
  144. package/dist/{index-9r0wyj6w.js.map → index-ytvwyp6k.js.map} +2 -2
  145. package/dist/{index-cqqb6gaq.js → index-yvnwpxbb.js} +5 -5
  146. package/dist/{index-cqqb6gaq.js.map → index-yvnwpxbb.js.map} +1 -1
  147. package/dist/index.js +379 -448
  148. package/dist/index.js.map +26 -28
  149. package/dist/init.d.ts.map +1 -1
  150. package/dist/lib/agent-secrets.d.ts +38 -0
  151. package/dist/lib/agent-secrets.d.ts.map +1 -0
  152. package/dist/lib/agent-template.d.ts +54 -0
  153. package/dist/lib/agent-template.d.ts.map +1 -0
  154. package/dist/lib/channel-actions.d.ts +103 -0
  155. package/dist/lib/channel-actions.d.ts.map +1 -0
  156. package/dist/lib/chat-frame.d.ts +12 -1
  157. package/dist/lib/chat-frame.d.ts.map +1 -1
  158. package/dist/lib/commands.d.ts +13 -0
  159. package/dist/lib/commands.d.ts.map +1 -1
  160. package/dist/lib/const.d.ts +1 -1
  161. package/dist/lib/daemon-plan.d.ts.map +1 -1
  162. package/dist/lib/help.d.ts.map +1 -1
  163. package/dist/lib/host-actions.d.ts +121 -0
  164. package/dist/lib/host-actions.d.ts.map +1 -0
  165. package/dist/lib/init-flow.d.ts +32 -0
  166. package/dist/lib/init-flow.d.ts.map +1 -1
  167. package/dist/lib/init-whatsapp.d.ts +52 -0
  168. package/dist/lib/init-whatsapp.d.ts.map +1 -0
  169. package/dist/lib/plugin-install.d.ts +120 -0
  170. package/dist/lib/plugin-install.d.ts.map +1 -0
  171. package/dist/lib/providers.d.ts.map +1 -1
  172. package/dist/lib/provision.d.ts +13 -0
  173. package/dist/lib/provision.d.ts.map +1 -1
  174. package/dist/lib/readme-table.d.ts +15 -0
  175. package/dist/lib/readme-table.d.ts.map +1 -0
  176. package/dist/lib/sandbox.d.ts +17 -0
  177. package/dist/lib/sandbox.d.ts.map +1 -1
  178. package/dist/lib/schema.d.ts +34 -1
  179. package/dist/lib/schema.d.ts.map +1 -1
  180. package/dist/lib/subcommand.d.ts.map +1 -1
  181. package/dist/lib/web-url.d.ts +15 -0
  182. package/dist/lib/web-url.d.ts.map +1 -0
  183. package/dist/lib/wizard.d.ts.map +1 -1
  184. package/dist/memory.d.ts.map +1 -1
  185. package/dist/model.d.ts.map +1 -1
  186. package/dist/plugins.d.ts +27 -8
  187. package/dist/plugins.d.ts.map +1 -1
  188. package/dist/restart.d.ts +21 -0
  189. package/dist/restart.d.ts.map +1 -0
  190. package/dist/run.d.ts.map +1 -1
  191. package/dist/schedules.d.ts.map +1 -1
  192. package/dist/serve.d.ts.map +1 -1
  193. package/dist/sessions.d.ts.map +1 -1
  194. package/dist/skills.d.ts.map +1 -1
  195. package/dist/status.d.ts +16 -0
  196. package/dist/status.d.ts.map +1 -0
  197. package/dist/tools.d.ts.map +1 -1
  198. package/dist/validate.d.ts.map +1 -1
  199. package/dist/web-61cjhpv2.js +14 -0
  200. package/dist/{web-vkb16r62.js.map → web-61cjhpv2.js.map} +3 -3
  201. package/dist/web.d.ts +2 -13
  202. package/dist/web.d.ts.map +1 -1
  203. package/dist/workspace.d.ts.map +1 -1
  204. package/dist/wrapper-9msjh1xg.js +5 -0
  205. package/dist/wrapper-9msjh1xg.js.map +9 -0
  206. package/package.json +6 -3
  207. package/dist/App-b1yrwrcq.js +0 -11
  208. package/dist/ConfigEditor-n8hdw6r7.js +0 -6
  209. package/dist/KeyProbe-9jjeze5r.js +0 -5
  210. package/dist/Picker-hfeh1g6m.js +0 -5
  211. package/dist/SessionPicker-zyqkg4dn.js +0 -5
  212. package/dist/SkillBrowser-3qdp8080.js +0 -5
  213. package/dist/WizardApp-vzpbydy3.js +0 -5
  214. package/dist/config-g7za9x13.js +0 -24
  215. package/dist/credential-npr6z8c8.js +0 -19
  216. package/dist/index-02dn6m2j.js +0 -7
  217. package/dist/index-0d93hyfc.js +0 -6
  218. package/dist/index-1c5113t4.js +0 -66
  219. package/dist/index-1c5113t4.js.map +0 -12
  220. package/dist/index-258d8bzg.js +0 -12
  221. package/dist/index-4z7axw4r.js +0 -6
  222. package/dist/index-6p999cx4.js +0 -9
  223. package/dist/index-6q4wf8e3.js +0 -6
  224. package/dist/index-9r0wyj6w.js +0 -6
  225. package/dist/index-d4x6yvqh.js +0 -6
  226. package/dist/index-fecm8xe7.js +0 -77
  227. package/dist/index-fecm8xe7.js.map +0 -12
  228. package/dist/index-fex44816.js +0 -6
  229. package/dist/index-ff514z3y.js +0 -14
  230. package/dist/index-gz9x25tz.js +0 -6
  231. package/dist/index-h9mw7b9d.js +0 -6
  232. package/dist/index-hwpvhaza.js +0 -6
  233. package/dist/index-j55s3ehk.js +0 -12
  234. package/dist/index-mtn0g9vc.js +0 -7
  235. package/dist/index-mtn0g9vc.js.map +0 -11
  236. package/dist/index-qdbq8crg.js +0 -6
  237. package/dist/index-tf71ap9v.js +0 -6
  238. package/dist/index-ttwyrdjs.js +0 -427
  239. package/dist/index-ttwyrdjs.js.map +0 -11
  240. package/dist/index-tv4yv7d2.js +0 -903
  241. package/dist/index-ty24n0jh.js +0 -167
  242. package/dist/index-ty24n0jh.js.map +0 -19
  243. package/dist/index-v8e92nfw.js +0 -6
  244. package/dist/index-vgc3y3rm.js +0 -6
  245. package/dist/index-whaw4b18.js +0 -6
  246. package/dist/index-whaw4b18.js.map +0 -10
  247. package/dist/web-vkb16r62.js +0 -14
package/dist/index.js CHANGED
@@ -1,531 +1,462 @@
1
1
  #!/usr/bin/env node
2
- import{Mt,e,E,tr,t,_e,fn,Ie,mt,je,H,hn,kr,Sr,ye,xr,ze,we,mn,pt,T,x,R,yt,He,wt,gn,We,_,M,$r,L,yn,Rr,Ir,m,Co}from"./index-tv4yv7d2.js";import{Me,Fn,Un,jn}from"./index-1c5113t4.js";import{A,O,Y,N,X,C,fr,et,hr,Ht,G,Kr,Hr,Wr,Mn,ce,tt,ke,Ln,Se,nt,qr,Gr}from"./index-ty24n0jh.js";import{Ko}from"./index-d4x6yvqh.js";import{Et}from"./index-gme2egyq.js";import{ct,ut,cn,Nt,un,ft,Qn,Ct,Pt,Fe,Te,ht,er}from"./index-ttwyrdjs.js";import{Rt,le,Ot}from"./index-whaw4b18.js";import{on,sn,$t,Xn,lt,bo,ko,So}from"./index-258d8bzg.js";import"./index-cqqb6gaq.js";import{cr,Lr,Xe,Dr,Fr,Ur}from"./index-fecm8xe7.js";import{Ye,Pr}from"./index-ammv5st7.js";import{jr}from"./index-hwpvhaza.js";import{zr,Pn,Br,Ce,Pe,St,xt,Je,Qe,Kt}from"./index-qdbq8crg.js";import{Wt,pe,Zr,b,Vr,J,ue,Dn,Yr,Z,ie}from"./index-6p999cx4.js";import{Ee,ee,B,w,Xt,Jt,ao,K,te}from"./index-mtn0g9vc.js";import{Hn}from"./index-4cf6v9nb.js";import{_o,$o}from"./index-tf71ap9v.js";import{Ro}from"./index-s9mbq7h6.js";import{q}from"./index-h9mw7b9d.js";import{l,p,d,c,bt,or,vt,qe}from"./index-j7gyr5nx.js";import{jo,Bo}from"./index-3g3ny01d.js";import{_n,Jo,ve,j,An,Cn,n,s,Bt,us}from"./index-vgc3y3rm.js";async function Gt(r){let o=await L.create({agents:[...r.manifestPaths],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m(r.manifestPaths),store:w(),lease:!1});b(()=>o.stop("cli-exit"));let a=o.list().map((f)=>f.describe()),u=new Map;for(let f of await o.store.leases.all()){if(f.runtimeId===o.runtimeId||!_(f.pid))continue;let h=Date.now()-Date.parse(f.startedAt);u.set(f.agentId,`serving · ${f.mode} · pid ${f.pid}${Number.isFinite(h)?` · up ${or(h)}`:""}`)}if(r.json===!0)return process.stdout.write(`${JSON.stringify({agents:a.map((f)=>({...f,serving:u.get(f.id)??null}))},null,2)}
3
- `),n;let i=a.map((f)=>({label:f.id,value:`${f.model} ${String(f.window).padStart(7)} window`,note:u.get(f.id)??f.name}));return process.stdout.write(`${l(i)}
4
- `),n}import{closeSync as Wo,existsSync as Tr,mkdirSync as Go,openSync as qo,readFileSync as Vo,readSync as Xo,statSync as Ar}from"node:fs";import{homedir as Yn}from"node:os";import{dirname as kn,join as Or,resolve as zo}from"node:path";function qt(r){let o=[];if(r.problem!==void 0)o.push({code:"daemon_agent_unreadable",severity:"warn",message:`Agent "${r.agentId}" could not be read: ${r.problem}`,hint:"The host skips an agent whose manifest will not load and serves the rest, so this is a warning rather than a refusal — `validate` on that agent says exactly what is wrong with it."});if(r.envFileMode!==void 0&&(r.envFileMode&63)!==0)o.push({code:"daemon_env_world_readable",severity:"warn",message:`${r.agentId}'s .env is mode ${(r.envFileMode&511).toString(8)} and holds its only secrets.`,hint:`Under a service manager that file is the *only* path credentials arrive by — a unit carries none on purpose, because its manager echoes the environment in plaintext. \`chmod 600 ${r.agentDir}/.env\`.`});return o}function Eo(r){let o=[];if(r.gitRoot!==void 0)o.push({code:"daemon_binary_in_checkout",severity:"warn",message:`The binary resolves to ${r.scriptPath}, inside a git checkout at ${r.gitRoot}.`,hint:"A rebuild, a branch switch or a `git clean` changes or breaks what the service runs, and the failure arrives with no obvious connection to the change. Fine for testing; install a released build for a service you intend to leave running."});if(/[/.](nvm|fnm|volta|asdf)\//.test(r.execPath))o.push({code:"daemon_versioned_runtime",severity:"warn",message:`The interpreter is a version-managed install: ${r.execPath}`,hint:"The absolute path is baked into the service definition, so removing that runtime version later kills the service with a message only the log file sees. A system or Homebrew install is more durable."});return o}function Vt(r){let o=[];for(let a of r.retiring)o.push({code:"daemon_per_agent_retired",severity:"warn",message:`Retiring ${a} — one service hosts every agent now.`,hint:"It is unloaded, re-enabled and its definition removed. The re-enable is not cosmetic: a `disable` row persists across boots and no verb deletes it, so a label left disabled makes any future job with that name install cleanly and silently never start. Per-agent on/off is `stop <agent>`, which persists in the store instead."});if(r.servedElsewhere.length>0){let a=r.servedElsewhere[0];o.push({code:"daemon_agents_held_elsewhere",severity:"warn",message:`${r.servedElsewhere.length} agent(s) are held by other live processes — ${a?.agentId} by pid ${a?.pid} (${a?.mode}).`,hint:"The service will start and serve everything else, and report those as served elsewhere rather than fighting for them — one listener per bot token is the whole reason the lease exists. `stop` with no agent ends the other processes."})}return o.push(...Eo(r.binary)),o}function Io(r,o="serving on"){let a=r.lastIndexOf(o);return a===-1?r:r.slice(a)}function zt(r){let o=Io(r),a=[],u=new Set;for(let i of o.matchAll(/denied — Sender "([^"]+)" is not in channel "([^"]+)"/g))if(i[1]!==void 0)u.add(`${i[1]}|${i[2]??""}`);for(let i of u){let[f,h]=i.split("|");a.push({code:"inbound_denied",summary:`messages from ${f} are being refused — they are not on channel "${h}"'s allowFrom list`,fix:`add ${f} to allowFrom in agent.yaml, then restart. An allowlist that is empty, or that has a typo in it, refuses silently from the sender's side: they see nothing at all.`})}if(/channel_telegram_unauthorized|telegram_token_missing/.test(o))a.push({code:"channel_unauthorized",summary:"the channel rejected its token",fix:"check the token in the .env beside the manifest, then restart."});return a}var To=3;function Yt(r,o){let a=Ao(o),u=[];if(o.pid!==void 0)u.push({label:"state",value:`running · pid ${o.pid}`,...o.uptimeMs===void 0?{}:{note:`up ${or(o.uptimeMs)}`}});else if(o.leasePid!==void 0)u.push({label:"state",value:`running in a terminal · pid ${o.leasePid}`,note:"not installed as a service"});if(o.runs!==void 0&&o.runs>1)u.push({label:"starts",value:String(o.runs),...a==="restart-loop"?{note:`launchd has restarted this ${o.runs} times`}:{note:"since the service was installed"}});if(a!=="running"&&o.lastExitCode!==void 0&&o.lastExitCode!==0)u.push({label:"last exit",value:`code ${o.lastExitCode}`});if(o.stderrPath!==void 0)u.push({label:"logs",value:o.stderrPath,...o.stderrBytes===void 0?{}:{note:`(${bt(o.stderrBytes)})`}});return{verdict:a,healthy:a==="running",headline:a==="restart-loop"?`${r} — RESTART LOOP`:`${r} — ${Oo(a)}`,rows:u,wantsStderrTail:a==="restart-loop"||a==="failed"||a==="installed-idle"}}function Ao(r){if(!r.installed)return r.leasePid===void 0?"absent":"running";if(r.pid!==void 0)return"running";if(r.disabled)return"stopped";if((r.runs??0)>=To&&(r.lastExitCode??0)!==0)return"restart-loop";if((r.lastExitCode??0)!==0)return"failed";return"installed-idle"}function Oo(r){switch(r){case"running":return"running";case"failed":return"STOPPED AFTER A FAILURE";case"restart-loop":return"exited · nothing is running";case"stopped":return"stopped by you";case"installed-idle":return"installed · not running";case"absent":return"not installed"}}function Qt(r){return`${r.headline}
5
- ${l(r.rows)}`}function dn(r){return["HOME","PATH","TMPDIR",`${r}SERVICE`,`${r}HOME`]}class Wn extends Error{code="daemon_secret_in_service";hint;constructor(r,o,a){super(`The service definition would carry an environment variable named ${r}.`);this.hint=`A ${a} unit is readable and its manager echoes every environment value in plaintext to any process running as this user — so a credential here is a credential published. The agent reads its own secrets from the .env beside its manifest, which is what the service is pointed at. Only these may appear: ${o.join(", ")}.`}}function ln(r,o,a){let u=dn(o);for(let i of Object.keys(r))if(!u.includes(i))throw new Wn(i,u,a)}var No={Crashed:!0},Be=30,Ge=30;function pn(r,o){return`${r}.agent.${o}`}function Ke(r){return`${r}.server`}function Re(r){return r.replaceAll("&","&amp;").replaceAll("<","&lt;").replaceAll(">","&gt;").replaceAll('"',"&quot;").replaceAll("'","&apos;")}function wn(r,o){ln(r.environment,o,"launchd");let a=r.programArguments.map((f)=>` <string>${Re(f)}</string>`).join(`
6
- `),u=Object.entries(r.environment).map(([f,h])=>` <key>${Re(f)}</key>
7
- <string>${Re(h)}</string>`).join(`
8
- `);return`<?xml version="1.0" encoding="UTF-8"?>
9
- <!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
10
- <!--
11
- ${r.provenance.map((f)=>` ${Re(f)}`).join(`
12
- `)}
13
- -->
14
- <plist version="1.0">
15
- <dict>
16
- <key>Label</key>
17
- <string>${Re(r.label)}</string>
18
- <key>ProgramArguments</key>
19
- <array>
20
- ${a}
21
- </array>
22
- <key>RunAtLoad</key>
23
- <true/>
24
- <key>KeepAlive</key>
25
- <dict>
26
- <key>Crashed</key>
27
- <${No.Crashed}/>
28
- </dict>
29
- <key>ThrottleInterval</key>
30
- <integer>${Be}</integer>
31
- <key>ExitTimeOut</key>
32
- <integer>${Ge}</integer>
33
- <key>ProcessType</key>
34
- <string>Adaptive</string>
35
- <key>WorkingDirectory</key>
36
- <string>${Re(r.workingDirectory)}</string>
37
- <key>StandardOutPath</key>
38
- <string>${Re(r.stdoutPath)}</string>
39
- <key>StandardErrorPath</key>
40
- <string>${Re(r.stderrPath)}</string>
41
- <key>EnvironmentVariables</key>
42
- <dict>
43
- ${u}
44
- </dict>
45
- </dict>
46
- </plist>
47
- `}function Zt(r){let o=[];for(let a of r.split(`
48
- `)){let u=a.split("\t");if(u.length<3)continue;let[i,f,h]=u;if(h===void 0||h==="Label"||h==="")continue;let g=Number.parseInt(f??"",10);o.push({...i===void 0||i==="-"?{}:{pid:Number.parseInt(i,10)},status:Number.isFinite(g)?g:0,label:h})}return o}function nr(r){let o={};for(let a of r.split(`
49
- `)){let u=a.trim(),i=/^pid = (\d+)$/.exec(u);if(i?.[1]!==void 0)o.pid=Number.parseInt(i[1],10);let f=/^runs = (\d+)$/.exec(u);if(f?.[1]!==void 0)o.runs=Number.parseInt(f[1],10);let h=/^last exit code = (-?\d+)$/.exec(u);if(h?.[1]!==void 0)o.lastExitCode=Number.parseInt(h[1],10);let g=/^state = (.+)$/.exec(u);if(g?.[1]!==void 0)o.jobState=g[1];let v=/^stdout path = (.+)$/.exec(u);if(v?.[1]!==void 0)o.stdoutPath=v[1];let k=/^stderr path = (.+)$/.exec(u);if(k?.[1]!==void 0)o.stderrPath=k[1]}return o}function rr(r){let o=[];for(let a of r.split(`
50
- `)){let u=/^\s*"(.+)"\s*=>\s*(disabled|true)\s*$/.exec(a);if(u?.[1]!==void 0)o.push(u[1])}return o}function Fo(r,o){if(o<r)return{from:0,to:o,truncated:!0};return{from:r,to:o,truncated:!1}}async function sr(r,o,a){let u=new Map(r.map((f)=>[f.path,a.offsets[f.path]??0])),i;while(!o.stopped()){for(let f of r){let h=o.sizeOf(f.path);if(h===void 0)continue;let g=Fo(u.get(f.path)??0,h);if(u.set(f.path,g.to),g.truncated)o.write(`
51
- ── ${f.label} was emptied ──
52
- `),i=f.label;if(g.to<=g.from)continue;let v=o.read(f.path,g.from,g.to);if(v==="")continue;if(r.length>1&&f.label!==i)o.write(`
53
- ── ${f.label} ──
54
- `),i=f.label;o.write(v)}await o.wait(a.intervalMs)}}import{existsSync as Mo,mkdirSync as qn,readdirSync as ur,rmSync as mr,writeFileSync as pr}from"node:fs";import{basename as Uo,dirname as vn,join as lr}from"node:path";import{join as ir}from"node:path";function ar(r,o,a=process.env){let u=a.XDG_CONFIG_HOME,i=u===void 0||u===""?ir(o,".config"):u;return ir(i,"systemd","user",`${r}.service`)}function Gn(r,o){if(/[\r\n]/.test(r))throw Error(`${o} contains a newline, which systemd cannot express. hint: a unit value runs to end of line, so this would silently truncate rather than fail — rename the path.`)}function Lo(r){if(!/[\s"\\]/.test(r))return r;return`"${r.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function bn(r,o){ln(r.environment,o,"systemd");for(let f of r.programArguments)Gn(f,"ExecStart");Gn(r.workingDirectory,"WorkingDirectory");for(let[f,h]of Object.entries(r.environment))Gn(h,`Environment=${f}`);let a=r.programArguments.map(Lo).join(" "),u=Object.entries(r.environment).map(([f,h])=>`Environment=${f}=${h}`).join(`
55
- `);return`${r.provenance.map((f)=>`# ${f}`).join(`
56
- `)}
57
-
58
- [Unit]
59
- Description=${r.label}
60
- After=network-online.target
61
- Wants=network-online.target
62
-
63
- [Service]
64
- Type=simple
65
- ExecStart=${a}
66
- WorkingDirectory=${r.workingDirectory}
67
- ${u}
68
- # A configuration fault stops the service once rather than retrying into a log nobody opens.
69
- # Mirrors launchd's KeepAlive: {Crashed: true} — see launchd.ts for why that is structural.
70
- Restart=on-failure
71
- RestartSec=${Be}
72
- # Must exceed the runtime's own stop deadline, or the reaper that kills backgrounded exec
73
- # children never finishes and they outlive the service.
74
- TimeoutStopSec=${Ge}
75
- KillMode=mixed
76
-
77
- [Install]
78
- WantedBy=default.target
79
- `}function dr(r,o){return["systemctl --user daemon-reload",`systemctl --user enable --now ${r}`,`loginctl enable-linger ${o}`]}var Do=6000,Ho=200,gr=(r,o)=>{let a=Ro({command:r,args:o});return{code:a.code,stdout:a.stdout,stderr:a.stderr}};function Ue(r,o){if(r==="darwin")return new br(o);if(r==="linux")return new wr(o);throw Vn(r)}function yr(r){return r==="darwin"}function Vn(r,o){let a=o===void 0?"":` For a systemd user unit, the line to write is:
80
-
81
- ${o}
82
- Restart=on-failure
83
- RestartSec=30
84
-
85
- Put no secrets in the unit: the agent reads the .env beside its manifest, and \`systemctl show\` echoes Environment= to anyone.`;return new t({code:"daemon_platform_unsupported",message:`daemon installs a macOS LaunchAgent or a systemd user unit, and this platform is ${r}.`,hint:`No service manager is implemented for this platform.${a} In a container, run \`serve\` in the foreground and let the container runtime supervise it; that is the deployment this runtime is designed around.`})}class wr{id="systemd";#r;#e;#s;#t;constructor(r){this.#r=r.home,this.#e=r.envPrefix,this.#s=r.exec??gr,this.#t=r.env??process.env}unitPath(r){return ar(r,this.#r,this.#t)}install(r){let o=this.unitPath(r.label),a=bn(r,this.#e);qn(vn(o),{recursive:!0}),pr(o,a,{encoding:"utf8",mode:384})}uninstall(r){mr(this.unitPath(r),{force:!0})}stop(r){throw this.#n(`systemctl --user stop ${r}`)}start(r){throw this.#n(`systemctl --user start ${r}`)}restart(r){throw this.#n(`systemctl --user restart ${r}`)}state(r){return{installed:Mo(this.unitPath(r)),disabled:!1,liveness:!1}}labels(r){try{return ur(vn(this.unitPath(r))).filter((o)=>o.startsWith(r)&&o.endsWith(".service")).map((o)=>o.slice(0,-8)).sort()}catch{return[]}}followUp(r){return dr(r,this.#o())}caution(){let r=this.#o(),o=this.#s("loginctl",["show-user",r,"--property=Linger"]);if(o.code===0&&/Linger=yes/i.test(o.stdout))return;return`A systemd user unit stops when your last session ends. \`loginctl enable-linger ${r}\` is what keeps it running after you log out or close an SSH connection.`}#o(){return this.#t.USER??this.#t.LOGNAME??Uo(this.#r)}#n(r){return new t({code:"daemon_manual_step",message:`This has to be run yourself: ${r}`,hint:`Unit files are written and read from here, and the lifecycle is not driven from here — nothing in this project's test environment can run \`systemctl --user\` (a container has no systemd, and a CI runner has no user session bus), and a command that reported success while nothing happened would be worse than this sentence. The unit is at ${this.unitPath(r.split(" ").pop()??"")}.`})}}class br{id="launchd";#r;#e;#s;#t;constructor(r){this.#r=r.home,this.#e=`gui/${r.uid}`,this.#s=r.envPrefix,this.#t=r.exec??gr}unitPath(r){return lr(this.#r,"Library","LaunchAgents",`${r}.plist`)}install(r){let o=this.unitPath(r.label),a=wn(r,this.#s);if(qn(vn(o),{recursive:!0}),qn(vn(r.stdoutPath),{recursive:!0}),this.#n(["bootout",`${this.#e}/${r.label}`],{tolerate:!0}),this.#o(r.label),pr(o,a,{encoding:"utf8",mode:384}),this.#n(["enable",`${this.#e}/${r.label}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,o]),!this.state(r.label).installed)throw new t({code:"daemon_not_loaded",message:`${r.label} was written to ${o} but launchd did not load it.`,hint:`\`launchctl bootstrap\` returned success and \`launchctl print ${this.#e}/${r.label}\` finds nothing, which usually means an earlier copy was still unloading. Try again in a moment. Over SSH with no desktop session the ${this.#e} domain is unavailable and no LaunchAgent can load at all.`})}#o(r){let o=Date.now()+Do;while(Date.now()<o){if(this.#t("launchctl",["print",`${this.#e}/${r}`]).code!==0)return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,Ho)}}uninstall(r){this.#n(["bootout",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["enable",`${this.#e}/${r}`],{tolerate:!0}),mr(this.unitPath(r),{force:!0})}stop(r){this.#n(["disable",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["bootout",`${this.#e}/${r}`],{tolerate:!0})}start(r){this.#n(["enable",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["bootstrap",this.#e,this.unitPath(r)])}restart(r){this.#n(["kickstart","-k",`${this.#e}/${r}`])}state(r){let o=this.#t("launchctl",["print",`${this.#e}/${r}`]),a=rr(this.#t("launchctl",["print-disabled",this.#e]).stdout).includes(r);if(o.code!==0)return{installed:!1,disabled:a,liveness:!0};let u=nr(o.stdout);return{installed:!0,disabled:a,liveness:!0,print:u,...u.pid===void 0?{}:{pid:u.pid}}}labels(r){let o=Zt(this.#t("launchctl",["list"]).stdout).map((u)=>u.label).filter((u)=>u.startsWith(r)),a=[];try{a=ur(lr(this.#r,"Library","LaunchAgents")).filter((u)=>u.startsWith(r)&&u.endsWith(".plist")).map((u)=>u.slice(0,-6))}catch{}return[...new Set([...o,...a])].sort()}followUp(){return[]}caution(){return}#n(r,o={}){let a=this.#t("launchctl",r);if(a.code===0||o.tolerate===!0)return a;throw new t({code:"daemon_launchctl_failed",message:`launchctl ${r.join(" ")} failed (${a.code}): ${a.stderr.trim()||"no output"}`,hint:`Code 5 usually means the service is already loaded — try \`daemon restart\`. Code 37 means an operation is still in progress; wait a moment. Code 125 or 112 means the ${this.#e} domain is unavailable, which happens over SSH with no GUI session: a LaunchAgent needs a logged-in desktop session, and the exit timeout is ${Ge}s.`})}}var vr=["install","uninstall","start","stop","restart","status","logs"];async function Ze(r){if(!vr.includes(r.action))throw new t({code:"cli_daemon_unknown_action",message:`daemon takes one of ${vr.join(", ")}, not "${r.action}".`,hint:`Usage: ${e.slug} daemon <action> <agent>. Run \`${e.slug} daemon --help\` for what each one does.`});let o=r.action;if(r.manifestPath!==void 0&&o!=="status"&&o!=="logs")throw new t({code:"daemon_per_agent_retired",message:`daemon ${o} no longer takes an agent — one service hosts every agent.`,hint:`\`${e.slug} daemon ${o}\` acts on that one service. Per-agent on/off is \`${e.slug} stop <agent>\` and \`${e.slug} start <agent>\`, which persist in the store rather than as a unit — so an agent you switch off stays off across a restart without the host going down with it.`});let a=r.platform??process.platform,u=Qo();if(a!=="darwin"&&a!=="linux"&&o!=="status")throw Vn(a,ei(u,r.manifestPath??"<manifest>"));let i=a==="darwin"||a==="linux"?Ue(a,{home:Yn(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec},...r.env===void 0?{}:{env:r.env}}):void 0;switch(o){case"status":return await oi(r,i);case"install":return await Yo(r,u,i);case"uninstall":return ri(r,i);case"start":case"stop":case"restart":return si(o,i);case"logs":return await di(r)}}async function Yo(r,o,a){let u=Ke(e.slug),i=Xt(r.env),f=(a?.labels(`${e.slug}.agent.`)??[]).filter((y)=>y!==u),h=[...Vt({binary:o,retiring:f,servedElsewhere:(await St(r.store)).map((y)=>({agentId:y.agentId,pid:y.pid,mode:y.mode}))}),...K(r.env).flatMap((y)=>{let S=ti(y.dir);return qt({agentId:y.id??y.ref,agentDir:y.dir,...y.problem===void 0?{}:{problem:y.problem},...S===void 0?{}:{envFileMode:S}})})],g={label:u,programArguments:[o.execPath,o.scriptPath,"serve","--store",w()],workingDirectory:ee(r.env),stdoutPath:i.out,stderrPath:i.err,environment:ni(u),provenance:[`Generated by \`${e.slug} daemon install\`. One service hosts every agent.`,"Rewritten on every install — it names no agent, so there is nothing here to edit","when you add one. Switch an agent off with `stop <agent>`, which persists.","There are no secrets here and there never will be: a service manager echoes a","unit's environment in plaintext to anything running as this user. Each agent","reads its own credentials from the .env beside its manifest."]};if(r.dryRun===!0){if(process.stdout.write(a?.id==="systemd"?bn(g,e.envPrefix):wn(g,e.envPrefix)),h.length>0)process.stderr.write(Er(h));return n}for(let y of f)a?.uninstall(y);if(h.length>0)process.stdout.write(Er(h));Go(kn(i.out),{recursive:!0}),a?.install(g);let v=a?.followUp(u)??[];if(process.stdout.write(`${u} — ${v.length===0?"service installed":"unit written"}
86
- ${l([{label:"runs",value:`${Ve(o.execPath)} … serve`},{label:"hosts",value:"every agent in the sandbox that is not stopped"},{label:"logs",value:Ve(i.err)},{label:"restarts",value:`on crash only, at most one per ${Be}s`}])}
87
- `),v.length>0)process.stdout.write(`
88
- Not started yet — run these:
89
- ${v.map((y,S)=>` ${S+1}. ${y}`).join(`
90
- `)}
91
- `);let k=a?.caution();if(k!==void 0)process.stdout.write(`
92
- ${k}
93
- `);return process.stdout.write(`
94
- A configuration error stops it once rather than looping — \`${e.slug} daemon status\` says why.
95
- `),n}function Qo(){let r=Jn(process.execPath),o=Jn(process.argv[1]??""),a=Zo(kn(o));return{execPath:r,scriptPath:o,...a===void 0?{}:{gitRoot:a}}}function Jn(r){try{return Mt("node:fs").realpathSync(r)}catch{return r}}function Zo(r){let o=r;for(let a=0;a<40;a+=1){if(Tr(Or(o,".git")))return o;let u=kn(o);if(u===o)return;o=u}return}function ei(r,o){return`ExecStart=${r.execPath} ${r.scriptPath} serve ${o} --store ${w()}`}function ni(r){let o=Yn(),u=[kn(Jn(process.execPath)),"/opt/homebrew/bin","/usr/local/bin","/usr/bin","/bin","/usr/sbin","/sbin"].filter((h,g,v)=>v.indexOf(h)===g).join(":"),i={HOME:o,PATH:u,[`${e.envPrefix}SERVICE`]:r},f=process.env[`${e.envPrefix}HOME`];if(f!==void 0&&f!=="")i[`${e.envPrefix}HOME`]=f;return i}function ti(r){try{return Ar(Or(r,".env")).mode}catch{return}}function Er(r){return`${r.map((o)=>`${o.severity==="block"?"refused":"warning"}: ${o.message}
96
- hint: ${o.hint}`).join(`
97
-
98
- `)}
99
- `}function ri(r,o){let a=Ke(e.slug),u=Xt(r.env);for(let i of(o?.labels(`${e.slug}.agent.`)??[]).filter((f)=>f!==a))o?.uninstall(i),process.stdout.write(` also removed ${i}
100
- `);return o?.uninstall(a),process.stdout.write(`${a} — service removed
101
- ${l([{label:"logs kept",value:Ve(u.err)},{label:"agents",value:"unchanged — nothing was switched off"}])}
102
- `),n}function si(r,o){let a=Ke(e.slug);if(o===void 0)return s;if(r==="start")o.start(a);if(r==="stop")o.stop(a);if(r==="restart")o.restart(a);let u=r==="stop"?" — the whole host. It stays stopped across a login until you start it again, and no"+" agent was switched off":"";return process.stdout.write(`${a} — ${r}${r==="stop"?"ped":"ed"}${u}
103
- `),n}async function oi(r,o){let a=Ke(e.slug),u=await St(r.store);if(r.manifestPath===void 0){if(o?.state(a).installed!==!0&&u.length===0)return process.stdout.write(`no server is installed and nothing is running
104
- hint: \`${e.slug} daemon install\` keeps one running after you close the terminal. One service hosts every agent.
105
- `),s}let i=r.manifestPath===void 0?[a]:[_r(r.manifestPath)],f=await Promise.all(i.map((v)=>ai(v,o,{...v===a?{label:a}:{},logs:v===a?Xt(r.env):Jt(v),...r.store===void 0?{}:{store:r.store},...v===a&&u[0]!==void 0?{leaseOf:u[0].agentId}:{}}))),h=r.manifestPath===void 0&&u.length>0?u.map((v)=>v.agentId).sort():[],g=(await ii()).filter((v)=>r.manifestPath===void 0||i.includes(v.agentId));if(r.json===!0)process.stdout.write(`${JSON.stringify({agents:f,hosting:h,disabled:g},null,2)}
106
- `);else{for(let v of f){process.stdout.write(`${Qt(v.report)}
107
- `);for(let k of v.attention)process.stdout.write(`
108
- needs you ${k.summary}
109
- ${k.fix}
110
- `);if(v.report.wantsStderrTail&&v.tail!=="")process.stdout.write(`
111
- last lines of stderr:
112
- ${c(v.tail,4)}
113
- `);if(v.report.verdict==="restart-loop"||v.report.verdict==="failed")process.stdout.write(`
114
- fix correct the error above, then \`${e.slug} daemon restart ${v.agentId}\`
115
- `);process.stdout.write(`
116
- `)}if(h.length>0)process.stdout.write(` hosting ${h.length} ${h.length===1?"agent":"agents"}: ${h.join(", ")}
117
- `);if(g.length>0){let v=`${g.length} ${g.length===1?"agent":"agents"}`;process.stdout.write(` ${v} switched off, so nothing is hosting them:
118
- `);for(let k of g)process.stdout.write(` ${k.agentId}${k.reason===void 0?"":` — ${k.reason}`}${k.disabledAt===void 0?"":` (since ${k.disabledAt})`}
119
- `);process.stdout.write(` \`${e.slug} start <agent>\` switches one back on — a restart alone will not.
120
-
121
- `)}}return f.every((v)=>v.report.healthy)?n:s}async function ii(){try{let r=await M.open({path:w()});try{return(await r.agentState.list()).filter((o)=>!o.enabled).map((o)=>({agentId:o.agentId,...o.reason===void 0?{}:{reason:o.reason},...o.disabledAt===void 0?{}:{disabledAt:o.disabledAt}}))}finally{await r.close()}}catch{return[]}}async function ai(r,o,a){let u=a.label,i=u===void 0?void 0:o?.unitPath(u),f=u===void 0?void 0:o?.state(u),h=a.logs,g;try{let U=await M.open({path:a.store??w()});g=await U.leases.get(a.leaseOf??r),await U.close()}catch{g=void 0}if(g!==void 0&&!_(g.pid))g=void 0;let v=f?.print?.stderrPath??h.err,k=$n(v),y={installed:i!==void 0&&Tr(i)||f?.installed===!0,disabled:f?.disabled??!1,...f?.pid===void 0?{}:{pid:f.pid},...f?.print?.runs===void 0?{}:{runs:f.print.runs},...f?.print?.lastExitCode===void 0?{}:{lastExitCode:f.print.lastExitCode},stderrPath:Ve(v),...k===void 0?{}:{stderrBytes:k},...g===void 0?{}:{leasePid:g.pid,leaseMode:g.mode,leaseStartedAt:g.startedAt,uptimeMs:Date.now()-Date.parse(g.startedAt)}},S=Yt(r,y),P=zt(zn(h.out,200));return{agentId:r,report:S,tail:S.wantsStderrTail?zn(v,20):"",attention:P}}async function di(r){let o=r.manifestPath===void 0?void 0:_r(r.manifestPath),a=o??Ke(e.slug),u=o===void 0?Xt(r.env):Jt(o);if(r.truncate===!0){for(let f of[u.out,u.err])try{Mt("node:fs").writeFileSync(f,"")}catch{}return process.stdout.write(`${a} — logs truncated
122
- `),n}let i=zn(u.err,r.lines??40);if(process.stdout.write(i===""?`${Ve(u.err)} is empty
123
- `:`${i}
124
- `),r.follow!==!0)return n;return await sr([{path:u.err,label:"stderr"},{path:u.out,label:"stdout"}],li(),{offsets:{[u.err]:$n(u.err)??0,[u.out]:$n(u.out)??0},intervalMs:us}),n}function li(){let r=!1,o,a=()=>{r=!0,o?.()};return process.on("SIGINT",a),b(()=>{process.off("SIGINT",a)}),{sizeOf:(u)=>$n(u),read:(u,i,f)=>{try{let h=qo(u,"r");try{let g=Buffer.alloc(f-i),v=Xo(h,g,0,g.length,i);return g.subarray(0,v).toString("utf8")}finally{Wo(h)}}catch{return""}},write:(u)=>void process.stdout.write(u),wait:(u)=>new Promise((i)=>{if(r){i();return}let f=setTimeout(i,u);o=()=>{clearTimeout(f),i()}}),stopped:()=>r}}function _r(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_daemon_agent_id_missing",message:`${r} declares no id, so there is no stable name to install a service under.`,hint:"A service label is derived from the manifest id and has to survive a rename of the directory. Add `id: <name>` to the manifest."});return o.id}function Ve(r){return vt(zo(r),Yn())}function $n(r){try{return Ar(r).size}catch{return}}function zn(r,o){try{let a=Vo(r,"utf8").trimEnd();if(a==="")return"";return a.split(`
125
- `).slice(-o).join(`
126
- `)}catch{return""}}var ll=dn(e.envPrefix);import{basename as Si,dirname as xi,join as xe,resolve as Pi}from"node:path";import{rmSync as ci}from"node:fs";import{isAbsolute as Cr,join as ui,resolve as Nr}from"node:path";var fi=3;async function Mr(r){if(r.answers.skills!=="find")return;let o=r.answers.skillsSearch?.trim()??"";if(o===""){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 a=G(r.env);if(a.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(`
127
- searching ${a.length} skill source(s) for ${JSON.stringify(o)}
128
- `);let u=[],i=[];for(let y of a){if(!ce(y.name,r.env))try{await tt(y,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}})}catch(S){i.push(`${y.name} — ${S instanceof t?S.message:String(S)}`);continue}u.push(...ke(y,r.env))}for(let y of i)process.stdout.write(c(`could not fetch ${y}
129
- `));if(u.length===0){process.stdout.write(`${c("no source could be read, so no skill was installed — the directory is there and empty")}
130
- ${c("`sources update` reports why; `sources search <words>` when it works",4)}
131
- `);return}let f=mi(o,u);if(f.length===0){process.stdout.write(`${c(`nothing in ${u.length} skills matches those words, so none was installed`)}
132
- ${c("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
133
- `);return}let h=f[0],g=`${h.source}/${h.skill}`;if(process.stdout.write(`${c(`best of ${u.length}: ${g}`)}
134
- `),f.length>1)process.stdout.write(`${c(`also matched: ${f.slice(1,1+fi).map((y)=>`${y.source}/${y.skill}`).join(", ")}`,4)}
2
+ import{A,x,Ge,t,_A,Tn,DA,Bt,GA,fe,Rn,Ii,li,oA,Ei,PA,iA,kn,Fe,L,K,di,Bi,pt,H,Ln,Gn,UA,ft,Pn,HA,J,ie,fi,ge,Fn,vn,Un,Qi,yi,M,Gr}from"./index-a0h0p20f.js";import{So,NA,Do,wo,pA,Oo,bo,Mo}from"./index-gwhx69qs.js";import{oe,Ae,Z,ae,ni}from"./index-34p39yfc.js";import{Wr}from"./index-qx3xdk4x.js";import{Ht}from"./index-qm612hwa.js";import{at,gt,Qn,we,Ir,lr,fo,ti,ho,Ze,Qo,ct,dA,yo,BA,It,Er,Cr}from"./index-xbn26c8g.js";import{lo,Mt,CA,Xo,Eo,nt,Co,cn,ot,In,Nt,ln,En,Ar,Cn,un,dn}from"./index-6p70fnb7.js";import{Et,Ct,bn,Lt,Mn,ut,Lo,Gt,je,kA,hA,dt,Go}from"./index-s9va2kmc.js";import{Ai,nr,Tt,or,ir,rr,MA}from"./index-d0zxvr99.js";import{Rt,Ye,kt,gr}from"./index-6dvnfk8y.js";import{sn,an,Ot,co,tt,ji,gn,Wi,zi}from"./index-c8ge88a9.js";import"./index-yvnwpxbb.js";import{EA,bt,$i,er}from"./index-e508e0vt.js";import{it,tr}from"./index-s6zfpyqa.js";import{Re}from"./index-10009hp8.js";import{sr}from"./index-3y96s740.js";import{cr,Bo,po,ke,_e,uA,Ie,st,ze,hn}from"./index-wx1jzjzr.js";import{Oe,Je}from"./index-4ybeefmn.js";import{yn,tA,ur,P,Br,Le,Xe,mo,pr}from"./index-kjgzhf3w.js";import{QA,pe,le,ai,G,V,Po,Pt,Rr,X,Me}from"./index-v5dmsgpx.js";import{Se}from"./index-59z88wrb.js";import{Uo}from"./index-rh0meegk.js";import{E,N,f,p,KA,Kt,xA,YA}from"./index-qwntpbwe.js";import{Jr,qr}from"./index-mhmgw54j.js";import{qn,ns,sA,Ce,zn,Ao,n,c,xt}from"./index-d0c5abkw.js";async function nn(e){let r=await uA(e),o=[];for(let i of X()){let s=i.id??i.ref,a=await po(s,e)??{enabled:!0},d=r.find((m)=>m.agentId===s),l=d===void 0?Number.NaN:Date.now()-Date.parse(d.startedAt);o.push({...i,enabled:a.enabled,...a.reason===void 0?{}:{reason:a.reason},...d===void 0?{}:{pid:d.pid,serving:`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(l)?` · up ${Kt(l)}`:""}`}})}return o}function tn(e){if(e.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return e.map((r)=>({label:r.ref,value:r.problem!==void 0?"broken":r.enabled?"on":"off",note:r.problem??r.serving??(r.enabled?`not hosted${r.modelId===void 0?"":` · ${r.modelId}`}`:`switched off${r.reason===void 0?"":` — ${r.reason}`}`)}))}async function Zn(e){if(e.manifestPaths.length===0){let a=await nn(e.store);if(e.json===!0)process.stdout.write(`${JSON.stringify({agents:a},null,2)}
3
+ `);else process.stdout.write(`${E(tn(a))}
4
+ `);return n}let r=await ge.create({agents:[...e.manifestPaths],toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M(e.manifestPaths),store:e.store??G(),lease:!1});P(()=>r.stop("cli-exit"));let o=r.list().map((a)=>a.describe()),i=new Map;for(let a of await r.store.leases.all()){if(a.runtimeId===r.runtimeId||!J(a.pid))continue;let d=Date.now()-Date.parse(a.startedAt);i.set(a.agentId,`serving · ${a.mode} · pid ${a.pid}${Number.isFinite(d)?` · up ${Kt(d)}`:""}`)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:o.map((a)=>({...a,serving:i.get(a.id)??null}))},null,2)}
5
+ `),n;let s=o.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(`${E(s)}
6
+ `),n}import{basename as pn,dirname as no,join as ee,resolve as to}from"node:path";import{rmSync as Kr}from"node:fs";import{isAbsolute as et,join as Lr,resolve as rt}from"node:path";var Ur=3;async function lt(e){if(e.answers.skills!=="find")return;let r=e.answers.skillsSearch?.trim()??"";if(r===""){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 o=we(e.env);if(o.length===0){process.stdout.write("\nno skill sources are configured, so there was nothing to search\n\n `sources add <url>` adds one, then `skills install <agent> <source>/<skill>`.\n");return}process.stdout.write(`
7
+ searching ${o.length} skill source(s) for ${JSON.stringify(r)}
8
+ `);let i=[],s=[];for(let u of o){if(!Ze(u.name,e.env))try{await ct(u,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}})}catch(h){s.push(`${u.name} — ${h instanceof t?h.message:String(h)}`);continue}i.push(...dA(u,e.env))}for(let u of s)process.stdout.write(p(`could not fetch ${u}
9
+ `));if(i.length===0){process.stdout.write(`${p("no source could be read, so no skill was installed — the directory is there and empty")}
10
+ ${p("`sources update` reports why; `sources search <words>` when it works",4)}
11
+ `);return}let a=Mr(r,i);if(a.length===0){process.stdout.write(`${p(`nothing in ${i.length} skills matches those words, so none was installed`)}
12
+ ${p("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
13
+ `);return}let d=a[0],l=`${d.source}/${d.skill}`;if(process.stdout.write(`${p(`best of ${i.length}: ${l}`)}
14
+ `),a.length>1)process.stdout.write(`${p(`also matched: ${a.slice(1,1+Ur).map((u)=>`${u.source}/${u.skill}`).join(", ")}`,4)}
135
15
  `);if(process.stdout.write(`
136
- `),Se({action:"install",manifestPath:r.manifestPath,name:g,...r.env===void 0?{}:{sandboxEnv:r.env},...r.envOverlay===void 0?{}:{envOverlay:r.envOverlay}})!==n)return;let k=pi(r.manifestPath,r.envOverlay);if(k!==void 0)hi(r.manifestPath,h.skill,r.envOverlay),process.stdout.write(`
137
- ${d(`${g} was removed again: it does not load on this machine`)}
138
- ${c(k,4)}
139
- ${c("everything else is fine; `sources search` for one that needs no extra runtime",4)}
140
- `)}function mi(r,o){let a=new Map,u=o.filter((i)=>i.problem===void 0).map((i)=>{let f=`${i.source}/${i.skill}`;return a.set(f,i),{name:f,dir:i.dir,tokens:i.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:f,description:i.description,metadata:{}}}});return wt(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}function pi(r,o){try{let a=x(r,{knownProviders:Y,knownChannels:X,...o===void 0?{}:{env:{...process.env,...o}}}),u=a.manifest.skills;if(u===void 0)return;let i=H(a.manifest.model.main.id,a.manifest.model.main.capabilities);He({dir:Cr(u.dir)?u.dir:Nr(a.dir,u.dir),maxActive:u.maxActive,threshold:u.threshold,style:i.promptStyle,agentDir:a.dir,runner:O()});return}catch(a){return a instanceof t?a.message:String(a)}}function hi(r,o,a){try{let u=x(r,{knownProviders:Y,knownChannels:X,...a===void 0?{}:{env:{...process.env,...a}}}),i=u.manifest.skills;if(i===void 0)return;let f=Cr(i.dir)?i.dir:Nr(u.dir,i.dir);ci(ui(f,o),{recursive:!0,force:!0}),Ln(f,o)}catch{}}import{existsSync as gi,mkdirSync as yi,writeFileSync as wi}from"node:fs";import{dirname as bi,join as Zn,resolve as vi}from"node:path";var Sn={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",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 rt(r,o,a){let u=[];for(;;){let i=Fe(r,a);if(i===void 0)break;if(i.optional===!0){r[i.step]="";continue}if(i.fallback===""){u.push(i.step),r[i.step]="(missing)";continue}let f=Te(i.step,i.fallback);if(f.ok)r[i.step]=f.value}if(u.length>0){let i=u.map((f)=>Sn[f]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${o}), and ${u.join(", ")} ${u.length===1?"has":"have"} no default.`,hint:`Pass ${i} — 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 st(r,o){let a=r,u=ct(a.preset),i=a.apiKeyEnv??u?.apiKeyEnv,f=a.server??"local",h=a.dir??ut(a.dirChoice,a.name,o);if(h===void 0)throw new t({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(a.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:a.user,name:a.name,purpose:a.purpose,preset:a.preset,model:a.model,baseUrl:a.baseUrl,system:a.system,web:a.web,...a.webBackend===void 0?{}:{webBackend:a.webBackend},...a.webKey===void 0||a.webKey===""?{}:{webKey:a.webKey},composio:a.composio,...a.composioKey===void 0||a.composioKey===""?{}:{composioKey:a.composioKey},telegram:a.telegram,...a.telegramToken===void 0||a.telegramToken===""?{}:{telegramToken:a.telegramToken},...a.telegramAllow===void 0||a.telegramAllow===""?{}:{telegramAllow:a.telegramAllow},schedules:a.schedules??"none",server:f,skills:a.skills,...a.skillsSearch===void 0||a.skillsSearch===""?{}:{skillsSearch:a.skillsSearch},...a.skillsPick===void 0||a.skillsPick===""?{}:{skillsPick:a.skillsPick},daemon:a.daemon,...f==="local"?{serverToken:$i()}:{},...i===void 0?{}:{apiKeyEnv:i},...a.apiKey===void 0||a.apiKey===""?{}:{apiKey:a.apiKey},...a.dirChoice===void 0?{}:{dirChoice:a.dirChoice},dir:h}}function $i(){let r=new Uint8Array(32);return crypto.getRandomValues(r),[...r].map((o)=>o.toString(16).padStart(2,"0")).join("")}function ot(r,o){let a=o.map((u)=>Zn(r,u.relPath)).filter((u)=>gi(u));if(a.length>0)throw new t({code:"cli_init_target_exists",message:`${a.length} of the files init would write already exist: ${a.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 u of o){let i=Zn(r,u.relPath);yi(bi(i),{recursive:!0}),wi(i,u.contents,{encoding:"utf8",...u.relPath===".env"?{mode:384}:{}})}}var Jr=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."}]]),it=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 Qr(r){let o=Te(r.step,r.fallback);return o.ok?o.value:r.fallback}function ki(r,o){let a=it.get(r.step);return{step:r.step,prompt:r.prompt,fallback:Qr(r),optional:r.optional===!0,secret:Ct.has(r.step),...o===void 0?{}:{requires:o},...r.options===void 0?{}:{choices:r.options.filter((u)=>a?.has(u.value)!==!0).map((u)=>({value:u.value,label:u.label,...u.hint===void 0?{}:{hint:u.hint}}))}}}var Xr=64;function es(r){let o=new Map,a=new Set,u=(f,h)=>{let g={...f},v=[];for(let k=0;k<Xr;k+=1){let y=Fe(g,r);if(y===void 0)break;let S=Qr(y);if(!Jr.has(y.step)&&!o.has(y.step))o.set(y.step,ki(y,h));for(let P of y.options??[]){if(P.value===S)continue;if(it.get(y.step)?.has(P.value)===!0)continue;v.push({seed:{...g,[y.step]:P.value},opened:{step:y.step,value:P.value}})}g[y.step]=S}return v},i=[...u({})];for(let f=0;f<Xr&&i.length>0;f+=1){let h=i.splice(0,i.length);for(let g of h){let v=`${g.opened.step}=${g.opened.value}`;if(a.has(v))continue;a.add(v),i.push(...u(g.seed,g.opened))}}return[...o.values()].sort((f,h)=>Qn.indexOf(f.step)-Qn.indexOf(h.step))}function ns(r){let o={};for(let[g,v]of Object.entries(r.answers)){let k=g;if(!(k in Sn))throw new t({code:"provision_unknown_answer",message:`"${g}" 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:g});let y=Jr.get(k);if(y!==void 0)throw new t({code:y.code,message:`"${g}" cannot be set over the API.`,hint:y.hint,field:g});let S=it.get(k)?.get(v.trim().toLowerCase());if(S!==void 0)throw new t({code:S.code,message:`${g} is ${JSON.stringify(v)}, which this runtime cannot do over the API.`,hint:S.hint,field:g});let P=Te(k,v);if(!P.ok)throw new t({code:"provision_answer_invalid",message:`${g} is ${JSON.stringify(v)}, which ${P.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:g});o[k]=P.value}rt(o,"this is the provisioning API",r.defaults);let a=st(o,r.defaults),u=Pt(a.name),i=ut("sandbox",a.name,r.defaults);if(i===void 0)throw new t({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(a.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 f=vi(i),h=er({...a,dir:f});return ot(f,h),{agentId:u,dir:f,manifestPath:Zn(f,"agent.yaml"),files:h.map((g)=>g.relPath)}}function Ei(r){if(r.web!=="search")return;return cn(r.webBackend??"tavily")?.apiKeyEnv}async function ts(r){let o=await rs(r);if(o.kind==="aborted")return process.stdout.write(`nothing written
141
- `),n;return o.kind==="failed"?o.code:n}async function at(r){return rs(r)}async function rs(r){let o=Ii(r),a=ie({json:!1,plain:r.plain===!0,oneShot:!1}),u=a.mode==="rich"&&r.yes!==!0,i={agentDirBase:B()};if(u){let F=await Ti(o,i);if(F===void 0)return{kind:"aborted"};Object.assign(o,F)}else rt(o,r.yes===!0?"--yes was passed":a.because,i);let f=st(o,i),h=Pi(process.cwd(),f.dir),g=ao(h);if(g!==void 0)process.stderr.write(`${g}
142
- `);let v=xe(h,"agent.yaml"),k=er(f);ot(h,k);let y=f.apiKeyEnv,S=y!==void 0&&f.apiKey===void 0&&(process.env[y]===void 0||process.env[y]===""),P=S&&y!==void 0?{[y]:"(pending)"}:void 0,U=!1;try{let F=x(xe(h,"agent.yaml"),{knownProviders:Y,knownChannels:X,...S?{env:{...process.env,[y]:"(pending)"}}:{}}),I=H(F.manifest.model.main.id,F.manifest.model.main.capabilities),{workspace:de,warnings:oe}=We(F,I.promptStyle),ge=Ie(de,F.manifest.context.rules);if(ge!==void 0&&F.manifest.context.rules.onExceed==="fail")throw ge;U=oe.some((z)=>z.code==="soul_distilled")}catch(F){if(F instanceof t)return process.stderr.write(`init wrote ${k.length} files to ${h}, but the result does not load:
143
- ${F.format()}
144
- `),{kind:"failed",code:s};throw F}if(process.stdout.write(`wrote ${k.length} files to ${h} — validated ok
145
- `),f.skills==="find"){let F=(f.skillsPick??"").split(",").map((I)=>I.trim()).filter((I)=>I!=="");if(F.length>0)qr(F,v,{...P===void 0?{}:{envOverlay:P}});else if(!u)await Mr({answers:f,manifestPath:v,...P===void 0?{}:{envOverlay:P}})}let W=!1;if(f.daemon==="service"){process.stdout.write(`
146
- `);try{W=await Ze({action:"install",manifestPath:v})===n}catch(F){process.stderr.write(`the background service was not installed: ${F instanceof t?F.message:String(F)}
147
- `)}}return process.stdout.write(Ai(f,h,U,W)),{kind:"ok",manifestPath:xe(h,"agent.yaml")}}function Ri(r){if(r===void 0)return[];if(ft.some((o)=>o.value===r))return[["skills",r]];return[["skills","find"],["skillsSearch",r]]}function Ii(r){let o={},a=[["user",r.user],["name",r.name],["purpose",r.purpose],["preset",r.preset],["model",r.model],["baseUrl",r.baseUrl],["apiKeyEnv",r.apiKeyEnv],["system",r.system],["web",r.web],["webBackend",r.webBackend],["composio",r.composio],["telegram",r.telegram],["telegramAllow",r.telegramAllow],["server",r.server],["schedules",r.schedules],...Ri(r.skills),["daemon",r.daemon],["dir",r.dir]];for(let[u,i]of a){if(i===void 0)continue;let f=Te(u,i);if(!f.ok)throw new t({code:"cli_init_flag_invalid",message:`${Sn[u]} is ${JSON.stringify(i)}, which ${f.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."});o[u]=f.value}return o}async function Ti(r,o){let[{render:a},{createElement:u},{WizardApp:i}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-vzpbydy3.js")]),f;Wt();let h=a(u(i,{title:`${e.name} ${R}`,given:r,defaults:o,onDone:(g)=>{f=g}}),{exitOnCtrlC:!1,...Z()});return b(()=>h.unmount()),await h.waitUntilExit(),h.unmount(),f}function Ai(r,o,a,u=!1){let f=xi(o)===B()?Si(o):xe(o,"agent.yaml"),h=xe(o,"agent.yaml"),g=[];if(r.apiKeyEnv!==void 0&&r.apiKey===void 0)g.push(`Add your key: edit ${xe(o,".env")} and set ${r.apiKeyEnv}=`);let v=Ei(r);if(v!==void 0&&r.webKey===void 0)g.push(`Add your search key: edit ${xe(o,".env")} and set ${v}= — web_fetch works without it, web_search does not`);if(ht(r)&&r.composioKey===void 0)g.push(`Add your Composio key: edit ${xe(o,".env")} and set ${Nt}=`);if(r.telegram==="connected"&&r.telegramToken===void 0)g.push(`Add your bot token: message @BotFather with /newbot, then edit ${xe(o,".env")} and set ${un}=`);let k=r.telegram==="connected"||r.server==="local",y=r.telegram==="connected"&&r.server==="local"?"the Telegram bot and the HTTP API":r.telegram==="connected"?"the Telegram bot":"the HTTP API";if(k&&u)g.push(`${e.slug} run ${f} — talks to it right here. It starts no channel and binds `+`no port; ${y} belongs to the service, which is already up.`);else g.push(`${e.slug} run ${f}`);if(k){if(!u)g.push(`${e.slug} serve ${f} — starts ${y}; \`run\` starts neither`);if(r.daemon==="service"&&!u)g.push(`${e.slug} daemon install ${f} — the same thing, supervised: starts at `+"login and survives a reboot. Do this once the key and token above are in .env; the install checks them and refuses without them, on purpose.")}if(r.telegram==="connected"&&r.telegramAllow===void 0)g.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(ht(r))g.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.");g.push(r.skills==="find"?`Add more skills: \`${e.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${e.slug} skills install ${f} <source>/<skill>\`.`:r.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${e.slug} sources search <what it should do>\` searches 440+ from two catalogues.`:`Skills are off but the directory is there — \`${e.slug} sources search <what it should do>\` finds one, \`${e.slug} skills new ${f} <name>\` writes one.`),g.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${e.slug} workspace ${h}\` shows exactly what still reads as a template.`);let S=u?`
148
- it is running in the background now — \`${e.slug} daemon status ${f}\` at any time,
149
- and \`${e.slug} stop\` turns everything off.
150
- `:"";return`${a?`
16
+ `),BA({action:"install",manifestPath:e.manifestPath,name:l,...e.env===void 0?{}:{sandboxEnv:e.env},...e.envOverlay===void 0?{}:{envOverlay:e.envOverlay}})!==n)return;let g=Dr(e.manifestPath,e.envOverlay);if(g!==void 0)Hr(e.manifestPath,d.skill,e.envOverlay),process.stdout.write(`
17
+ ${f(`${l} was removed again: it does not load on this machine`)}
18
+ ${p(g,4)}
19
+ ${p("everything else is fine; `sources search` for one that needs no extra runtime",4)}
20
+ `)}function Mr(e,r){let o=new Map,i=r.filter((s)=>s.problem===void 0).map((s)=>{let a=`${s.source}/${s.skill}`;return o.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return ft(e,i).filter((s)=>s.score>0).map((s)=>o.get(s.skill.name)).filter((s)=>s!==void 0)}function Dr(e,r){try{let o=K(e,{...r===void 0?{}:{env:{...process.env,...r}}}),i=o.manifest.skills;if(i===void 0)return;let s=fe(o.manifest.model.main.id,o.manifest.model.main.capabilities);UA({dir:et(i.dir)?i.dir:rt(o.dir,i.dir),maxActive:i.maxActive,threshold:i.threshold,style:s.promptStyle,agentDir:o.dir,runner:Ae()});return}catch(o){return o instanceof t?o.message:String(o)}}function Hr(e,r,o){try{let i=K(e,{...o===void 0?{}:{env:{...process.env,...o}}}),s=i.manifest.skills;if(s===void 0)return;let a=et(s.dir)?s.dir:rt(i.dir,s.dir);Kr(Lr(a,r),{recursive:!0,force:!0}),yo(a,r)}catch{}}import{existsSync as Vr,mkdirSync as Xr,writeFileSync as zr}from"node:fs";import{dirname as Qr,join as rn,resolve as Yr}from"node:path";var Ne={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 on(e,r,o){let i=[];for(;;){let s=kA(e,o);if(s===void 0)break;if(s.optional===!0){e[s.step]="";continue}if(s.fallback===""){i.push(s.step),e[s.step]="(missing)";continue}let a=hA(s.step,s.fallback);if(a.ok)e[s.step]=a.value}if(i.length>0){let s=i.map((a)=>Ne[a]).join(", ");throw new t({code:"cli_init_missing_answers",message:`Not interactive (${r}), and ${i.join(", ")} ${i.length===1?"has":"have"} no default.`,hint:`Pass ${s} — an agent's name is not something to guess — or run the command at a terminal to be asked. Everything with a sensible default (purpose, preset, endpoint, directory) already took it.`})}}function fn(e,r){let o=e,i=Et(o.preset),s=o.apiKeyEnv??i?.apiKeyEnv,a=o.server??"local",d=o.dir??Ct(o.dirChoice,o.name,r);if(d===void 0)throw new t({code:"cli_init_no_directory",message:`The directory answer was ${JSON.stringify(o.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:o.user,name:o.name,purpose:o.purpose,preset:o.preset,model:o.model,baseUrl:o.baseUrl,system:o.system,web:o.web,...o.webBackend===void 0?{}:{webBackend:o.webBackend},...o.webKey===void 0||o.webKey===""?{}:{webKey:o.webKey},composio:o.composio,...o.composioKey===void 0||o.composioKey===""?{}:{composioKey:o.composioKey},telegram:o.telegram,...o.telegramToken===void 0||o.telegramToken===""?{}:{telegramToken:o.telegramToken},...o.telegramAllow===void 0||o.telegramAllow===""?{}:{telegramAllow:o.telegramAllow},whatsapp:o.whatsapp??"none",...o.whatsappNumber===void 0||o.whatsappNumber===""?{}:{whatsappNumber:o.whatsappNumber},schedules:o.schedules??"none",server:a,skills:o.skills,...o.skillsSearch===void 0||o.skillsSearch===""?{}:{skillsSearch:o.skillsSearch},...o.skillsPick===void 0||o.skillsPick===""?{}:{skillsPick:o.skillsPick},daemon:o.daemon,...a==="local"?{serverToken:Zr()}:{},...s===void 0?{}:{apiKeyEnv:s},...o.apiKey===void 0||o.apiKey===""?{}:{apiKey:o.apiKey},...o.dirChoice===void 0?{}:{dirChoice:o.dirChoice},dir:d}}function Zr(){let e=new Uint8Array(32);return crypto.getRandomValues(e),[...e].map((r)=>r.toString(16).padStart(2,"0")).join("")}function $e(e,r){let o=r.map((i)=>rn(e,i.relPath)).filter((i)=>Vr(i));if(o.length>0)throw new t({code:"cli_init_target_exists",message:`${o.length} of the files init would write already exist: ${o.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 r){let s=rn(e,i.relPath);Xr(Qr(s),{recursive:!0}),zr(s,i.contents,{encoding:"utf8",...i.relPath===".env"?{mode:384}:{}})}}function Ke(e,r){let o=K(e,{...r===void 0?{}:{env:{...process.env,...r}}}),i=fe(o.manifest.model.main.id,o.manifest.model.main.capabilities),{workspace:s,warnings:a}=HA(o,i.promptStyle),d=DA(s,o.manifest.context.rules);if(d!==void 0&&o.manifest.context.rules.onExceed==="fail")throw d;return{distilled:a.some((l)=>l.code==="soul_distilled")}}var ht=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."}]]),mn=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 yt(e){let r=hA(e.step,e.fallback);return r.ok?r.value:e.fallback}function eo(e,r){let o=mn.get(e.step);return{step:e.step,prompt:e.prompt,fallback:yt(e),optional:e.optional===!0,secret:Gt.has(e.step),...r===void 0?{}:{requires:r},...e.options===void 0?{}:{choices:e.options.filter((i)=>o?.has(i.value)!==!0).map((i)=>({value:i.value,label:i.label,...i.hint===void 0?{}:{hint:i.hint}}))}}}var mt=64;function wt(e){let r=new Map,o=new Set,i=(a,d)=>{let l={...a},m=[];for(let g=0;g<mt;g+=1){let u=kA(l,e);if(u===void 0)break;let h=yt(u);if(!ht.has(u.step)&&!r.has(u.step))r.set(u.step,eo(u,d));for(let y of u.options??[]){if(y.value===h)continue;if(mn.get(u.step)?.has(y.value)===!0)continue;m.push({seed:{...l,[u.step]:y.value},opened:{step:u.step,value:y.value}})}l[u.step]=h}return m},s=[...i({})];for(let a=0;a<mt&&s.length>0;a+=1){let d=s.splice(0,s.length);for(let l of d){let m=`${l.opened.step}=${l.opened.value}`;if(o.has(m))continue;o.add(m),s.push(...i(l.seed,l.opened))}}return[...r.values()].sort((a,d)=>Lo.indexOf(a.step)-Lo.indexOf(d.step))}function $t(e){let r={};for(let[l,m]of Object.entries(e.answers)){let g=l;if(!(g in Ne))throw new t({code:"provision_unknown_answer",message:`"${l}" is not a question this runtime asks.`,hint:"GET /v1/provision lists every step with its prompt, default and choices. It is generated from the same walk the terminal wizard uses, so it cannot be stale.",field:l});let u=ht.get(g);if(u!==void 0)throw new t({code:u.code,message:`"${l}" cannot be set over the API.`,hint:u.hint,field:l});let h=mn.get(g)?.get(m.trim().toLowerCase());if(h!==void 0)throw new t({code:h.code,message:`${l} is ${JSON.stringify(m)}, which this runtime cannot do over the API.`,hint:h.hint,field:l});let y=hA(g,m);if(!y.ok)throw new t({code:"provision_answer_invalid",message:`${l} is ${JSON.stringify(m)}, which ${y.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:l});r[g]=y.value}on(r,"this is the provisioning API",e.defaults);let o=fn(r,e.defaults),i=je(o.name),s=Ct("sandbox",o.name,e.defaults);if(s===void 0)throw new t({code:"provision_dir_unresolved",message:`No directory could be derived for ${JSON.stringify(o.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=Yr(s),d=Go({...o,dir:a});return $e(a,d),{agentId:i,dir:a,manifestPath:rn(a,"agent.yaml"),files:d.map((l)=>l.relPath)}}function so(e){if(e.web!=="search")return;return bn(e.webBackend??"tavily")?.apiKeyEnv}async function vt(e){let r=await St(e);if(r.kind==="aborted")return process.stdout.write(`nothing written
21
+ `),n;return r.kind==="failed"?r.code:n}async function wn(e){return St(e)}async function St(e){let r=oo(e),o=Je({json:!1,plain:e.plain===!0,oneShot:!1}),i=o.mode==="rich"&&e.yes!==!0,s={agentDirBase:le()};if(i){let v=await io(r,s);if(v===void 0)return{kind:"aborted"};Object.assign(r,v)}else on(r,e.yes===!0?"--yes was passed":o.because,s);let a=fn(r,s),d=to(process.cwd(),a.dir),l=Rr(d);if(l!==void 0)process.stderr.write(`${l}
22
+ `);let m=ee(d,"agent.yaml"),g=Go(a);$e(d,g);let u=a.apiKeyEnv,y=u!==void 0&&a.apiKey===void 0&&(process.env[u]===void 0||process.env[u]==="")&&u!==void 0?{[u]:"(pending)"}:void 0,b=!1;try{b=Ke(ee(d,"agent.yaml"),y).distilled}catch(v){if(v instanceof t)return process.stderr.write(`init wrote ${g.length} files to ${d}, but the result does not load:
23
+ ${v.format()}
24
+ `),{kind:"failed",code:c};throw v}if(process.stdout.write(`wrote ${g.length} files to ${d} — validated ok
25
+ `),a.skills==="find"){let v=(a.skillsPick??"").split(",").map((U)=>U.trim()).filter((U)=>U!=="");if(v.length>0)Er(v,m,{...y===void 0?{}:{envOverlay:y}});else if(!i)await lt({answers:a,manifestPath:m,...y===void 0?{}:{envOverlay:y}})}let R;if(a.daemon==="service"){process.stdout.write(`
26
+ `);let{outcome:v,host:U}=await cn({...e.installServer===void 0?{}:{install:e.installServer}}),k=nt(v);if(k!==void 0)process.stderr.write(k);if(U?.baseUrl!==void 0){let j=await ot(U,m);if(j.ok)R=U.baseUrl;else process.stderr.write(`pid ${U.pid} did not adopt ${je(a.name)}${j.detail===void 0?"":`: ${j.detail}`}
27
+ `)}}let w;if(a.whatsapp==="connected"&&(a.whatsappNumber??"")!==""&&i)w=R!==void 0?await ln({manifestPath:m,channelId:"wa"}):await En({manifestPath:m,dir:d,number:a.whatsappNumber??"",channelId:"wa"});if(a.whatsapp==="connected"&&w!=="paired")process.stdout.write(`
28
+ ${Ar(je(a.name))}`);return process.stdout.write(ao(a,d,b,R)),{kind:"ok",manifestPath:ee(d,"agent.yaml")}}function ro(e){if(e===void 0)return[];if(ut.some((r)=>r.value===e))return[["skills",e]];return[["skills","find"],["skillsSearch",e]]}function oo(e){let r={},o=[["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],...ro(e.skills),["daemon",e.daemon],["dir",e.dir]];for(let[i,s]of o){if(s===void 0)continue;let a=hA(i,s);if(!a.ok)throw new t({code:"cli_init_flag_invalid",message:`${Ne[i]} is ${JSON.stringify(s)}, which ${a.reason}`,hint:"The flags take the same values the interactive questions do; run the command at a terminal without flags to be walked through them."});r[i]=a.value}return r}async function io(e,r){let[{render:o},{createElement:i},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-wr1tftcr.js")]),a;yn();let d=o(i(s,{title:`${A.name} ${H}`,given:e,defaults:r,onDone:(l)=>{a=l}}),{exitOnCtrlC:!1,...Oe()});return P(()=>d.unmount()),await d.waitUntilExit(),d.unmount(),a}function ao(e,r,o,i){let s=i!==void 0,d=no(r)===le()?pn(r):ee(r,"agent.yaml"),l=ee(r,"agent.yaml"),m=[];if(e.apiKeyEnv!==void 0&&e.apiKey===void 0)m.push(`Add your key: edit ${ee(r,".env")} and set ${e.apiKeyEnv}=`);let g=so(e);if(g!==void 0&&e.webKey===void 0)m.push(`Add your search key: edit ${ee(r,".env")} and set ${g}= — web_fetch works without it, web_search does not`);if(dt(e)&&e.composioKey===void 0)m.push(`Add your Composio key: edit ${ee(r,".env")} and set ${Lt}=`);if(e.telegram==="connected"&&e.telegramToken===void 0)m.push(`Add your bot token: message @BotFather with /newbot, then edit ${ee(r,".env")} and set ${Mn}=`);let u=[...e.telegram==="connected"?["the Telegram bot"]:[],...e.whatsapp==="connected"?["WhatsApp"]:[]],h=u.length>0||e.server==="local",y=[...u,...e.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)m.push(`open ${MA(i,pn(r))} — the web UI. The service is serving `+`${pn(r)} now; ${y} ${u.length+(e.server==="local"?1:0)===1?"is":"are"} up.`),m.push(`${A.slug} run ${d} — talks to it here, attached to that same service.`);else m.push(`${A.slug} run ${d}`);if(h&&!s){if(m.push(`${A.slug} serve ${d} — starts ${y}; \`run\` starts neither`),e.daemon==="service")m.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)m.push("Message the bot. Nobody is on its allowFrom yet, so it will refuse you — and print "+"the exact line to paste into agent.yaml.");if(dt(e))m.push('Ask it for an app — "connect my Gmail" — and it finds the tools, gives you the '+"sign-in link, and pins what you need. New tools go live on the next restart.");m.push(e.skills==="find"?`Add more skills: \`${A.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${A.slug} skills install ${d} <source>/<skill>\`.`:e.skills==="starter"?`Fill in workspace-level skills/starter/SKILL.md, or take a real one — \`${A.slug} sources search <what it should do>\` searches 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 ${d} <name>\` writes one.`),m.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${A.slug} workspace ${l}\` shows exactly what still reads as a template.`);let b=s?`
29
+ it is running in the background now — \`${A.slug} status\` at any time,
30
+ \`${A.slug} restart ${d}\` after editing it, and \`${A.slug} stop\` turns everything off.
31
+ `:"";return`${o?`
151
32
  this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
152
33
  frontier-class model, and activates automatically if you upgrade.
153
- `:""}${S}
154
- `+g.map((U,W)=>` ${W+1}. ${U}
155
- `).join("")}var xn=16;function En(r=process.stdin){let o=[],a=[],u=(i)=>{let f=typeof i==="string"?i:i.toString("utf8");if(a.push(f),a.length>xn)a.splice(0,a.length-xn);if(o.push(...jo(f)),o.length>xn)o.splice(0,o.length-xn)};return r.on("data",u),{correct:(i,f)=>Bo(i,f,o),takeRaw:()=>a.shift(),close:()=>{r.off("data",u)}}}var ss=[{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 — \`${e.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 Rn(r){let o=r.TERM_PROGRAM??"";if(o==="vscode")return"vscode";if(o==="ghostty"||r.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(r.KITTY_WINDOW_ID!==void 0||r.TERM==="xterm-kitty")return"kitty";if(r.WEZTERM_PANE!==void 0)return"wezterm";if(o==="WarpTerminal")return"warp";if(o==="iTerm.app")return"iterm2";if(o==="Apple_Terminal")return"apple";return"unknown"}function In(r){return ss.find((o)=>o.id===r)}function os(){return ss}function is(r,o){return o.marker!==void 0&&r.includes(o.marker)}function as(r,o){let a=o.line;if(a===void 0)return;if(o.id!=="vscode"){let g=r.trimEnd();return g===""?`${a}
156
- `:`${g}
157
- ${a}
158
- `}let u=r.trim();if(u===""||u==="[]")return`[
159
- ${a}
34
+ `:""}${b}
35
+ `+m.map((w,v)=>` ${v+1}. ${w}
36
+ `).join("")}var Ue=16;function De(e=process.stdin){let r=[],o=[],i=(s)=>{let a=typeof s==="string"?s:s.toString("utf8");if(o.push(a),o.length>Ue)o.splice(0,o.length-Ue);if(r.push(...Jr(a)),r.length>Ue)r.splice(0,r.length-Ue)};return e.on("data",i),{correct:(s,a)=>qr(s,a,r),takeRaw:()=>o.shift(),close:()=>{e.off("data",i)}}}var At=[{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 He(e){let r=e.TERM_PROGRAM??"";if(r==="vscode")return"vscode";if(r==="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(r==="WarpTerminal")return"warp";if(r==="iTerm.app")return"iterm2";if(r==="Apple_Terminal")return"apple";return"unknown"}function We(e){return At.find((r)=>r.id===e)}function _t(){return At}function jt(e,r){return r.marker!==void 0&&e.includes(r.marker)}function Ft(e,r){let o=r.line;if(o===void 0)return;if(r.id!=="vscode"){let l=e.trimEnd();return l===""?`${o}
37
+ `:`${l}
38
+ ${o}
39
+ `}let i=e.trim();if(i===""||i==="[]")return`[
40
+ ${o}
160
41
  ]
161
- `;let i=u.indexOf("[");if(i===-1)return;let h=u.slice(i+1).trimStart().startsWith("]")?"":",";return`${u.slice(0,i+1)}
162
- ${a}${h}
163
- ${u.slice(i+1)}`}async function ds(r={}){let o=ie({plain:!1,json:!1,oneShot:!1});if(o.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 (${o.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 a=Z(r.noEnhancedKeys),u=a.kittyKeyboard!==void 0,i=Rn(process.env),f=In(i)?.name??i,[{render:h},{createElement:g},{KeyProbe:v}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-9jjeze5r.js")]),k=()=>{},y=new Promise((U)=>{k=U}),S=En();b(()=>{S.close()}),pe(),process.stdout.write(ve);let P=h(g(v,{columns:q(process.stdout.columns,j),asked:u,terminal:f,takeRaw:S.takeRaw,correctKeys:S.correct,onDone:k}),{exitOnCtrlC:!1,...a});return b(()=>P.unmount()),await y,P.unmount(),S.close(),J(),await ue(),n}import{existsSync as Oi}from"node:fs";function dt(r=process.env){return Oi("/.dockerenv")||r.container!==void 0}function _i(r){let o=r.env??process.env;if(!r.needsServer)return"command-needs-no-server";if(r.disabled===!0)return"disabled-by-flag";if(o[`${e.envPrefix}SERVICE`]!==void 0)return"is-the-service";if(o[`${e.envPrefix}NO_BOOTSTRAP`]!==void 0)return"disabled-by-env";if(dt(o))return"in-container";if(o.CI!==void 0)return"in-ci";return}async function ls(r){let o=_i(r);if(o!==void 0)return{kind:"skipped",reason:o};if((await St(r.store)).length>0)return{kind:"already"};let u=r.platform??process.platform;if(!yr(u))return{kind:"manual",lines:[`${e.slug} daemon install`]};let i=r.install;if(i===void 0)return{kind:"failed",message:"no installer was supplied",hint:"This is a wiring mistake rather than a configuration one: `ensureServer` is called with an `install` callback by `index.ts`."};try{return await i()}catch(f){return{kind:"failed",message:f instanceof Error?f.message:String(f),hint:`The command ran anyway. \`${e.slug} daemon install\` reports the same failure with more detail — on macOS over SSH it is usually that a LaunchAgent needs a logged-in desktop session.`}}}function cs(r){switch(r.kind){case"started":return`started the background server · \`${e.slug} daemon uninstall\` to undo
164
- `;case"manual":return`no server is running · ${r.lines.join(", then ")}
165
- `;case"failed":return`could not start a background server: ${r.message}
166
- hint: ${r.hint}
167
- `;default:return}}var Ci=24,gt=22;function kt(r){let o=r.args.map((a)=>{let u=a.variadic===!0?`${a.name}...`:a.name;return a.required?`<${u}>`:`[${u}]`}).join(" ");return`${e.slug} ${r.name}${o===""?"":` ${o}`}`}function fs(r){let o=r.placeholder===void 0?`--${r.name}`:`--${r.name} <${r.placeholder}>`,a=r.short===void 0?o:`-${r.short}, ${o}`,u=r.defaultHelp===void 0?"":` (default ${r.defaultHelp})`;return` ${a.padEnd(Ci)}${r.help}${u}`}var ms=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
168
- delivery reads the channel back out of the key.`;function Ni(r){let o=[];for(let a of r.args){if(a.choices===void 0||a.choices.length===0)continue;let u=Math.max(...a.choices.map((i)=>i.value.length))+2;o.push("",`${a.name}:`);for(let i of a.choices)o.push(` ${i.value.padEnd(u)}${i.help}`)}return o}function It(r){if(r!==void 0){let a=[r.summary,"","usage:",` ${kt(r)} [flags]`,...Ni(r),"","flags:",...Ot(r).map(fs)];if(r.flags.some((u)=>u.name==="session"))a.push("",ms);return`${a.join(`
42
+ `;let s=i.indexOf("[");if(s===-1)return;let d=i.slice(s+1).trimStart().startsWith("]")?"":",";return`${i.slice(0,s+1)}
43
+ ${o}${d}
44
+ ${i.slice(s+1)}`}async function Ut(e={}){let r=Je({plain:!1,json:!1,oneShot:!1});if(r.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 (${r.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 o=Oe(e.noEnhancedKeys),i=o.kittyKeyboard!==void 0,s=He(process.env),a=We(s)?.name??s,[{render:d},{createElement:l},{KeyProbe:m}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-4fp152yv.js")]),g=()=>{},u=new Promise((b)=>{g=b}),h=De();P(()=>{h.close()}),tA(),process.stdout.write(sA);let y=d(l(m,{columns:Se(process.stdout.columns,Ce),asked:i,terminal:a,takeRaw:h.takeRaw,correctKeys:h.correct,onDone:g}),{exitOnCtrlC:!1,...o});return P(()=>y.unmount()),await u,y.unmount(),h.close(),Le(),await Xe(),n}var uo=24,$n=22;function Sn(e){let r=e.args.map((o)=>{let i=o.variadic===!0?`${o.name}...`:o.name;return o.required?`<${i}>`:`[${i}]`}).join(" ");return`${A.slug} ${e.name}${r===""?"":` ${r}`}`}function Dt(e){let r=e.placeholder===void 0?`--${e.name}`:`--${e.name} <${e.placeholder}>`,o=e.short===void 0?r:`-${e.short}, ${r}`,i=e.defaultHelp===void 0?"":` (default ${e.defaultHelp})`;return` ${o.padEnd(uo-1)} ${e.help}${i}`}var Wt=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
45
+ delivery reads the channel back out of the key.`;function go(e){let r=[];for(let o of e.args){if(o.choices===void 0||o.choices.length===0)continue;let i=Math.max(...o.choices.map((s)=>s.value.length))+2;r.push("",`${o.name}:`);for(let s of o.choices)r.push(` ${s.value.padEnd(i)}${s.help}`)}return r}function xn(e){if(e!==void 0){let o=[e.summary,"","usage:",` ${Sn(e)} [flags]`,...go(e),"","flags:",...kt(e).map(Dt)];if(e.flags.some((i)=>i.name==="session"))o.push("",Wt);return`${o.join(`
169
46
  `)}
170
- `}let o=Math.max(...le.map((a)=>kt(a).length))+2;return`${[`${e.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...le.map((a)=>` ${kt(a).padEnd(o)}${a.summary}`),` ${e.slug} --version`,` ${e.slug} --help`,"",`Per-command flags: ${e.slug} <command> --help`,"","global flags:",...Rt.map(fs),"",ms,"","environment:",` ${`${e.envPrefix}BRAND`.padEnd(gt)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(gt)}set to anything to force plain output`,` ${"DEBUG".padEnd(gt)}print stack traces on failure`].join(`
47
+ `}let r=Math.max(...Ye.map((o)=>Sn(o).length))+2;return`${[`${A.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...Ye.map((o)=>` ${Sn(o).padEnd(r)}${o.summary}`),` ${A.slug} --version`,` ${A.slug} --help`,"",`Per-command flags: ${A.slug} <command> --help`,"","global flags:",...Rt.map(Dt),"",Wt,"","environment:",` ${`${A.envPrefix}BRAND`.padEnd($n)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd($n)}set to anything to force plain output`,` ${"DEBUG".padEnd($n)}print stack traces on failure`].join(`
171
48
  `)}
172
- `}var Fi=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function Li(r,o){return Fi.some((a)=>a.name===r&&o.includes(a.contains))}function ji(r){return r.execArgv.includes("--trace-warnings")||(r.nodeOptions??"").includes("--trace-warnings")}var ps;function hs(r={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(ps)return;if(ji(r))return;let o=process.emitWarning;ps=o,process.emitWarning=(a,...u)=>{let i=typeof a==="string"?Mi(u):a.name,f=typeof a==="string"?a:a.message;if(Li(i,f))return;Reflect.apply(o,process,[a,...u])}}function Mi(r){let o=r[0];return typeof o==="string"?o:"Warning"}var gs=96;async function ws(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});try{let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");if(r.action==="rebuild"){let v=await a.rebuildMemory();if(r.json===!0)return process.stdout.write(`${JSON.stringify(v,null,2)}
173
- `),n;return process.stdout.write(l([{label:"passages",value:String(v.passages)},{label:"files read",value:String(v.indexed.length)},{label:"conversations",value:v.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(v.sessions.length)},{label:"dropped",value:v.dropped.length===0?"":v.dropped.join(", ")}])),process.stdout.write(v.indexed.length===0&&v.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
174
- Read: ${[...v.indexed,...v.sessions].join(", ")}
175
- `),n}let u=r.query??"";if(u.trim()==="")return process.stderr.write(`memory search needs something to search for.
176
- `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),s;let i=await a.searchMemory({query:u,limit:r.limit??10}),f=i.hits.filter((v)=>v.score>=i.threshold),h=r.all===!0?i.hits:f;if(r.json===!0)return process.stdout.write(`${JSON.stringify({query:u,corpus:i.corpus,threshold:i.threshold,carried:i.carried??null,hits:h.map((v)=>({source:v.passage.source,at:v.passage.at,score:v.score,lexical:v.lexical,coverage:v.coverage,tokens:v.tokens,wouldInject:v.score>=i.threshold,carried:v.passage.source===i.carried,text:v.passage.text}))},null,2)}
177
- `),n;if(process.stdout.write(l([{label:"corpus",value:`${i.corpus} passage${i.corpus===1?"":"s"}`},{label:"threshold",value:i.threshold.toFixed(2)},{label:"above it",value:String(f.length)}])),i.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),n;if(h.length===0)return process.stdout.write(`
178
- Nothing ${r.all===!0?"matched":`scored above ${i.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
179
- `),n;let g=Math.max(6,...h.map((v)=>ys(v,i.carried).length));process.stdout.write(`
180
- ${$e("SCORE",6)} ${$e("LEXICAL",7)} ${$e("COVER",5)} ${$e("SOURCE",g)} ${$e("LEARNED",10)} PASSAGE
181
- `);for(let v of h){let k=v.score>=i.threshold?" ":"·";process.stdout.write(`${$e(v.score.toFixed(3),6)} ${$e(v.lexical.toFixed(3),7)} ${$e(v.coverage.toFixed(2),5)} ${$e(ys(v,i.carried),g)} ${$e(v.passage.at.slice(0,10),10)} ${k}${Ki(v.passage.text)}
182
- `)}if(r.all===!0&&f.length<h.length)process.stdout.write(`
183
- ${h.length-f.length} shown below the threshold; a turn would not inject those.
184
- `);if(i.carried!==void 0&&h.some((v)=>v.passage.source===i.carried))process.stdout.write(`
185
- ${i.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
186
- `);return n}finally{await o.stop("cli-exit")}}function Ki(r){let o=r.replace(/\s+/g," ").trim();return o.length<=gs?o:`${o.slice(0,gs-1)}…`}function $e(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function ys(r,o){return r.passage.source===o?`${r.passage.source} *`:r.passage.source}var Ui=["context_length","context_window","max_context_length","max_model_len"],Di=[["prompt_cache_hit_tokens",(r)=>r.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(r)=>{let o=r.prompt_tokens_details;return Tn(o)?o.cached_tokens:void 0}],["cache_read_input_tokens",(r)=>r.cache_read_input_tokens]];function Tn(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function Tt(r){if(typeof r!=="number"||!Number.isFinite(r))return;if(!Number.isInteger(r)||r<=0)return;return r}function bs(r,o){let a=Tn(r)?r.data:void 0,u=Array.isArray(a)?a:Array.isArray(r)?r:void 0;if(u===void 0)return;let i=o.toLowerCase();for(let f of u){if(!Tn(f))continue;let h=typeof f.id==="string"?f.id.toLowerCase():void 0;if(h===void 0)continue;if(!(h===i||h.endsWith(`/${i}`)||i.endsWith(`/${h}`)))continue;for(let v of Ui){let k=Tt(f[v]);if(k!==void 0)return{technique:"metadata",tokens:k,bound:"ceiling",detail:`GET /models published ${v}: ${k}`}}return}return}function At(r){let o=[/(?: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],a=[];for(let u of o){let i=u.exec(r);if(i?.[1]===void 0)continue;let f=Tt(Number(i[1].replaceAll(/[,_]/g,"")));if(f!==void 0)a.push(f)}if(a.length===0)return;return Math.max(...a)}function vs(r){if(!Tn(r))return;let o=Tt(r.prompt_tokens)??0;for(let[a,u]of Di){let i=u(r);if(typeof i==="number"&&Number.isFinite(i))return{cached:i,promptTokens:o,field:a}}return{cached:void 0,promptTokens:o,field:void 0}}function $s(r,o,a){if(r===void 0||o===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(o.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let u=o.cached??0;if(u>0)return{supported:!0,detail:`the second identical call reported ${u} cached of ${o.promptTokens} prompt tokens, via ${o.field}`};return{supported:!1,detail:`${o.field} came back 0 on an identical repeat of a ${a}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function en(r){let o=r.filter((u)=>u.bound==="ceiling");return(o.length>0?o:r).reduce((u,i)=>u===void 0||i.tokens>u.tokens?i:u,void 0)}function ks(r,o,a){return[" {",` pattern: "${`${r.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${o.toLocaleString("en-US").replaceAll(",","_")},`,...a===void 0?[]:[` maxOutput: ${a.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
187
- `)}function Ss(r,o,a){return`measured ${o} against ${r} — ${a}`}function xs(r,o){let a=Math.max(1,r),u=0,i=0;while(a<o)u+=a,i+=1,a*=2;return u+=o,i+=1,{requests:i,tokens:u}}var Hi=2000000000,Ps=1024,Rs=8192,Is=2097152;function Ts(r){return"context ".repeat(Math.max(1,r))}async function nn(r){let o=await r.text();try{return{text:o,json:JSON.parse(o)}}catch{return{text:o,json:void 0}}}function As(r,o){if(typeof r==="object"&&r!==null){let a=r,u=a.error;if(typeof u==="string")return u;if(typeof u==="object"&&u!==null){let i=u.message;if(typeof i==="string")return i}if(typeof a.message==="string")return a.message}return o}async function Bi(r,o,a){try{let u=await o(r.models,{headers:r.headers});if(!u.ok){a.push(`GET /models answered ${u.status}`);return}let{json:i}=await nn(u),f=bs(i,r.modelId);if(f===void 0)a.push("GET /models published no context length");return f}catch(u){a.push(`GET /models failed: ${u instanceof Error?u.message:String(u)}`);return}}async function Wi(r,o,a){try{let u=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:"hi"}],max_tokens:Hi})}),{text:i,json:f}=await nn(u);if(u.ok)return a.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 h=As(f,i.slice(0,400)),g=At(h);if(g===void 0)return a.push(`the refusal named no number: ${h.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let v=/max_?tokens/i.test(h);return{window:v?void 0:{technique:"refusal",tokens:g,bound:"ceiling",detail:`refused an over-range request naming ${g}`},outputCeiling:v?g:void 0}}catch(u){return a.push(`the over-range request failed: ${u instanceof Error?u.message:String(u)}`),{window:void 0,outputCeiling:void 0}}}async function Es(r,o,a){let u=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:a}],max_tokens:1})});if(!u.ok)return;let{json:i}=await nn(u),f=typeof i==="object"&&i!==null?i.usage:void 0;return vs(f)}async function Gi(r,o,a){let u=`${Ts(Ps)}
188
- Reply with the single character x.`;try{let i=await Es(r,o,u),f=await Es(r,o,u);return $s(i,f,Ps)}catch(i){return a.push(`the caching probe failed: ${i instanceof Error?i.message:String(i)}`),{supported:void 0,detail:"the probe did not complete"}}}async function qi(r,o,a){let u=Rs,i=0;while(u<=Is){let f;try{f=await o(r.chat,{method:"POST",headers:{"content-type":"application/json",...r.headers},body:JSON.stringify({model:r.modelId,messages:[{role:"user",content:Ts(u)}],max_tokens:1})})}catch(k){a.push(`the search stopped at ${u}: ${k instanceof Error?k.message:String(k)}`);break}if(f.ok){let{json:k}=await nn(f),y=typeof k==="object"&&k!==null?k.usage:void 0,S=typeof y==="object"&&y!==null?y.prompt_tokens:void 0;i=typeof S==="number"&&Number.isFinite(S)?S:i,u*=2;continue}let{text:h,json:g}=await nn(f),v=At(As(g,h.slice(0,400)));if(v!==void 0)return{technique:"search",tokens:v,bound:"ceiling",detail:`refused a ${u}-token prompt and named ${v}`};break}if(i===0)return;return{technique:"search",tokens:i,bound:"floor",detail:`accepted a prompt the endpoint counted at ${i} tokens; nothing above it named a number`}}function Vi(r,o){let a=en(r.findings),u=a===void 0?"nothing measured — every technique came back empty":`${a.tokens} (${a.bound}) · ${a.detail}`,i=a===void 0?"":a.tokens===r.declared?"matches what is configured":a.bound==="ceiling"&&a.tokens>r.declared?`configured value is ${r.declared}, which is ${(a.tokens-r.declared).toLocaleString("en-US")} tokens short`:`configured value is ${r.declared}`,f=r.cache.supported===void 0?`unknown — ${r.cache.detail}`:r.cache.supported?`yes — ${r.cache.detail}`:`no — ${r.cache.detail}`;return[p(` ${r.role} · ${r.modelId}`),l([{label:"endpoint",value:r.baseUrl},{label:"configured",value:`${r.declared} (${r.declaredSource})`},{label:"measured",value:u},{label:"agreement",value:i},{label:"output cap",value:r.outputCeiling===void 0?"":String(r.outputCeiling)},{label:"prompt cache",value:f},...o===void 0?[]:[{label:"price",value:`$${o}/Mtok input, as given`}]]),...r.failures.length===0?[]:[" what did not answer:",...r.failures.map((h)=>` · ${h}`)],...a===void 0||a.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",ks(r.modelId,a.tokens,r.outputCeiling).split(`
189
- `).map((h)=>` ${h}`).join(`
49
+ `}var $o=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function vo(e,r){return $o.some((o)=>o.name===e&&r.includes(o.contains))}function ko(e){return e.execArgv.includes("--trace-warnings")||(e.nodeOptions??"").includes("--trace-warnings")}var qt;function Vt(e={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(qt)return;if(ko(e))return;let r=process.emitWarning;qt=r,process.emitWarning=(o,...i)=>{let s=typeof o==="string"?xo(i):o.name,a=typeof o==="string"?o:o.message;if(vo(s,a))return;Reflect.apply(r,process,[o,...i])}}function xo(e){let r=e[0];return typeof r==="string"?r:"Warning"}var Jt=96;async function zt(e){let r=await ge.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath])});try{let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");if(e.action==="rebuild"){let m=await o.rebuildMemory();if(e.json===!0)return process.stdout.write(`${JSON.stringify(m,null,2)}
50
+ `),n;return process.stdout.write(E([{label:"passages",value:String(m.passages)},{label:"files read",value:String(m.indexed.length)},{label:"conversations",value:m.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(m.sessions.length)},{label:"dropped",value:m.dropped.length===0?"":m.dropped.join(", ")}])),process.stdout.write(m.indexed.length===0&&m.sessions.length===0?"\nNothing to index. Memory files are written by `memory_write` and by hand, and conversations are indexed at the end of each turn.\n":`
51
+ Read: ${[...m.indexed,...m.sessions].join(", ")}
52
+ `),n}let i=e.query??"";if(i.trim()==="")return process.stderr.write(`memory search needs something to search for.
53
+ `+' hint: quote a phrase — `memory search <agent> "the deploy pipeline"`. An empty query cannot rank anything, which is different from finding nothing.\n'),c;let s=await o.searchMemory({query:i,limit:e.limit??10}),a=s.hits.filter((m)=>m.score>=s.threshold),d=e.all===!0?s.hits:a;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:i,corpus:s.corpus,threshold:s.threshold,carried:s.carried??null,hits:d.map((m)=>({source:m.passage.source,at:m.passage.at,score:m.score,lexical:m.lexical,coverage:m.coverage,tokens:m.tokens,wouldInject:m.score>=s.threshold,carried:m.passage.source===s.carried,text:m.passage.text}))},null,2)}
54
+ `),n;if(process.stdout.write(E([{label:"corpus",value:`${s.corpus} passage${s.corpus===1?"":"s"}`},{label:"threshold",value:s.threshold.toFixed(2)},{label:"above it",value:String(a.length)}])),s.corpus===0)return process.stdout.write("\nNothing indexed. `memory_write` fills the carried file, and eviction moves older notes into the memory directory.\n"),n;if(d.length===0)return process.stdout.write(`
55
+ Nothing ${e.all===!0?"matched":`scored above ${s.threshold.toFixed(2)}`}. Try --all, or fewer words: a term present in more than half the corpus is dropped as uninformative.
56
+ `),n;let l=Math.max(6,...d.map((m)=>Xt(m,s.carried).length));process.stdout.write(`
57
+ ${Y("SCORE",6)} ${Y("LEXICAL",7)} ${Y("COVER",5)} ${Y("SOURCE",l)} ${Y("LEARNED",10)} PASSAGE
58
+ `);for(let m of d){let g=m.score>=s.threshold?" ":"·";process.stdout.write(`${Y(m.score.toFixed(3),6)} ${Y(m.lexical.toFixed(3),7)} ${Y(m.coverage.toFixed(2),5)} ${Y(Xt(m,s.carried),l)} ${Y(m.passage.at.slice(0,10),10)} ${g}${Ro(m.passage.text)}
59
+ `)}if(e.all===!0&&a.length<d.length)process.stdout.write(`
60
+ ${d.length-a.length} shown below the threshold; a turn would not inject those.
61
+ `);if(s.carried!==void 0&&d.some((m)=>m.passage.source===s.carried))process.stdout.write(`
62
+ ${s.carried} is carried in every prompt already, so it is searchable here and deliberately absent from the retrieved block.
63
+ `);return n}finally{await r.stop("cli-exit")}}function Ro(e){let r=e.replace(/\s+/g," ").trim();return r.length<=Jt?r:`${r.slice(0,Jt-1)}…`}function Y(e,r){return e.length>=r?e:e+" ".repeat(r-e.length)}function Xt(e,r){return e.passage.source===r?`${e.passage.source} *`:e.passage.source}var Io=["context_length","context_window","max_context_length","max_model_len"],To=[["prompt_cache_hit_tokens",(e)=>e.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(e)=>{let r=e.prompt_tokens_details;return qe(r)?r.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 An(e){if(typeof e!=="number"||!Number.isFinite(e))return;if(!Number.isInteger(e)||e<=0)return;return e}function Qt(e,r){let o=qe(e)?e.data:void 0,i=Array.isArray(o)?o:Array.isArray(e)?e:void 0;if(i===void 0)return;let s=r.toLowerCase();for(let a of i){if(!qe(a))continue;let d=typeof a.id==="string"?a.id.toLowerCase():void 0;if(d===void 0)continue;if(!(d===s||d.endsWith(`/${s}`)||s.endsWith(`/${d}`)))continue;for(let m of Io){let g=An(a[m]);if(g!==void 0)return{technique:"metadata",tokens:g,bound:"ceiling",detail:`GET /models published ${m}: ${g}`}}return}return}function On(e){let r=[/(?: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],o=[];for(let i of r){let s=i.exec(e);if(s?.[1]===void 0)continue;let a=An(Number(s[1].replaceAll(/[,_]/g,"")));if(a!==void 0)o.push(a)}if(o.length===0)return;return Math.max(...o)}function Yt(e){if(!qe(e))return;let r=An(e.prompt_tokens)??0;for(let[o,i]of To){let s=i(e);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:r,field:o}}return{cached:void 0,promptTokens:r,field:void 0}}function Zt(e,r,o){if(e===void 0||r===void 0)return{supported:void 0,detail:"no usage came back, so the question was not answered"};if(r.field===void 0)return{supported:void 0,detail:"the endpoint reported usage with no cache field in it — unknown, not absent"};let i=r.cached??0;if(i>0)return{supported:!0,detail:`the second identical call reported ${i} cached of ${r.promptTokens} prompt tokens, via ${r.field}`};return{supported:!1,detail:`${r.field} came back 0 on an identical repeat of a ${o}-token prefix — evidence of no caching, not proof: a longer prefix may still hit`}}function ve(e){let r=e.filter((i)=>i.bound==="ceiling");return(r.length>0?r:e).reduce((i,s)=>i===void 0||s.tokens>i.tokens?s:i,void 0)}function es(e,r,o){return[" {",` pattern: "${`${e.split(":")[0]}*`}",`," capabilities: {",` contextWindow: ${r.toLocaleString("en-US").replaceAll(",","_")},`,...o===void 0?[]:[` maxOutput: ${o.toLocaleString("en-US").replaceAll(",","_")},`]," // the other fields are unchanged — this row reports only what was measured"," },"," },"].join(`
64
+ `)}function ts(e,r,o){return`measured ${r} against ${e} — ${o}`}function ss(e,r){let o=Math.max(1,e),i=0,s=0;while(o<r)i+=o,s+=1,o*=2;return i+=r,s+=1,{requests:s,tokens:i}}var _o=2000000000,rs=1024,is=8192,as=2097152;function ds(e){return"context ".repeat(Math.max(1,e))}async function Ee(e){let r=await e.text();try{return{text:r,json:JSON.parse(r)}}catch{return{text:r,json:void 0}}}function ls(e,r){if(typeof e==="object"&&e!==null){let o=e,i=o.error;if(typeof i==="string")return i;if(typeof i==="object"&&i!==null){let s=i.message;if(typeof s==="string")return s}if(typeof o.message==="string")return o.message}return r}async function No(e,r,o){try{let i=await r(e.models,{headers:e.headers});if(!i.ok){o.push(`GET /models answered ${i.status}`);return}let{json:s}=await Ee(i),a=Qt(s,e.modelId);if(a===void 0)o.push("GET /models published no context length");return a}catch(i){o.push(`GET /models failed: ${i instanceof Error?i.message:String(i)}`);return}}async function jo(e,r,o){try{let i=await r(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:"hi"}],max_tokens:_o})}),{text:s,json:a}=await Ee(i);if(i.ok)return o.push("the endpoint accepted an impossible max_tokens rather than refusing it — it clamps silently, so this technique cannot measure it"),{window:void 0,outputCeiling:void 0};let d=ls(a,s.slice(0,400)),l=On(d);if(l===void 0)return o.push(`the refusal named no number: ${d.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let m=/max_?tokens/i.test(d);return{window:m?void 0:{technique:"refusal",tokens:l,bound:"ceiling",detail:`refused an over-range request naming ${l}`},outputCeiling:m?l:void 0}}catch(i){return o.push(`the over-range request failed: ${i instanceof Error?i.message:String(i)}`),{window:void 0,outputCeiling:void 0}}}async function os(e,r,o){let i=await r(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:o}],max_tokens:1})});if(!i.ok)return;let{json:s}=await Ee(i),a=typeof s==="object"&&s!==null?s.usage:void 0;return Yt(a)}async function Fo(e,r,o){let i=`${ds(rs)}
65
+ Reply with the single character x.`;try{let s=await os(e,r,i),a=await os(e,r,i);return Zt(s,a,rs)}catch(s){return o.push(`the caching probe failed: ${s instanceof Error?s.message:String(s)}`),{supported:void 0,detail:"the probe did not complete"}}}async function Ko(e,r,o){let i=is,s=0;while(i<=as){let a;try{a=await r(e.chat,{method:"POST",headers:{"content-type":"application/json",...e.headers},body:JSON.stringify({model:e.modelId,messages:[{role:"user",content:ds(i)}],max_tokens:1})})}catch(g){o.push(`the search stopped at ${i}: ${g instanceof Error?g.message:String(g)}`);break}if(a.ok){let{json:g}=await Ee(a),u=typeof g==="object"&&g!==null?g.usage:void 0,h=typeof u==="object"&&u!==null?u.prompt_tokens:void 0;s=typeof h==="number"&&Number.isFinite(h)?h:s,i*=2;continue}let{text:d,json:l}=await Ee(a),m=On(ls(l,d.slice(0,400)));if(m!==void 0)return{technique:"search",tokens:m,bound:"ceiling",detail:`refused a ${i}-token prompt and named ${m}`};break}if(s===0)return;return{technique:"search",tokens:s,bound:"floor",detail:`accepted a prompt the endpoint counted at ${s} tokens; nothing above it named a number`}}function Ho(e,r){let o=ve(e.findings),i=o===void 0?"nothing measured — every technique came back empty":`${o.tokens} (${o.bound}) · ${o.detail}`,s=o===void 0?"":o.tokens===e.declared?"matches what is configured":o.bound==="ceiling"&&o.tokens>e.declared?`configured value is ${e.declared}, which is ${(o.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[N(` ${e.role} · ${e.modelId}`),E([{label:"endpoint",value:e.baseUrl},{label:"configured",value:`${e.declared} (${e.declaredSource})`},{label:"measured",value:i},{label:"agreement",value:s},{label:"output cap",value:e.outputCeiling===void 0?"":String(e.outputCeiling)},{label:"prompt cache",value:a},...r===void 0?[]:[{label:"price",value:`$${r}/Mtok input, as given`}]]),...e.failures.length===0?[]:[" what did not answer:",...e.failures.map((d)=>` · ${d}`)],...o===void 0||o.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",es(e.modelId,o.tokens,e.outputCeiling).split(`
66
+ `).map((d)=>` ${d}`).join(`
190
67
  `)]].join(`
191
- `)}async function Os(r){let o=r.fetch??globalThis.fetch;try{let a=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),{manifest:u}=a,i=ye(u).filter((v)=>v.role===v.configuredAs),f=!1;if(r.window){let v=xs(Rs,Is),k=v.tokens*i.length,y=r.price===void 0?"":` ≈ $${(k/1e6*r.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${v.requests} requests per role, about ${k.toLocaleString("en-US")} input tokens in total${y}.
68
+ `)}async function cs(e){let r=e.fetch??globalThis.fetch;try{let o=K(e.manifestPath,{env:M([e.manifestPath])}),{manifest:i}=o,s=oA(i).filter((m)=>m.role===m.configuredAs),a=!1;if(e.window){let m=ss(is,as),g=m.tokens*s.length,u=e.price===void 0?"":` ≈ $${(g/1e6*e.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${m.requests} requests per role, about ${g.toLocaleString("en-US")} input tokens in total${u}.
192
69
  That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
193
70
  Tokens rather than dollars unless --price says otherwise: a price table in this repo would be wrong within a quarter.
194
- `),f=r.yes||await Ye("spend it?"),process.stdout.write(f?`
71
+ `),a=e.yes||await it("spend it?"),process.stdout.write(a?`
195
72
  `:`
196
73
  Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
197
74
 
198
- `)}let h=[];for(let v of i){let k=u.model[v.role]??u.model.main,y={chat:hn(k.baseUrl),models:kr(k.baseUrl),headers:Sr(k.apiKeyEnv,a.env,`model.${v.role}`),modelId:k.id},S=[],P=[],U=await Bi(y,o,S);if(U!==void 0)P.push(U);let W=await Wi(y,o,S);if(W.window!==void 0)P.push(W.window);let F=await Gi(y,o,S);if(f){let I=await qi(y,o,S);if(I!==void 0)P.push(I)}h.push({role:v.role,modelId:k.id,baseUrl:k.baseUrl,declared:v.window.contextWindow,declaredSource:v.window.source,findings:P,cache:F,outputCeiling:W.outputCeiling,failures:S})}if(r.json)return process.stdout.write(`${JSON.stringify({agent:u.id,probes:h},null,2)}
199
- `),n;let g=r.write?await Xi(a.path,h):{written:[],refused:[]};return process.stdout.write([`probed ${u.id} · ${h.length} role${h.length===1?"":"s"}`,...h.map((v)=>Vi(v,r.price)),"",...r.write?[...g.written.length===0?[]:[" written to the manifest:",...g.written.map((v)=>` ${v}`)],...g.refused.length===0?[]:[" not written:",...g.refused.map((v)=>` ${v}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Ji(h)],""].join(`
200
- `)),n}catch(a){if(a instanceof t)return process.stderr.write(`${a.format()}
201
- `),s;throw a}}async function Xi(r,o){let a=[],u=[];for(let i of o){let f=en(i.findings);if(f===void 0){u.push(`${i.role}: nothing measured`);continue}if(f.bound!=="ceiling"){u.push(`${i.role}: ${f.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(f.tokens===i.declared){u.push(`${i.role}: already ${f.tokens}, nothing to change`);continue}await pt({file:r,path:["model",i.role,"capabilities","contextWindow"],value:f.tokens}),a.push(`${i.role}: ${i.declared} → ${f.tokens}`)}return{written:a,refused:u}}function Ji(r){let o=r.filter((f)=>en(f.findings)?.bound==="ceiling");if(o.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let a=o[0],u=a===void 0?void 0:en(a.findings);if(a===void 0||u===void 0)return"";let i=new URL(a.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${u.tokens}`,` # ${Ss(i,new Date().toISOString().slice(0,10),u.detail)}`].join(`
202
- `)}async function _s(r){let o=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),store:w(),lease:!1});b(()=>o.stop("cli-exit"));let a=[...o.plugins.values()].flat();if(r.json===!0)return process.stdout.write(`${JSON.stringify({plugins:a,available:fr},null,2)}
203
- `),n;if(a.length===0)return process.stdout.write(`No plugins. This binary can resolve these by name:
75
+ `)}let d=[];for(let m of s){let g=i.model[m.role]??i.model.main,u={chat:Rn(g.baseUrl),models:Ii(g.baseUrl),headers:li(g.apiKeyEnv,o.env,`model.${m.role}`),modelId:g.id},h=[],y=[],b=await No(u,r,h);if(b!==void 0)y.push(b);let R=await jo(u,r,h);if(R.window!==void 0)y.push(R.window);let w=await Fo(u,r,h);if(a){let v=await Ko(u,r,h);if(v!==void 0)y.push(v)}d.push({role:m.role,modelId:g.id,baseUrl:g.baseUrl,declared:m.window.contextWindow,declaredSource:m.window.source,findings:y,cache:w,outputCeiling:R.outputCeiling,failures:h})}if(e.json)return process.stdout.write(`${JSON.stringify({agent:i.id,probes:d},null,2)}
76
+ `),n;let l=e.write?await Wo(o.path,d):{written:[],refused:[]};return process.stdout.write([`probed ${i.id} · ${d.length} role${d.length===1?"":"s"}`,...d.map((m)=>Ho(m,e.price)),"",...e.write?[...l.written.length===0?[]:[" written to the manifest:",...l.written.map((m)=>` ${m}`)],...l.refused.length===0?[]:[" not written:",...l.refused.map((m)=>` ${m}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[qo(d)],""].join(`
77
+ `)),n}catch(o){if(o instanceof t)return process.stderr.write(`${o.format()}
78
+ `),c;throw o}}async function Wo(e,r){let o=[],i=[];for(let s of r){let a=ve(s.findings);if(a===void 0){i.push(`${s.role}: nothing measured`);continue}if(a.bound!=="ceiling"){i.push(`${s.role}: ${a.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(a.tokens===s.declared){i.push(`${s.role}: already ${a.tokens}, nothing to change`);continue}await Fe({file:e,path:["model",s.role,"capabilities","contextWindow"],value:a.tokens}),o.push(`${s.role}: ${s.declared} → ${a.tokens}`)}return{written:o,refused:i}}function qo(e){let r=e.filter((a)=>ve(a.findings)?.bound==="ceiling");if(r.length===0)return" Nothing measured a ceiling, so there is nothing worth writing down. A floor is not a window.";let o=r[0],i=o===void 0?void 0:ve(o.findings);if(o===void 0||i===void 0)return"";let s=new URL(o.baseUrl).host;return[" --write records this. By hand, it is one line under the role, and the comment is the point:",` contextWindow: ${i.tokens}`,` # ${ts(s,new Date().toISOString().slice(0,10),i.detail)}`].join(`
79
+ `)}import{existsSync as bs,rmSync as si}from"node:fs";import{resolve as ri}from"node:path";var Vo={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function us(e){if(e===null||typeof e!=="object")return!1;let r=e.kind;return r==="network"||r==="env"||r==="fs"||r==="exec"||r==="store"}async function fs(e,r={}){let o=[],i=[],s=r.hostVersion??NA,a=(y,b,R)=>{o.push({level:"error",check:y,message:b,hint:R})},d=(y,b,R)=>{o.push({level:"warning",check:y,message:b,hint:R})};if(typeof e.name!=="string"||e.name==="")a("name","The plugin has no name.","`name` is how events, errors and `plugins` output refer to this plugin. It must be unique within a runtime.");if(Do(e.version,"*")===void 0)a("version",`\`version\` is ${JSON.stringify(e.version)}, which is not a plain semver triple.`,"Write it as `major.minor.patch`. It is reported verbatim in `plugin.loaded`, and a version nobody can compare is a version nobody can act on.");let l=Do(s,e.dispachApi);if(l===void 0)a("dispachApi",`\`dispachApi\` is ${JSON.stringify(e.dispachApi)}, which the host cannot check.`,"Supported: `*`, an exact version, `^`, `~`, space-separated comparators, and `||`. A range the host cannot parse is refused rather than assumed satisfied, so this plugin would not load.");else if(!l)d("dispachApi",`\`dispachApi\` ${e.dispachApi} does not admit this host (${s}).`,"Correct if you are testing against a host you do not support. A warning rather than an error, because running the suite on a newer host than the plugin targets is a normal thing to do.");if(e.dispachApi.trim()==="*")d("dispachApi","`dispachApi` is `*`, which accepts every host version including ones that do not exist yet.","Narrow it to the range you have actually tested. A plugin that never refuses to load is a plugin that fails at runtime instead, somewhere else, with nothing pointing back at the skew.");for(let[y,b]of(e.permissions??[]).entries())if(!us(b))a("permissions",`\`permissions[${y}]\` is not one of the declared kinds.`,"Kinds are network, env, fs, exec and store. Advisory in v1 — but authors who declare accurately before enforcement lands are the ones who will not have to scramble afterwards.");let m=r.config??{};if(e.configSchema!==void 0){let y=e.configSchema.safeParse(m);if(y.success)m=y.data;else d("configSchema","The schema refused the config this suite passed.","Pass a valid `config` through `conformance(plugin, { config })`. The default is `{}`, which a schema with required fields correctly rejects.")}let g={defineChannel:(y)=>i.push(`channel:${y}`),defineToolProvider:(y)=>i.push(`toolProvider:${y}`),defineScriptRunner:()=>i.push("scriptRunner"),use:(y)=>i.push(`middleware:${y.name}`),config:m,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Vo,events:new So({runtimeId:"conformance"})},u=performance.now();try{await e.setup(g)}catch(y){a("setup",`\`setup\` threw: ${y instanceof Error?y.message:String(y)}`,"`setup` registers capabilities and does no work, so it must succeed with an empty environment and a workspace that does not exist. Read a token in the factory you register, not here — that runs only when an agent actually uses the capability.")}let h=Math.round((performance.now()-u)*100)/100;if(h>wo)a("setup budget",`\`setup\` took ${h} ms against a ${wo} ms budget.`,"Move the work into the factory you register. A channel connects in `start()`, which runs after readiness; a provider resolves from its cache at boot and refreshes afterwards. Hard rule 4: no network I/O before `runtime.ready`.");if(i.length===0)d("setup","`setup` registered nothing.","A plugin that registers no channel, tool provider, script runner or middleware extends nothing. Every `define*` and `use` call is recorded, so registering something and still seeing this means the registration did not run — check for a branch in `setup` that skipped it.");return{ok:o.every((y)=>y.level!=="error"),findings:o,registered:i,setupMs:h,declared:{name:e.name,version:e.version,apiRange:e.dispachApi,permissions:(e.permissions??[]).filter(us)}}}import{existsSync as re,mkdirSync as Jo,readdirSync as zo,readFileSync as _n,renameSync as ms,rmSync as se,writeFileSync as Yo}from"node:fs";import{join as z}from"node:path";var ps=".origin.json";function Zo(e){let r=z(e,ps);if(!re(r))return;try{return JSON.parse(_n(r,"utf8"))}catch{return}}function Nn(e){let r=V(e),o;try{o=zo(r)}catch{return[]}let i=[];for(let s of o.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let a=z(r,s);if(!re(z(a,"package.json"))&&!re(z(a,"index.js")))continue;let d=Zo(a);i.push({name:s,dir:a,...d===void 0?{}:{origin:d}})}return i}function hs(e){let r=z(e,"package.json");if(!re(r))return z(e,"index.js");try{let o=JSON.parse(_n(r,"utf8"));if(typeof o.main==="string"&&o.main!=="")return z(e,o.main)}catch{}return z(e,"index.js")}function gs(e){let r=z(e,"package.json");if(!re(r))return;let o;try{o=JSON.parse(_n(r,"utf8"))}catch(a){return`its package.json is not valid JSON (${a instanceof Error?a.message:String(a)})`}let i=Object.keys(o.dependencies??{});if(i.length===0)return;if(re(z(e,"node_modules")))return;let s=i.slice(0,4).join(", ");return`it declares ${i.length} runtime ${i.length===1?"dependency":"dependencies"} (${s}${i.length>4?", …":""}) and ships no node_modules`}function ys(e,r){let i=((r??e).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!gt(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 ws(e,r={}){let o=r.git??ti,i=Po(e.name,r.env),s=`${i}.partial`;Jo(V(r.env),{recursive:!0}),se(s,{recursive:!0,force:!0});let a=await o(["clone","--depth","1","--single-branch",...e.ref===void 0?[]:["--branch",e.ref],e.url,s]);if(a.code!==0)throw se(s,{recursive:!0,force:!0}),ei(e,a.stderr,a.timedOut===!0);let d=await o(["rev-parse","--short","HEAD"],s),l=d.code===0?d.stdout.trim():"unknown",m=e.path===void 0?s:z(s,e.path);if(!re(m))throw se(s,{recursive:!0,force:!0}),new t({code:"plugin_path_missing",message:`${e.url} has no ${e.path} at ${l}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});se(z(m,".git"),{recursive:!0,force:!0});try{await r.inspect?.(m)}catch(u){throw se(s,{recursive:!0,force:!0}),u}if(se(i,{recursive:!0,force:!0}),m===s)ms(s,i);else ms(m,i),se(s,{recursive:!0,force:!0});let g={url:e.url,...e.ref===void 0?{}:{ref:e.ref},...e.path===void 0?{}:{path:e.path},commit:l,fetchedAt:new Date().toISOString()};return Yo(z(i,ps),`${JSON.stringify(g,null,4)}
80
+ `),{dir:i,commit:l}}function ei(e,r,o){let i=r.trim().split(`
81
+ `).slice(-3).join(" ");if(o)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 $s(e){switch(e.action){case"list":return await oi(e);case"add":return await ci(e);case"remove":return await hi(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 oi(e){let r=await ge.create({agents:[e.manifestPath],toolProviders:oe,builtInPlugins:ae,pluginRoot:V(e.env),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath]),store:G(e.env),lease:!1});P(()=>r.stop("cli-exit"));let o=[...r.plugins.values()].flat(),i=Nn(e.env);if(e.json===!0)return process.stdout.write(`${JSON.stringify({plugins:o,installed:i,available:ni},null,2)}
82
+ `),n;if(o.length===0){if(process.stdout.write(`No plugins. This binary can resolve these by name:
204
83
 
205
- ${fr.map((f)=>` - "${f}"`).join(`
84
+ ${ni.map((l)=>` - "${l}"`).join(`
206
85
  `)}
207
86
 
208
- Add a \`plugins:\` block to agent.yaml naming the ones you want.
209
- `),n;let u=a.map((f)=>({label:f.name,value:`${f.version} ${`${f.setupMs} ms`.padStart(9)}`,note:f.registered.length===0?"registered nothing":f.registered.join(", ")}));process.stdout.write(`${l(u)}
210
- `);let i=a.filter((f)=>f.permissions.length>0);if(i.length>0){process.stdout.write(`
87
+ Add a \`plugins:\` block to agent.yaml naming the ones you want, or fetch one with \`${A.slug} plugins add <agent> <repo>\`.
88
+ `),i.length>0)process.stdout.write(`
89
+ Installed in ${V(e.env)} and named by no agent:
90
+ ${i.map((l)=>` - "${l.name}"`).join(`
91
+ `)}
92
+ `);return n}let s=o.map((l)=>({label:l.name,value:`${l.version} ${`${l.setupMs} ms`.padStart(9)}`,note:`${ii(l.spec,l.lookup,i)} — ${l.registered.length===0?"registered nothing":l.registered.join(", ")}`}));process.stdout.write(`${E(s)}
93
+ `);let a=o.filter((l)=>l.permissions.length>0);if(a.length>0){process.stdout.write(`
211
94
  Declared access — advisory in v1, recorded and not enforced:
212
- `);for(let f of i)for(let h of f.permissions){let g=h.kind==="network"?h.hosts.join(", "):h.kind==="env"?h.vars.join(", "):h.kind==="fs"?`${h.paths.join(", ")} (${h.mode})`:h.kind==="exec"?h.commands.join(", "):h.tables.join(", ");process.stdout.write(` ${f.name} ${h.kind} ${g}
213
- `)}}return n}import{existsSync as sa,readdirSync as Ms,rmSync as _t,statSync as Ks}from"node:fs";import{homedir as oa}from"node:os";import{join as Us}from"node:path";function Cs(r){if(r.filesOnly||r.sharesIdWith.length===0)return[];let o=r.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${r.ref}" has the manifest id "${r.agentId}", which is also used by ${o} — 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 ${r.ref} directory and leave the store alone.`}]}function Ns(r){let o=[];if(r.running!==void 0)o.push({kind:"stop",detail:`stop pid ${r.running.pid} (${r.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!r.filesOnly&&r.service!==void 0)o.push({kind:"service",detail:`disable and unload ${r.service}`});if(!r.filesOnly){let a=r.footprint;if(o.push({kind:"store",detail:`delete ${ae(a.sessions,"conversation")}, ${ae(a.messages,"message")}, ${ae(a.passages,"memory passage")}`}),r.logs.length>0)o.push({kind:"logs",detail:`delete ${ae(r.logs.length,"log file")}`})}return o.push({kind:"directory",detail:`delete ${r.dir}`}),o}function Fs(r){let o=r.footprint,a=[{label:"directory",value:`${r.dir}`,note:`${ae(r.files.count,"file")}, ${bt(r.files.bytes)}`}];if(r.agentId!==r.ref)a.push({label:"manifest id",value:r.agentId,note:"keys the store, logs and service"});if(r.filesOnly)a.push({label:"keeping",value:`${ae(o.sessions,"conversation")}, ${ae(o.passages,"memory passage")}, and the logs`,note:"--files-only"});else a.push({label:"sessions",value:`${ae(o.sessions,"conversation")}, ${ae(o.messages,"message")}, ${ae(o.turns,"turn")}`},{label:"memory",value:`${ae(o.passages,"passage")} from ${ae(o.memorySources,"source")}`},{label:"outbox",value:o.outbox===0?"nothing queued":`${ae(o.outbox,"delivery")}${o.outboxPending===0?"":`, ${o.outboxPending} not yet sent`}`,...o.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:o.schedules===0?"none":ae(o.schedules,"schedule"),...o.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:r.logs.length===0?"none":`${ae(r.logs.length,"file")}, ${bt(r.logs.reduce((u,i)=>u+i.bytes,0))}`},{label:"service",value:r.service??"not installed"});return a.push({label:"running",value:r.running===void 0?"no":`pid ${r.running.pid} (${r.running.mode})`}),l(a)}function Ls(r){if(r.length===0)return"";return r.map((o)=>{let a=o.footprint,u=[];if(a.sessions>0)u.push(`${ae(a.sessions,"conversation")}, ${ae(a.messages,"message")}`);if(a.passages>0)u.push(`${ae(a.passages,"memory passage")}`);if(a.outbox>0)u.push(`${ae(a.outbox,"queued delivery")}`);if(a.schedules>0)u.push(`${ae(a.schedules,"schedule")}`);if(a.lease)u.push("a stale lease");if(o.logs.length>0)u.push(`${ae(o.logs.length,"log file")}, ${bt(o.logs.reduce((i,f)=>i+f.bytes,0))}`);return` ${o.agentId} ${u.length===0?"rows with no detail":u.join(" · ")}`}).join(`
214
- `)}function ae(r,o){return`${r} ${o}${r===1?"":"s"}`}import{homedir as zi}from"node:os";var js=12000,Yi=250;async function Nn(r){if(r.manifestPath!==void 0)return await Qi(r,r.manifestPath);return await Zi(r)}async function Qi(r,o){let a=ra(o),u=[];if(r.dryRun===!0){let g=await Ce(a,r.store);return process.stdout.write(`would stop 1 agent:
215
- ${d(`${a} — ${g===void 0?"not running; would be switched off for the next start":g.baseUrl===void 0?`pid ${g.pid} (${g.mode}), which serves no HTTP — would be signalled`:`pid ${g.pid} (${g.mode}) at ${g.baseUrl}, which would drop it and keep serving`}`)}
216
- `),n}await Pn(a,!1,r.reason,r.store),u.push("switched off for the next start");let i=await Ce(a,r.store),f=!0;if(i===void 0)u.push("nothing was running");else if(i.baseUrl===void 0){let g=await On(i.pid,"SIGTERM");f=g||await On(i.pid,"SIGKILL",!0),u.push(g?`pid ${i.pid} stopped cleanly`:f?`pid ${i.pid} had to be killed`:`pid ${i.pid} would not stop — check it by hand`)}else{let g=await Qe(i,`/v1/agents/${encodeURIComponent(a)}/stop`,r.reason===void 0?{}:{reason:r.reason},o);if(g.ok)u.push(`pid ${i.pid} dropped it and kept serving`);else if(g.status===409)f=!1,u.push(g.detail??"a turn is running");else if(g.status===401)f=!1,u.push(`pid ${i.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else f=!1,u.push(`pid ${i.pid} at ${i.baseUrl} could not be reached${g.detail===void 0?"":`: ${g.detail}`}`)}let h={agentId:a,service:!1,...i===void 0?{}:{pid:i.pid,mode:i.mode},stopped:f,note:u.join(" · ")};if(r.json===!0)process.stdout.write(`${JSON.stringify({stopped:[h]},null,2)}
217
- `);else process.stdout.write(`${l([{label:a,value:f?"stopped":"NOT FULLY STOPPED",note:h.note}])}
95
+ `);for(let l of a)for(let m of l.permissions)process.stdout.write(` ${l.name} ${m.kind} ${vs(m)}
96
+ `)}let d=i.filter((l)=>!o.some((m)=>m.spec===l.name));if(d.length>0)process.stdout.write(`
97
+ Also installed, named by no agent: ${d.map((l)=>l.name).join(", ")}
98
+ `);return n}function ii(e,r,o){if(r!=="installed")return r==="registry"?"built in":"imported";let i=o.find((s)=>s.name===e)?.origin;return i===void 0?"installed":`installed ${i.commit}`}function vs(e){switch(e.kind){case"network":return e.hosts.join(", ");case"env":return e.vars.join(", ");case"fs":return`${e.paths.join(", ")} (${e.mode})`;case"exec":return e.commands.join(", ");default:return e.tables.join(", ")}}async function ci(e){let r=e.rest?.[0];if(r===void 0||r==="")throw new t({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${A.slug} plugins add <agent> <owner/repo> [--ref v1.0.0]\`. A plugin is fetched with git — an owner/repo shorthand, a clone URL, the page URL you were reading (whose .../tree/<branch>/<subdir> is understood), or a local repository while you are writing one.`});let o=Qo(r)?{url:ri(r.replace(/^file:\/\//,""))}:fo(r),i=e.ref??o.ref,s=e.name===void 0?ys(o.url,o.path):ui(e.name),a=Nn(e.env).find((h)=>h.name===s);if(a?.origin!==void 0&&a.origin.url!==o.url)throw new t({code:"plugin_name_taken",message:`A different plugin is already installed as "${s}" — from ${a.origin.url}`,hint:`Two repositories cannot share one directory, and the directory name is what a manifest's \`plugins:\` entry means. Pass \`--name <name>\`, or \`${A.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${o.url}${i===void 0?"":` at ${i}`} as "${s}"…
99
+ `);let d,l=await ws({name:s,url:o.url,...i===void 0?{}:{ref:i},...o.path===void 0?{}:{path:o.path}},{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git},inspect:async(h)=>{let y=gs(h);if(y!==void 0)throw new t({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${y}`,hint:"A plugin is distributed as one self-contained bundle. Nothing is installed while this runtime runs (hard rule 5), so a declared dependency would simply be missing at boot. Ask the author to bundle their dependencies, or commit node_modules in the distribution repository."});let b=hs(h);if(!bs(b))throw new t({code:"plugin_entry_missing",message:`${s} has no entry file — ${b.slice(h.length+1)} is not in the repository`,hint:"A plugin directory is entered through the `main` its package.json names, defaulting to index.js. A distribution repository commits its built entry file; a source checkout does not, which is usually what this means."});let R=await mi(s,b);if(d=await fs(R),!d.ok)throw new t({code:"plugin_not_conformant",message:`${d.declared.name} does not meet the plugin contract:
100
+ ${d.findings.filter((w)=>w.level==="error").map((w)=>` ${w.check}: ${w.message}`).join(`
101
+ `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${A.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(Ln(H,d.declared.apiRange)!==!0)throw new t({code:"plugin_api_mismatch",message:`${d.declared.name} ${d.declared.version} supports host ${d.declared.apiRange}, and this host is ${H}`,hint:"The loader refuses this at boot, so installing it would write an entry that stops the agent starting. Look for a newer release of the plugin, or a `--ref` that matches this host."})}}),m=d?.declared;if(process.stdout.write(`
102
+ ${m?.name??s} ${m?.version??"?"} (${l.commit})
103
+ from ${o.url}${i===void 0?"":` at ${i}`}
104
+ installed ${l.dir}
105
+ host range ${m?.apiRange??"?"} — this host is ${H}
106
+ registers ${d===void 0||d.registered.length===0?"nothing":d.registered.join(", ")}
107
+ `),m!==void 0&&m.permissions.length>0)process.stdout.write(`
108
+ It declares access to:
109
+ ${m.permissions.map((h)=>` ${h.kind} ${vs(h)}`).join(`
110
+ `)}
111
+ `+"\nAdvisory only. `permissions` is recorded and enforced by nothing in v1 (decision 7.5) —\n"+`a plugin is trusted in-process code, so this list is what the author says it needs, not a
112
+ boundary. Install plugins you trust.
113
+ `);else process.stdout.write(`
114
+ It declares no access. That is not a guarantee: \`permissions\` is advisory in v1, so a
115
+ plugin that declares nothing can still do anything this process can. Install plugins you trust.
116
+ `);let g=d?.findings.filter((h)=>h.level==="warning")??[];for(let h of g)process.stdout.write(`
117
+ note: ${h.check} — ${h.message}
118
+ `);if(m!==void 0&&m.name!==s)process.stdout.write(`
119
+ note: it calls itself "${m.name}"; the \`plugins:\` entry is the directory, "${s}".
120
+ `);let u=await pi(e.manifestPath,s);return process.stdout.write(u==="already"?`
121
+ ${e.manifestPath} already names "${s}".
122
+ `:`
123
+ Added "${s}" to the plugins: block in ${e.manifestPath}.
124
+ It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
125
+ `),n}function ui(e){if(gt(e))return e;throw new t({code:"plugin_name_invalid",message:`--name ${JSON.stringify(e)} is not a usable plugin directory name`,hint:"Lowercase letters, digits and single hyphens. That segment is what the manifest's `plugins:` entry names, so it has to be a directory name and a YAML scalar at once."})}async function mi(e,r){let o;try{o=await import(r)}catch(s){throw new t({code:"plugin_import_failed",message:`${e}: ${r} could not be imported — ${s instanceof Error?s.message:String(s)}`,hint:"A plugin is one self-contained ES module. A bare `require` or an unresolved import is what this usually means, and neither can be fixed by installing anything: nothing is installed while this runtime runs. Nothing was installed.",cause:s})}let i=o.default;if(i===null||typeof i!=="object")throw new t({code:"plugin_malformed",message:`${e}: ${r} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${A.slug}Api\` host range and \`setup\`. A named export is not searched for and a factory function is not called, because a wrong guess produces a plugin that registers nothing and reports success.`});if(typeof i.setup!=="function")throw new t({code:"plugin_malformed",message:`${e}: the default export of ${r} has no \`setup\` function`,hint:"`setup(context)` is the whole extension surface — it registers channels, tool providers, a script runner or middleware, and does no work."});return i}async function pi(e,r){let i=L(e).plugins??[];if(i.some((a)=>(typeof a==="string"?a:a.spec)===r))return"already";return await Fe({file:e,path:["plugins"],value:[...i.map((a)=>typeof a==="string"?a:a.spec),r]}),"written"}async function hi(e){let r=e.rest?.[0];if(r===void 0||r==="")throw new t({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${A.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let i=(L(e.manifestPath).plugins??[]).map((d)=>typeof d==="string"?d:d.spec);if(i.includes(r))await Fe({file:e.manifestPath,path:["plugins"],value:i.filter((d)=>d!==r)}),process.stdout.write(`Dropped "${r}" from ${e.manifestPath}.
126
+ Run \`${A.slug} validate ${e.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
127
+ `);else process.stdout.write(`${e.manifestPath} does not name "${r}".
128
+ `);let s=Po(r,e.env);if(!bs(s))return process.stdout.write(`Nothing installed at ${s}.
129
+ `),n;let a=gi(r,e.manifestPath,e.env);if(a.length>0)return process.stdout.write(`Kept ${s} — still named by ${a.join(", ")}.
130
+ Remove it from those agents first, or delete the directory by hand.
131
+ `),n;return si(s,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${s}.
132
+ `),n}function gi(e,r,o){let i=[];for(let s of X(o)){if(s.manifestPath===r)continue;try{if((L(s.manifestPath).plugins??[]).map((l)=>typeof l==="string"?l:l.spec).includes(e))i.push(s.ref)}catch{}}return i}import{existsSync as Ti,readdirSync as Rs,rmSync as jn,statSync as Is}from"node:fs";import{homedir as Oi}from"node:os";import{join as Ts}from"node:path";function ks(e){if(e.filesOnly||e.sharesIdWith.length===0)return[];let r=e.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${e.ref}" has the manifest id "${e.agentId}", which is also used by ${r} — 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 Ss(e){let r=[];if(e.running!==void 0)r.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)r.push({kind:"service",detail:`disable and unload ${e.service}`});if(!e.filesOnly){let o=e.footprint;if(r.push({kind:"store",detail:`delete ${W(o.sessions,"conversation")}, ${W(o.messages,"message")}, ${W(o.passages,"memory passage")}`}),e.logs.length>0)r.push({kind:"logs",detail:`delete ${W(e.logs.length,"log file")}`})}return r.push({kind:"directory",detail:`delete ${e.dir}`}),r}function Es(e){let r=e.footprint,o=[{label:"directory",value:`${e.dir}`,note:`${W(e.files.count,"file")}, ${KA(e.files.bytes)}`}];if(e.agentId!==e.ref)o.push({label:"manifest id",value:e.agentId,note:"keys the store, logs and service"});if(e.filesOnly)o.push({label:"keeping",value:`${W(r.sessions,"conversation")}, ${W(r.passages,"memory passage")}, and the logs`,note:"--files-only"});else o.push({label:"sessions",value:`${W(r.sessions,"conversation")}, ${W(r.messages,"message")}, ${W(r.turns,"turn")}`},{label:"memory",value:`${W(r.passages,"passage")} from ${W(r.memorySources,"source")}`},{label:"outbox",value:r.outbox===0?"nothing queued":`${W(r.outbox,"delivery")}${r.outboxPending===0?"":`, ${r.outboxPending} not yet sent`}`,...r.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:r.schedules===0?"none":W(r.schedules,"schedule"),...r.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:e.logs.length===0?"none":`${W(e.logs.length,"file")}, ${KA(e.logs.reduce((i,s)=>i+s.bytes,0))}`},{label:"service",value:e.service??"not installed"});return o.push({label:"running",value:e.running===void 0?"no":`pid ${e.running.pid} (${e.running.mode})`}),E(o)}function xs(e){if(e.length===0)return"";return e.map((r)=>{let o=r.footprint,i=[];if(o.sessions>0)i.push(`${W(o.sessions,"conversation")}, ${W(o.messages,"message")}`);if(o.passages>0)i.push(`${W(o.passages,"memory passage")}`);if(o.outbox>0)i.push(`${W(o.outbox,"queued delivery")}`);if(o.schedules>0)i.push(`${W(o.schedules,"schedule")}`);if(o.lease)i.push("a stale lease");if(r.logs.length>0)i.push(`${W(r.logs.length,"log file")}, ${KA(r.logs.reduce((s,a)=>s+a.bytes,0))}`);return` ${r.agentId} ${i.length===0?"rows with no detail":i.join(" · ")}`}).join(`
133
+ `)}function W(e,r){return`${e} ${r}${e===1?"":"s"}`}import{homedir as wi}from"node:os";var Ps=12000,bi=250;async function Ve(e){if(e.manifestPath!==void 0)return await vi(e,e.manifestPath);return await ki(e)}async function vi(e,r){let o=Ri(r),i=[];if(e.dryRun===!0){let l=await ke(o,e.store);return process.stdout.write(`would stop 1 agent:
134
+ ${f(`${o} — ${l===void 0?"not running; would be switched off for the next start":l.baseUrl===void 0?`pid ${l.pid} (${l.mode}), which serves no HTTP — would be signalled`:`pid ${l.pid} (${l.mode}) at ${l.baseUrl}, which would drop it and keep serving`}`)}
135
+ `),n}await Bo(o,!1,e.reason,e.store),i.push("switched off for the next start");let s=await ke(o,e.store),a=!0;if(s===void 0)i.push("nothing was running");else if(s.baseUrl===void 0){let l=await Be(s.pid,"SIGTERM");a=l||await Be(s.pid,"SIGKILL",!0),i.push(l?`pid ${s.pid} stopped cleanly`:a?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let l=await ze(s,`/v1/agents/${encodeURIComponent(o)}/stop`,e.reason===void 0?{}:{reason:e.reason},r);if(l.ok)i.push(`pid ${s.pid} dropped it and kept serving`);else if(l.status===409)a=!1,i.push(l.detail??"a turn is running");else if(l.status===401)a=!1,i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else a=!1,i.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${l.detail===void 0?"":`: ${l.detail}`}`)}let d={agentId:o,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:a,note:i.join(" · ")};if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:[d]},null,2)}
136
+ `);else process.stdout.write(`${E([{label:o,value:a?"stopped":"NOT FULLY STOPPED",note:d.note}])}
218
137
  `),process.stdout.write(`
219
- Stays off across restarts. \`${e.slug} start ${a}\` switches it back on.
220
- `);return f?n:s}async function Zi(r){let o=r.platform??process.platform,a=o==="darwin"?Ue(o,{home:zi(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}}):void 0,u=await ea(a,r.store);if(u.length===0)return process.stdout.write(r.json===!0?`${JSON.stringify({stopped:[]})}
138
+ Stays off across restarts. \`${A.slug} start ${o}\` switches it back on.
139
+ `);return a?n:c}async function ki(e){let r=e.platform??process.platform,o=r==="darwin"?Mt(r,{home:wi(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}}):void 0,i=await Si(o,e.store);if(i.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({stopped:[]})}
221
140
  `:`Nothing is running — no service is installed and no process holds an agent.
222
- `),n;if(r.dryRun===!0)return process.stdout.write(`would stop ${u.length} ${u.length===1?"agent":"agents"}:
223
- ${u.map((f)=>d(ta(f))).join(`
141
+ `),n;if(e.dryRun===!0)return process.stdout.write(`would stop ${i.length} ${i.length===1?"agent":"agents"}:
142
+ ${i.map((a)=>f(Pi(a))).join(`
224
143
  `)}
225
- `),n;let i=[];for(let f of u)i.push(await na(f,a));if(r.json===!0)process.stdout.write(`${JSON.stringify({stopped:i},null,2)}
226
- `);else{let f=i.map((h)=>({label:h.agentId,value:h.stopped?"stopped":"STILL RUNNING",note:h.note}));if(process.stdout.write(`${l(f)}
227
- `),i.some((h)=>h.service&&h.stopped))process.stdout.write(`
144
+ `),n;let s=[];for(let a of i)s.push(await xi(a,o));if(e.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
145
+ `);else{let a=s.map((d)=>({label:d.agentId,value:d.stopped?"stopped":"STILL RUNNING",note:d.note}));if(process.stdout.write(`${E(a)}
146
+ `),s.some((d)=>d.service&&d.stopped))process.stdout.write(`
228
147
  Services are disabled as well as unloaded, so they stay stopped across a reboot.
229
- Start one again with \`${e.slug} daemon start <agent>\`.
230
- `);if(i.some((h)=>h.forced===!0))process.stdout.write(`
148
+ Start one again with \`${A.slug} daemon start <agent>\`.
149
+ `);if(s.some((d)=>d.forced===!0))process.stdout.write(`
231
150
  Something had to be killed rather than asked. A forced stop skips the runtime's own
232
151
  cleanup, so a command the agent had left running in the background may still be alive —
233
152
  \`ps\` will show it if so.
234
- `)}return i.every((f)=>f.stopped)?n:s}async function ea(r,o){let a=`${e.slug}.agent.`,u=new Map;for(let i of r?.labels(a)??[]){let f=i.slice(a.length);u.set(f,{agentId:f,service:!0})}try{let i=await M.open({path:o??w()});for(let f of await i.leases.all()){if(f.pid===process.pid||!_(f.pid))continue;u.set(f.agentId,{agentId:f.agentId,service:u.get(f.agentId)?.service===!0,pid:f.pid,mode:f.mode})}await i.close()}catch{}return[...u.values()].sort((i,f)=>i.agentId.localeCompare(f.agentId))}async function na(r,o){let a=[];if(r.service&&o!==void 0)try{o.stop(pn(e.slug,r.agentId)),a.push("service disabled and unloaded")}catch(f){a.push(`service could not be unloaded: ${f instanceof Error?f.message:String(f)}`)}if(r.pid===void 0)return{...r,stopped:!0,note:a.join(" · ")||"no process was running"};if(!_(r.pid))return{...r,stopped:!0,note:a.join(" · ")||`pid ${r.pid} exited`};if(await On(r.pid,"SIGTERM"))return a.push(`pid ${r.pid} stopped cleanly`),{...r,stopped:!0,note:a.join(" · ")};let i=await On(r.pid,"SIGKILL",!0);return a.push(i?`pid ${r.pid} did not stop in ${Math.round(js/1000)}s and was killed`:`pid ${r.pid} would not stop, even killed — check it by hand`),{...r,stopped:i,forced:!0,note:a.join(" · ")}}async function On(r,o,a=!1){try{process.kill(a?-r:r,o)}catch(i){if(i.code==="ESRCH")return!0;if(a)try{process.kill(r,o)}catch{return!_(r)}}let u=Date.now()+(o==="SIGKILL"?3000:js);while(Date.now()<u){if(!_(r))return!0;await new Promise((i)=>setTimeout(i,Yi))}return!_(r)}function ta(r){let o=[];if(r.service)o.push("background service");if(r.pid!==void 0)o.push(`pid ${r.pid}${r.mode===void 0?"":` (${r.mode})`}`);return`${r.agentId} — ${o.join(", ")}`}function ra(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_stop_agent_id_missing",message:`${r} declares no id, so there is nothing to match a running agent against.`,hint:`Add \`id: <name>\` to the manifest, or run \`${e.slug} stop\` with no argument to stop everything.`});return o.id}async function Ds(r){let o=await M.open({path:r.store??w()});try{if(r.prune===!0)return await da(r,o);if(r.all===!0)return await aa(r,o);if(r.ref===void 0)throw new t({code:"cli_remove_needs_agent",message:"remove needs an agent.",hint:`\`${e.slug} remove <name>\` takes a sandbox agent's name — the ones \`${e.slug} run\` lists. \`--prune\` clears data no agent claims; \`--all\` removes every agent.`});return await ia(r.ref,r,o)}finally{await o.close()}}async function ia(r,o,a){let u=await Bs(r,o,a),i=Cs(u);if(i.length>0){let g=i[0];throw new t({code:g.code,message:g.message,hint:g.hint})}let f=Ns(u),h=`${p(`removing ${r} will:`,!0)}
235
- ${Fs(u)}
153
+ `)}return s.every((a)=>a.stopped)?n:c}async function Si(e,r){let o=`${A.slug}.agent.`,i=new Map;for(let s of e?.labels(o)??[]){let a=s.slice(o.length);i.set(a,{agentId:a,service:!0})}try{let s=await ie.open({path:r??G()});for(let a of await s.leases.all()){if(a.pid===process.pid||!J(a.pid))continue;i.set(a.agentId,{agentId:a.agentId,service:i.get(a.agentId)?.service===!0,pid:a.pid,mode:a.mode})}await s.close()}catch{}return[...i.values()].sort((s,a)=>s.agentId.localeCompare(a.agentId))}async function xi(e,r){let o=[];if(e.service&&r!==void 0)try{r.stop(lo(A.slug,e.agentId)),o.push("service disabled and unloaded")}catch(a){o.push(`service could not be unloaded: ${a instanceof Error?a.message:String(a)}`)}if(e.pid===void 0)return{...e,stopped:!0,note:o.join(" · ")||"no process was running"};if(!J(e.pid))return{...e,stopped:!0,note:o.join(" · ")||`pid ${e.pid} exited`};if(await Be(e.pid,"SIGTERM"))return o.push(`pid ${e.pid} stopped cleanly`),{...e,stopped:!0,note:o.join(" · ")};let s=await Be(e.pid,"SIGKILL",!0);return o.push(s?`pid ${e.pid} did not stop in ${Math.round(Ps/1000)}s and was killed`:`pid ${e.pid} would not stop, even killed — check it by hand`),{...e,stopped:s,forced:!0,note:o.join(" · ")}}async function Be(e,r,o=!1){try{process.kill(o?-e:e,r)}catch(s){if(s.code==="ESRCH")return!0;if(o)try{process.kill(e,r)}catch{return!J(e)}}let i=Date.now()+(r==="SIGKILL"?3000:Ps);while(Date.now()<i){if(!J(e))return!0;await new Promise((s)=>setTimeout(s,bi))}return!J(e)}function Pi(e){let r=[];if(e.service)r.push("background service");if(e.pid!==void 0)r.push(`pid ${e.pid}${e.mode===void 0?"":` (${e.mode})`}`);return`${e.agentId} — ${r.join(", ")}`}function Ri(e){let r=L(e);if(r.id===void 0||r.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 r.id}async function As(e){let r=await ie.open({path:e.store??G()});try{if(e.prune===!0)return await Ni(e,r);if(e.all===!0)return await Ci(e,r);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 _i(e.ref,e,r)}finally{await r.close()}}async function _i(e,r,o){let i=await _s(e,r,o),s=ks(i);if(s.length>0){let l=s[0];throw new t({code:l.code,message:l.message,hint:l.hint})}let a=Ss(i),d=`${N(`removing ${e} will:`,!0)}
154
+ ${Es(i)}
236
155
 
237
- ${f.map((g)=>d(g.detail)).join(`
156
+ ${a.map((l)=>f(l.detail)).join(`
238
157
  `)}
239
- `;if(o.dryRun===!0)return process.stdout.write(o.json===!0?`${JSON.stringify({ref:r,agentId:u.agentId,steps:f,footprint:u.footprint},null,2)}
240
- `:`${h}
158
+ `;if(r.dryRun===!0)return process.stdout.write(r.json===!0?`${JSON.stringify({ref:e,agentId:i.agentId,steps:a,footprint:i.footprint},null,2)}
159
+ `:`${d}
241
160
  Nothing was deleted — this was --dry-run.
242
- `),n;if(process.stdout.write(h),!await Ft(o,r,"type the agent's name to confirm:"))return process.stdout.write(`
161
+ `),n;if(process.stdout.write(d),!await Kn(r,e,"type the agent's name to confirm:"))return process.stdout.write(`
243
162
  Nothing was deleted.
244
- `),n;return await Hs(u,o,a)}async function Hs(r,o,a){let u=[];if(r.running!==void 0||!r.filesOnly&&r.service!==void 0){if(await Nn({manifestPath:r.manifestPath,...o.exec===void 0?{}:{exec:o.exec},...o.platform===void 0?{}:{platform:o.platform}})!==n)return process.stderr.write(`
245
- Stopping ${r.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
246
- hint: check what is still running with \`${e.slug} stop --dry-run\`, then run remove again.
247
- `),s;u.push({label:"stopped",value:r.ref})}if(!r.filesOnly&&r.service!==void 0){let i=Ws(o);try{i?.uninstall(r.service),u.push({label:"service",value:`${r.service} removed`})}catch(f){u.push({label:"service",value:`${r.service} could NOT be removed`,note:f instanceof Error?f.message:String(f)})}}if(!r.filesOnly){let i=await a.purgeAgent(r.agentId);u.push({label:"store",value:`${i.sessions} conversation(s), ${i.messages} message(s), ${i.passages} passage(s)`});for(let f of r.logs)_t(f.path,{force:!0});if(r.logs.length>0)u.push({label:"logs",value:`${r.logs.length} file(s)`})}if(_t(r.dir,{recursive:!0,force:!0}),u.push({label:"directory",value:r.dir}),o.json===!0)return process.stdout.write(`${JSON.stringify({removed:r.ref,agentId:r.agentId,filesOnly:r.filesOnly},null,2)}
163
+ `),n;return await Os(i,r,o)}async function Os(e,r,o){let i=[];if(e.running!==void 0||!e.filesOnly&&e.service!==void 0){if(await Ve({manifestPath:e.manifestPath,...r.exec===void 0?{}:{exec:r.exec},...r.platform===void 0?{}:{platform:r.platform}})!==n)return process.stderr.write(`
164
+ Stopping ${e.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
165
+ hint: check what is still running with \`${A.slug} stop --dry-run\`, then run remove again.
166
+ `),c;i.push({label:"stopped",value:e.ref})}if(!e.filesOnly&&e.service!==void 0){let s=Cs(r);try{s?.uninstall(e.service),i.push({label:"service",value:`${e.service} removed`})}catch(a){i.push({label:"service",value:`${e.service} could NOT be removed`,note:a instanceof Error?a.message:String(a)})}}if(!e.filesOnly){let s=await o.purgeAgent(e.agentId);i.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let a of e.logs)jn(a.path,{force:!0});if(e.logs.length>0)i.push({label:"logs",value:`${e.logs.length} file(s)`})}if(jn(e.dir,{recursive:!0,force:!0}),i.push({label:"directory",value:e.dir}),r.json===!0)return process.stdout.write(`${JSON.stringify({removed:e.ref,agentId:e.agentId,filesOnly:e.filesOnly},null,2)}
248
167
  `),n;if(process.stdout.write(`
249
- ${r.ref} removed.
250
- ${l(u)}
251
- `),r.filesOnly)process.stdout.write(`
252
- Its sessions and memory are still in the store under the id "${r.agentId}", which another agent shares.
253
- `);return n}async function aa(r,o){let a=K();if(a.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
254
- `),n;if(process.stdout.write(`${p(`removing every agent in ${B()}:`,!0)}
255
- ${a.map((i)=>d(`${i.ref}${i.id===void 0||i.id===i.ref?"":` (id ${i.id})`}`)).join(`
168
+ ${e.ref} removed.
169
+ ${E(i)}
170
+ `),e.filesOnly)process.stdout.write(`
171
+ Its sessions and memory are still in the store under the id "${e.agentId}", which another agent shares.
172
+ `);return n}async function Ci(e,r){let o=X();if(o.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
173
+ `),n;if(process.stdout.write(`${N(`removing every agent in ${le()}:`,!0)}
174
+ ${o.map((s)=>f(`${s.ref}${s.id===void 0||s.id===s.ref?"":` (id ${s.id})`}`)).join(`
256
175
  `)}
257
- `),r.dryRun===!0)return process.stdout.write(`
176
+ `),e.dryRun===!0)return process.stdout.write(`
258
177
  Nothing was deleted — this was --dry-run.
259
- `),n;if(!await Ft(r,"all",`type \`all\` to remove all ${a.length}:`))return process.stdout.write(`
178
+ `),n;if(!await Kn(e,"all",`type \`all\` to remove all ${o.length}:`))return process.stdout.write(`
260
179
  Nothing was deleted.
261
- `),n;let u=n;for(let i of a){let f=await Bs(i.ref,r,o),h=await Hs({...f,sharesIdWith:[]},r,o);if(h!==n)u=h}return u}async function da(r,o){let a=new Set(K().map((h)=>h.id??h.ref).filter((h)=>h!=="")),u=new Set((await o.agentIds()).filter((h)=>!a.has(h)));for(let h of ca())if(!a.has(h))u.add(h);let i=[];for(let h of[...u].sort())i.push({agentId:h,footprint:await o.agentFootprint(h),logs:Gs(h)});if(i.length===0)return process.stdout.write(r.json===!0?`${JSON.stringify({pruned:[]})}
262
- `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${B()}.
263
- `),n;if(process.stdout.write(`${p("no sandbox directory claims these:",!0)}
264
- ${Ls(i)}
265
- `),r.dryRun===!0)return process.stdout.write(`
180
+ `),n;let i=n;for(let s of o){let a=await _s(s.ref,e,r),d=await Os({...a,sharesIdWith:[]},e,r);if(d!==n)i=d}return i}async function Ni(e,r){let o=new Set(X().map((d)=>d.id??d.ref).filter((d)=>d!=="")),i=new Set((await r.agentIds()).filter((d)=>!o.has(d)));for(let d of Ki())if(!o.has(d))i.add(d);let s=[];for(let d of[...i].sort())s.push({agentId:d,footprint:await r.agentFootprint(d),logs:Ns(d)});if(s.length===0)return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:[]})}
181
+ `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${le()}.
182
+ `),n;if(process.stdout.write(`${N("no sandbox directory claims these:",!0)}
183
+ ${xs(s)}
184
+ `),e.dryRun===!0)return process.stdout.write(`
266
185
  Nothing was deleted — this was --dry-run.
267
- `),n;if(!await Ft(r,"prune","type `prune` to delete them:"))return process.stdout.write(`
186
+ `),n;if(!await Kn(e,"prune","type `prune` to delete them:"))return process.stdout.write(`
268
187
  Nothing was deleted.
269
- `),n;let f=[];for(let h of i){let g=await o.purgeAgent(h.agentId);for(let v of h.logs)_t(v.path,{force:!0});f.push({label:h.agentId,value:`${g.sessions} conversation(s), ${g.passages} passage(s), ${h.logs.length} log file(s)`})}return process.stdout.write(r.json===!0?`${JSON.stringify({pruned:i.map((h)=>h.agentId)},null,2)}
188
+ `),n;let a=[];for(let d of s){let l=await r.purgeAgent(d.agentId);for(let m of d.logs)jn(m.path,{force:!0});a.push({label:d.agentId,value:`${l.sessions} conversation(s), ${l.passages} passage(s), ${d.logs.length} log file(s)`})}return process.stdout.write(e.json===!0?`${JSON.stringify({pruned:s.map((d)=>d.agentId)},null,2)}
270
189
  `:`
271
- pruned ${i.length} agent id(s).
272
- ${l(f)}
273
- `),n}async function Bs(r,o,a){if(r.includes("/")||r.endsWith(".yaml")||r.endsWith(".yml"))throw new t({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${r}" is a path.`,hint:`An agent outside ${B()} is a directory you created and yours to delete — \`rm -rf\` it. This command only removes agents \`${e.slug} init\` made, because it also has to clear their sessions, memory, logs and service.`});let u=K(),i=u.find((P)=>P.ref===r);if(i===void 0){let P=u.map((U)=>U.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${r}" in the sandbox${P.length===0?", which is empty":""}.`,hint:P.length===0?`Nothing to remove. \`${e.slug} init\` creates one.`:`Known agents: ${P.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let f=i.id;if(f===void 0)try{f=T(i.manifestPath).id}catch{}let h=o.filesOnly===!0||f===void 0,g=f??r,v=await a.agentFootprint(g),k=v.lease?await a.leases.get(g):void 0,y=Ws(o),S=pn(e.slug,g);return{ref:r,agentId:g,manifestPath:i.manifestPath,dir:i.dir,files:la(i.dir),footprint:v,logs:Gs(g),sharesIdWith:u.filter((P)=>P.ref!==r&&(P.id??"")===g).map((P)=>P.ref),...k!==void 0&&_(k.pid)?{running:{pid:k.pid,mode:k.mode}}:{},...y?.state(S).installed===!0?{service:S}:{},filesOnly:h}}function Ws(r){let o=r.platform??process.platform;if(o!=="darwin")return;return Ue(o,{home:oa(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}})}function la(r){let o=0,a=0,u=(i)=>{let f;try{f=Ms(i)}catch{return}for(let h of f){let g=Us(i,h);try{let v=Ks(g);if(v.isDirectory()){u(g);continue}o+=1,a+=v.size}catch{}}};return u(r),{count:o,bytes:a}}function Gs(r){let o=Jt(r),a=[];for(let u of[o.out,o.err])try{if(!sa(u))continue;a.push({path:u,bytes:Ks(u).size})}catch{}return a}function ca(){let r;try{r=Ms(Us(ee(),"logs"))}catch{return[]}let o=new Set;for(let a of r)for(let u of[".out.log",".err.log"])if(a.endsWith(u))o.add(a.slice(0,-u.length));return[...o]}async function Ft(r,o,a){if(r.yes===!0)return!0;let u=r.confirm;if(u===void 0)return!1;return await u(a,o)}import{randomBytes as jt}from"node:crypto";import{existsSync as wa}from"node:fs";import{createInterface as Zs}from"node:readline";class Oe extends Error{code;hint;field;status;request;constructor(r,o={}){super(r.hint===void 0?r.message:`${r.message}
274
- hint: ${r.hint}`);if(this.name="DispachError",this.code=r.code,this.hint=r.hint??"",this.field=r.field,this.status=o.status,this.request=o.method===void 0||o.path===void 0?void 0:{method:o.method,path:o.path},o.cause!==void 0)this.cause=o.cause}}function ua(r,o){let a=r instanceof Error?r.message:String(r);return new Oe({code:"transport_failed",message:`${o.method} ${o.path} did not reach ${o.baseUrl}: ${a}`,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."},{...o,cause:r})}async function fa(r,o){let a;try{let u=await r.json();if(typeof u.error?.code==="string"&&typeof u.error.message==="string")a={code:u.error.code,message:u.error.message,...u.error.hint===void 0?{}:{hint:u.error.hint},...u.error.field===void 0?{}:{field:u.error.field}}}catch{}return new Oe(a??{code:`http_${r.status}`,message:`${o.method} ${o.path} returned ${r.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:r.status,...o})}var qs=new Set(Me);async function*Vs(r){for await(let o of Fn(ma(r))){if(o.event===void 0||o.data==="")continue;let a;try{a=JSON.parse(o.data)}catch{continue}yield{name:o.event,data:a}}}async function*ma(r){let o=r.getReader();try{while(!0){let{done:a,value:u}=await o.read();if(a)return;if(u!==void 0)yield u}}finally{o.releaseLock()}}async function*pa(r){for await(let{name:o,data:a}of Vs(r)){if(qs.has(o)){yield{kind:"event",event:a};continue}let u=a??{};switch(o){case"turn.accepted":yield{kind:"accepted",turnId:String(u.turnId??""),sessionKey:String(u.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:u.state==="ended"?"ended":"running",events:Number(u.events??0),truncated:u.truncated===!0,dropped:Number(u.dropped??0),chunks:u.chunks==="start"||u.chunks==="partial"?u.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(u.turnId??""),status:String(u.status??"unknown"),steps:typeof u.steps==="number"?u.steps:void 0,errorCode:typeof u.errorCode==="string"?u.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(u.turnId??""),reason:String(u.reason??"not observable from this process")};break;default:break}}}async function*ha(r){for await(let{name:o,data:a}of Vs(r)){if(qs.has(o)){yield{kind:"event",event:a};continue}if(o==="stream.subscribed"){let u=a??{};yield{kind:"subscribed",report:{agentId:typeof u.agentId==="string"?u.agentId:null,types:Array.isArray(u.types)?u.types:null,chunks:u.chunks===!0,implied:typeof u.implied==="string"?u.implied:void 0}}}}}async function*ga(r,o={}){for await(let a of r){if(a.kind==="replay"&&a.report.truncated&&o.allowTruncated!==!0)throw new Oe({code:"replay_truncated",message:`This turn's replay is missing its oldest ${a.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(a.kind==="unavailable")throw new Oe({code:"turn_not_observable",message:`Turn ${a.turnId} is recorded as running but is not observable here: ${a.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(a.kind!=="event")continue;if(a.event.type!=="model.chunk")continue;let u=a.event.data;if(u.kind==="reasoning")continue;if(typeof u.delta==="string")yield u.delta}}function Xs(r){let o=r.baseUrl.replace(/\/+$/,""),a=r.fetch??fetch,u=(k={})=>({...r.token===void 0?{}:{authorization:`Bearer ${r.token}`},...k});async function i(k,y,S={}){let P;try{P=await a(`${o}${y}`,{method:k,headers:u({...S.body===void 0?{}:{"content-type":"application/json"},...S.accept===void 0?{}:{accept:S.accept},...S.headers}),...S.body===void 0?{}:{body:JSON.stringify(S.body)},...S.signal===void 0?{}:{signal:S.signal}})}catch(U){throw ua(U,{method:k,path:y,baseUrl:o})}if(!P.ok)throw await fa(P,{method:k,path:y});return P}async function f(k,y,S){return await(await i(k,y,S??{})).json()}async function h(k,y){let S=await i("GET",k,{accept:"text/event-stream",...y===void 0?{}:{signal:y}});if(S.body===null)throw new Oe({code:"no_response_body",message:`GET ${k} returned ${S.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:S.status,method:"GET",path:k});return S.body}function g(k,y,S,P={}){let U=(F)=>F?.chunks===!0?"?chunks=true":"",W={turnId:y,sessionKey:S,replayed:P.replayed===!0,async*stream(F){let I=await h(`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}/stream${U(F)}`,F?.signal);yield*pa(I)},async*tokens(F){yield*ga(W.stream({chunks:!0,...F}),{...F?.allowTruncated===void 0?{}:{allowTruncated:F.allowTruncated}})},async text(){for await(let F of W.stream()){if(F.kind==="ended")break;if(F.kind==="unavailable")break;if(F.kind==="event"&&F.event.type==="turn.end")break}return(await W.get()).text},get:()=>f("GET",`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}`),async stop(){await i("POST",`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}/stop`)}};return W}function v(k){let y=(S)=>`/v1/agents/${encodeURIComponent(k)}${S}`;return{id:k,async send(S,P){let U=await f("POST",y("/messages"),{body:{text:S,...P?.sessionKey===void 0?{}:{sessionKey:P.sessionKey},...P?.deliver===void 0?{}:{deliver:P.deliver},...P?.from===void 0?{}:{from:P.from}},...P?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":P.idempotencyKey}},...P?.signal===void 0?{}:{signal:P.signal}});return g(k,U.turnId,U.sessionKey,{replayed:U.replayed===!0})},turn:(S)=>g(k,S,""),describe:()=>f("GET",y("")),tools:()=>f("GET",y("/tools")),skills:()=>f("GET",y("/skills")),sessions:()=>f("GET",y("/sessions")),messages:(S,P)=>{let U=new URLSearchParams;if(P?.before!==void 0)U.set("before",String(P.before));if(P?.limit!==void 0)U.set("limit",String(P.limit));let W=U.size===0?"":`?${U.toString()}`;return f("GET",y(`/sessions/${encodeURIComponent(S)}/messages${W}`))},clearSession:(S)=>f("DELETE",y(`/sessions/${encodeURIComponent(S)}`)),reload:()=>f("POST",y("/reload"),{body:{}}),schedules:async()=>(await f("GET",y("/schedules"))).schedules,approvals:async()=>(await f("GET",y("/approvals"))).approvals,createSchedule:(S)=>f("POST",y("/schedules"),{body:S}),updateSchedule:(S,P)=>f("PATCH",y(`/schedules/${encodeURIComponent(S)}`),{body:P}),deleteSchedule:async(S)=>{await f("DELETE",y(`/schedules/${encodeURIComponent(S)}`))},runSchedule:(S)=>f("POST",y(`/schedules/${encodeURIComponent(S)}/run`),{body:{}}),config:()=>f("GET",y("/config")),setConfig:(S,P,U)=>f("PATCH",y("/config"),{body:{path:S,value:P,...U?.confirm===void 0?{}:{confirm:U.confirm}}}),session:(S)=>f("GET",y(`/sessions/${encodeURIComponent(S)}`)),setPhase:(S,P)=>f("POST",y(`/sessions/${encodeURIComponent(S)}/phase`),{body:{phase:P}}),approve:async(S,P)=>{await f("POST",y(`/approvals/${encodeURIComponent(S)}`),{body:{granted:P}})},stop:(S)=>f("POST",y("/stop"),{body:S===void 0?{}:{reason:S}}),start:()=>f("POST",y("/start"),{body:{}}),context:(S)=>{let P=new URLSearchParams;if(S?.sessionKey!==void 0)P.set("sessionKey",S.sessionKey);if(S?.input!==void 0)P.set("input",S.input);let U=P.size===0?"":`?${P.toString()}`;return f("GET",y(`/context${U}`))}}}return{agent:v,agents:()=>f("GET","/v1/agents"),health:()=>f("GET","/v1/health"),async ready(){try{return await i("GET","/v1/ready"),!0}catch(k){if(k instanceof Oe&&k.status===503)return!1;throw k}},provision:()=>f("GET","/v1/provision"),keys:()=>f("GET","/v1/keys"),createKey:(k)=>f("POST","/v1/keys",{body:k}),revokeKey:(k)=>f("DELETE",`/v1/keys/${encodeURIComponent(k)}`),createAgent:(k)=>f("POST","/v1/agents",{body:{answers:k}}),async*events(k){let y=new URLSearchParams;if(k?.agentId!==void 0)y.set("agentId",k.agentId);if(k?.types!==void 0&&k.types.length>0)y.set("types",k.types.join(","));if(k?.chunks===!0)y.set("chunks","true");let S=y.size===0?"":`?${y.toString()}`,P=await h(`/v1/events${S}`,k?.signal);yield*ha(P)}}}function tn(r,o){let a=[];for(let u of r){if(u.origin!==void 0&&u.origin!=="call")continue;if(u.role!=="user"&&u.role!=="assistant")continue;let i=Rr(u,o);if(i==="")continue;a.push({role:u.role,text:i})}return a}function Js(r){let o=r.ref??"<your agent>",a=`${e.slug} run ${o} --session ${r.sessionKey}`;return`
275
- ${Jo}Resume this session with:
276
- ${a}${_n}
277
- `}function Lt(r,o){switch(r){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 o===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${o}, still in the store. /sessions goes back to it.`}}function ya(r){return r==="nlt"?jn():Un()}function zs(r){return{kind:"embedded",agentId:r.agent.id,describe:()=>r.description,subscribe:(o)=>r.bus.on("*",o,{chunks:!0}),send:(o,a)=>r.send(o,{...a,source:"repl"}),streamFilter:r.streamFilter,history:r.history,sessions:r.sessions,clearSession:r.clearSession,tools:async()=>Xn(r.agent),context:r.context,close:async()=>{}}}function Ys(r){let o=r.client.agent(r.agentId),a=new Set,u=new AbortController,i,f=()=>{if(i!==void 0)return;i=(async()=>{for await(let h of r.client.events({agentId:r.agentId,chunks:!0,signal:u.signal})){if(h.kind!=="event"||h.event===void 0)continue;for(let g of a)g(h.event)}})().catch(()=>{})};return{kind:"attached",agentId:r.agentId,host:r.host,describe:()=>r.description,subscribe:(h)=>(a.add(h),f(),()=>a.delete(h)),send:async(h,g)=>{let v=!1,k,y=()=>{if(v=!0,k!==void 0)o.turn(k).stop().catch(()=>{})};g.signal.addEventListener("abort",y,{once:!0});let S,P=new Promise((U)=>{let W=(F)=>{if(k!==void 0&&F.turnId!==void 0&&F.turnId!==k)return;if(F.type==="error"){S=F.data;return}if(F.type!=="turn.end")return;a.delete(W),U({text:"",reason:F.data.reason,steps:F.data.steps,durationMs:F.data.durationMs,tokens:F.data.tokens,...S===void 0?{}:{error:S}})};a.add(W),f()});try{if(k=(await o.send(h,{sessionKey:g.sessionKey})).turnId,v)o.turn(k).stop().catch(()=>{});return await P}finally{g.signal.removeEventListener("abort",y)}},streamFilter:()=>ya(r.description.dialect),history:async(h)=>{let g=await o.messages(h);return tn([...g.messages].reverse().map((v)=>({role:v.role,content:v.content,...v.origin===void 0?{}:{origin:v.origin}})),r.description.dialect)},sessions:()=>o.sessions(),clearSession:async(h)=>{await o.clearSession(h)},tools:async()=>{let h=await o.tools();return{dialect:r.description.dialect,catalogueTokens:r.description.catalogueTokens,tools:h.map((g)=>({slug:g.slug,mutating:g.mutating,trust:g.trust,...g.trustReason===void 0?{}:{trustReason:g.trustReason},summary:g.summary}))}},context:async(h)=>{let g=await o.context({sessionKey:h});return{...g,windowSource:"as the host resolved it",...g.lastCompaction===void 0&&g.compactions!==void 0?{lastCompaction:g.compactions===0?void 0:`${g.compactions} stage${g.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await o.reload()).adopted,close:async()=>{u.abort(),a.clear()}}}function Qs(r){if(r?.baseUrl===void 0||r.baseUrl==="")return;return{baseUrl:r.baseUrl,pid:r.pid}}async function ba(r,o,a,u,i,f=[],h){let g=r.describe(),[v,k]=await Promise.all([r.turns(o,1),r.store.messages.count(r.id,o)]),y=[`${e.name} ${R} · ${g.id} · ${g.model}`,`session ${o} · ${k} message(s) · window ${g.window} · store ${a}`,`ready in ${u.toFixed(0)} ms · /help for commands and keys · /exit to leave`],S=Lt(i,h);if(S!==void 0)y.push(S);if(v[0]?.errorCode==="turn_abandoned")y.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let P of[...r.warnings,...r.tools.warnings])y.push(`note: ${P.message}
278
- ${P.hint}`);if(f.length>0)y.push(`note: ${f.join(", ")} in the .env here ${f.length===1?"was":"were"} ignored — this agent's own .env sets ${f.length===1?"it":"them"}.
279
- 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 y}async function Ut(r){let o=r.once!==void 0,a=ie({json:!1,plain:r.plain===!0,oneShot:o}),{mode:u}=a;if(r.manifestPath===void 0){let F=await $a(u,a.because,r);if(typeof F==="number")return F;return Ut({...r,manifestPath:F})}let i=$r();if(r.store===void 0&&r.ephemeral!==!0&&wa(i))process.stdout.write(`note: a session store exists at ${i} from an earlier version — pass --store ${i} to keep using it; the default is now ${w()}
280
- `);let f;b(()=>f?.stop("cli-exit"));let h={current:void 0},g={current:""},v={current:r.sessionKey},k={current:!1},y={current:void 0},S=r.quiet===!0,P="first",U={current:void 0},W=r.ephemeral===!0?void 0:Qs(await Ce(xt(r.manifestPath),r.store));if(W!==void 0)return await Pa({...r,host:W,mode:u==="rich"?"rich":"plain",quiet:S,oneShot:o,reader:h,draft:g,session:v,random:jt});for(;;){let F=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),store:r.ephemeral===!0?":memory:":r.store??w()});f=F;let I=F.list()[0];if(I===void 0)throw Error("The manifest produced no agent.");if(v.current===void 0||v.current===""){let fe=await eo({list:()=>Q.sessions(),mode:u,asked:v.current,wantsContinue:r.continueSession===!0,random:jt});if(typeof fe==="number")return await F.stop("cli-exit"),fe;v.current=fe.sessionKey,k.current=fe.fresh}let de=v.current,oe=I.roles.main.capabilities.thinking!=="none",ge=r.noReasoning===!0?!1:oe,z=S||o?[]:await ba(I,de,F.store.location,P==="first"?F.boot.processMs:F.boot.bootMs,P,Co([r.manifestPath]),y.current),V=u==="rich"&&!S&&!o?tn(await I.history(de),I.describe().dialect):[],Q=zs({agent:I,bus:F.bus,send:(fe,Ae)=>I.send(fe,Ae),history:async(fe)=>tn(await I.history(fe),I.describe().dialect),sessions:async()=>await I.store.sessions.list(I.id),clearSession:async(fe)=>{await I.clearSession(fe)},context:async(fe)=>Ea(I,fe),streamFilter:()=>I.streamFilter(),description:{agentId:I.id,name:I.describe().name,model:I.describe().model,dialect:I.describe().dialect,window:I.describe().window,catalogueTokens:I.describe().catalogueTokens,thinking:I.roles.main.capabilities.thinking,warnings:[...I.warnings,...I.tools.warnings]}}),re={...r,source:Q,embedded:{agent:I,runtime:F},sessionKey:de,banner:z,prior:V,quiet:S,reader:h,draft:g,showReasoning:ge,freshSession:k.current,switchTo:U,random:jt},he=u==="rich"?await no(re):await to(re);if(await F.stop(he===Ne?"restart":"cli-exit"),he!==Ne)return he;if(U.current===void 0)P="restart";else P=U.current.reason,y.current=de,v.current=U.current.key,U.current=void 0;k.current=!1}}function va(r,o){let a=[];for(let u of r)Se({action:"install",manifestPath:o,name:`${u.source}/${u.skill}`,quiet:!0,collect:a});return a}var Ne=Symbol("restart");async function $a(r,o,a){let u=K();if(u.length===0){if(r==="rich"){let y=await at({plain:a.plain===!0});if(y.kind==="aborted")return process.stdout.write(`nothing to run
281
- `),n;if(y.kind==="failed")return y.code;return y.manifestPath}throw new t({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${e.slug} init\`, or pass a path to an agent.yaml.`})}if(u.length===1&&u[0]!==void 0)return process.stdout.write(`running ${u[0].ref} — the only agent in the sandbox
282
- `),u[0].manifestPath;if(r!=="rich"){for(let y of u)process.stdout.write(`${y.ref} ${y.problem??y.modelId??"?"} ${y.dir}
283
- `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${o})
284
- `),s}let[{render:i},{createElement:f},{Picker:h}]=await Promise.all([import("ink"),import("react"),import("./Picker-hfeh1g6m.js")]),g={kind:"quit"};Wt();let v=i(f(h,{title:`${e.name} ${R}`,agents:u,onDone:(y)=>{g=y}}),{exitOnCtrlC:!1,...Z(a.noEnhancedKeys)});b(()=>v.unmount()),await v.waitUntilExit(),v.unmount();let k=g;if(k.kind==="quit")return process.stdout.write(`nothing run
285
- `),n;if(k.kind==="create"){let y=await at({plain:a.plain===!0});if(y.kind==="aborted")return process.stdout.write(`nothing to run
286
- `),n;if(y.kind==="failed")return y.code;return y.manifestPath}return k.manifestPath}async function eo(r){let o=()=>({sessionKey:Hn(r.random),fresh:!0});if(r.wantsContinue&&r.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(r.wantsContinue){let a=await r.list(),u=ka(a);if(u===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
287
- `),o();return{sessionKey:u.sessionKey,fresh:!1}}if(r.asked===""){let a=await r.list();if(a.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
288
- `),o();if(r.mode!=="rich"){for(let i of[...a].sort(Kn))process.stdout.write(`${i.sessionKey} ${i.messages} ${i.turns} ${i.lastActivityAt}
190
+ pruned ${s.length} agent id(s).
191
+ ${E(a)}
192
+ `),n}async function _s(e,r,o){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 ${le()} 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=X(),s=i.find((y)=>y.ref===e);if(s===void 0){let y=i.map((b)=>b.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${e}" in the sandbox${y.length===0?", which is empty":""}.`,hint:y.length===0?`Nothing to remove. \`${A.slug} init\` creates one.`:`Known agents: ${y.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let a=s.id;if(a===void 0)try{a=L(s.manifestPath).id}catch{}let d=r.filesOnly===!0||a===void 0,l=a??e,m=await o.agentFootprint(l),g=m.lease?await o.leases.get(l):void 0,u=Cs(r),h=lo(A.slug,l);return{ref:e,agentId:l,manifestPath:s.manifestPath,dir:s.dir,files:Fi(s.dir),footprint:m,logs:Ns(l),sharesIdWith:i.filter((y)=>y.ref!==e&&(y.id??"")===l).map((y)=>y.ref),...g!==void 0&&J(g.pid)?{running:{pid:g.pid,mode:g.mode}}:{},...u?.state(h).installed===!0?{service:h}:{},filesOnly:d}}function Cs(e){let r=e.platform??process.platform;if(r!=="darwin")return;return Mt(r,{home:Oi(),uid:process.getuid?.()??0,envPrefix:A.envPrefix,...e.exec===void 0?{}:{exec:e.exec}})}function Fi(e){let r=0,o=0,i=(s)=>{let a;try{a=Rs(s)}catch{return}for(let d of a){let l=Ts(s,d);try{let m=Is(l);if(m.isDirectory()){i(l);continue}r+=1,o+=m.size}catch{}}};return i(e),{count:r,bytes:o}}function Ns(e){let r=Pt(e),o=[];for(let i of[r.out,r.err])try{if(!Ti(i))continue;o.push({path:i,bytes:Is(i).size})}catch{}return o}function Ki(){let e;try{e=Rs(Ts(pe(),"logs"))}catch{return[]}let r=new Set;for(let o of e)for(let i of[".out.log",".err.log"])if(o.endsWith(i))r.add(o.slice(0,-i.length));return[...r]}async function Kn(e,r,o){if(e.yes===!0)return!0;let i=e.confirm;if(i===void 0)return!1;return await i(o,r)}async function js(e){if(e.manifestPath===void 0)return await CA({action:"restart",...e.store===void 0?{}:{store:e.store},...e.json===void 0?{}:{json:e.json}});let r=Ie(e.manifestPath),o=await In(e.manifestPath,e.store),i,s,a=n;switch(o.kind){case"reloaded":i="reloaded",s=`pid ${o.pid} rebuilt it from disk${o.adopted.length>0?` · adopted ${o.adopted.join(", ")}`:""}`;break;case"busy":i="not reloaded",s=`pid ${o.pid} has a turn in flight — try again when it finishes`,a=c;break;case"failed":i="not reloaded",s=`pid ${o.pid} answered ${o.status}${o.detail===void 0?"":`: ${o.detail}`}${o.hint===void 0?"":` — ${o.hint}`}`,a=c;break;case"no-host":{let d=await _e(e.store);if(d===void 0)throw new t({code:"cli_restart_nothing_running",message:`Nothing is hosting ${r}, and no server is running to adopt it.`,hint:`\`${A.slug} serve ${r}\` runs it in this terminal; \`${A.slug} daemon install\` keeps a server running that hosts every agent. Then \`${A.slug} restart ${r}\` reloads it in place.`});let l=await ot(d,e.manifestPath,e.store);if(l.ok)i="started",s=`nothing was hosting it — adopted by pid ${d.pid}`;else i="not started",s=`pid ${d.pid} did not adopt it${l.detail===void 0?"":`: ${l.detail}`}`,a=c;break}}if(e.json===!0)process.stdout.write(`${JSON.stringify({agentId:r,result:o,ok:a===n},null,2)}
193
+ `);else process.stdout.write(`${E([{label:r,value:i,note:s}])}
194
+ `);return a}import{randomBytes as Hn}from"node:crypto";import{existsSync as Vi}from"node:fs";import{createInterface as Gs}from"node:readline";class de extends Error{code;hint;field;status;request;constructor(e,r={}){super(e.hint===void 0?e.message:`${e.message}
195
+ hint: ${e.hint}`);if(this.name="DispachError",this.code=e.code,this.hint=e.hint??"",this.field=e.field,this.status=r.status,this.request=r.method===void 0||r.path===void 0?void 0:{method:r.method,path:r.path},r.cause!==void 0)this.cause=r.cause}}function Li(e,r){let o=e instanceof Error?e.message:String(e);return new de({code:"transport_failed",message:`${r.method} ${r.path} did not reach ${r.baseUrl}: ${o}`,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."},{...r,cause:e})}async function Ui(e,r){let o;try{let i=await e.json();if(typeof i.error?.code==="string"&&typeof i.error.message==="string")o={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 de(o??{code:`http_${e.status}`,message:`${r.method} ${r.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,...r})}var Ks=new Set(pA);async function*Ls(e){for await(let r of Oo(Mi(e))){if(r.event===void 0||r.data==="")continue;let o;try{o=JSON.parse(r.data)}catch{continue}yield{name:r.event,data:o}}}async function*Mi(e){let r=e.getReader();try{while(!0){let{done:o,value:i}=await r.read();if(o)return;if(i!==void 0)yield i}}finally{r.releaseLock()}}async function*Di(e){for await(let{name:r,data:o}of Ls(e)){if(Ks.has(r)){yield{kind:"event",event:o};continue}let i=o??{};switch(r){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*Hi(e){for await(let{name:r,data:o}of Ls(e)){if(Ks.has(r)){yield{kind:"event",event:o};continue}if(r==="stream.subscribed"){let i=o??{};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*Gi(e,r={}){for await(let o of e){if(o.kind==="replay"&&o.report.truncated&&r.allowTruncated!==!0)throw new de({code:"replay_truncated",message:`This turn's replay is missing its oldest ${o.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(o.kind==="unavailable")throw new de({code:"turn_not_observable",message:`Turn ${o.turnId} is recorded as running but is not observable here: ${o.reason}.`,hint:"Its events are buffered in whichever process is executing it. Poll GET /v1/agents/:id/turns/:turnId for the outcome."});if(o.kind!=="event")continue;if(o.event.type!=="model.chunk")continue;let i=o.event.data;if(i.kind==="reasoning")continue;if(typeof i.delta==="string")yield i.delta}}function Us(e){let r=e.baseUrl.replace(/\/+$/,""),o=e.fetch??fetch,i=(g={})=>({...e.token===void 0?{}:{authorization:`Bearer ${e.token}`},...g});async function s(g,u,h={}){let y;try{y=await o(`${r}${u}`,{method:g,headers:i({...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(b){throw Li(b,{method:g,path:u,baseUrl:r})}if(!y.ok)throw await Ui(y,{method:g,path:u});return y}async function a(g,u,h){return await(await s(g,u,h??{})).json()}async function d(g,u){let h=await s("GET",g,{accept:"text/event-stream",...u===void 0?{}:{signal:u}});if(h.body===null)throw new de({code:"no_response_body",message:`GET ${g} 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:g});return h.body}function l(g,u,h,y={}){let b=(w)=>w?.chunks===!0?"?chunks=true":"",R={turnId:u,sessionKey:h,replayed:y.replayed===!0,async*stream(w){let v=await d(`/v1/agents/${encodeURIComponent(g)}/turns/${encodeURIComponent(u)}/stream${b(w)}`,w?.signal);yield*Di(v)},async*tokens(w){yield*Gi(R.stream({chunks:!0,...w}),{...w?.allowTruncated===void 0?{}:{allowTruncated:w.allowTruncated}})},async text(){for await(let w of R.stream()){if(w.kind==="ended")break;if(w.kind==="unavailable")break;if(w.kind==="event"&&w.event.type==="turn.end")break}return(await R.get()).text},get:()=>a("GET",`/v1/agents/${encodeURIComponent(g)}/turns/${encodeURIComponent(u)}`),async stop(){await s("POST",`/v1/agents/${encodeURIComponent(g)}/turns/${encodeURIComponent(u)}/stop`)}};return R}function m(g){let u=(h)=>`/v1/agents/${encodeURIComponent(g)}${h}`;return{id:g,async send(h,y){let b=await a("POST",u("/messages"),{body:{text:h,...y?.sessionKey===void 0?{}:{sessionKey:y.sessionKey},...y?.deliver===void 0?{}:{deliver:y.deliver},...y?.from===void 0?{}:{from:y.from}},...y?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":y.idempotencyKey}},...y?.signal===void 0?{}:{signal:y.signal}});return l(g,b.turnId,b.sessionKey,{replayed:b.replayed===!0})},turn:(h)=>l(g,h,""),describe:()=>a("GET",u("")),tools:()=>a("GET",u("/tools")),skills:()=>a("GET",u("/skills")),sessions:()=>a("GET",u("/sessions")),messages:(h,y)=>{let b=new URLSearchParams;if(y?.before!==void 0)b.set("before",String(y.before));if(y?.limit!==void 0)b.set("limit",String(y.limit));let R=b.size===0?"":`?${b.toString()}`;return a("GET",u(`/sessions/${encodeURIComponent(h)}/messages${R}`))},clearSession:(h)=>a("DELETE",u(`/sessions/${encodeURIComponent(h)}`)),reload:()=>a("POST",u("/reload"),{body:{}}),usage:(h)=>a("GET",u(`/usage${Fs(h)}`)),turns:(h)=>{let y=new URLSearchParams;if(h?.limit!==void 0)y.set("limit",String(h.limit));if(h?.before!==void 0)y.set("before",String(h.before));let b=y.size===0?"":`?${y.toString()}`;return a("GET",u(`/turns${b}`))},secrets:async()=>(await a("GET",u("/secrets"))).secrets,setSecrets:(h)=>a("PUT",u("/secrets"),{body:{values:h}}),schedules:async()=>(await a("GET",u("/schedules"))).schedules,approvals:async()=>(await a("GET",u("/approvals"))).approvals,createSchedule:(h)=>a("POST",u("/schedules"),{body:h}),updateSchedule:(h,y)=>a("PATCH",u(`/schedules/${encodeURIComponent(h)}`),{body:y}),deleteSchedule:async(h)=>{await a("DELETE",u(`/schedules/${encodeURIComponent(h)}`))},runSchedule:(h)=>a("POST",u(`/schedules/${encodeURIComponent(h)}/run`),{body:{}}),config:()=>a("GET",u("/config")),setConfig:(h,y,b)=>a("PATCH",u("/config"),{body:{path:h,value:y,...b?.confirm===void 0?{}:{confirm:b.confirm}}}),setChannel:(h,y)=>a("PATCH",u(`/channels/${encodeURIComponent(h)}`),{body:{...y}}),unpairChannel:(h)=>a("POST",u(`/channels/${encodeURIComponent(h)}/unpair`)),session:(h)=>a("GET",u(`/sessions/${encodeURIComponent(h)}`)),setPhase:(h,y)=>a("POST",u(`/sessions/${encodeURIComponent(h)}/phase`),{body:{phase:y}}),approve:async(h,y)=>{await a("POST",u(`/approvals/${encodeURIComponent(h)}`),{body:{granted:y}})},stop:(h)=>a("POST",u("/stop"),{body:h===void 0?{}:{reason:h}}),start:()=>a("POST",u("/start"),{body:{}}),context:(h)=>{let y=new URLSearchParams;if(h?.sessionKey!==void 0)y.set("sessionKey",h.sessionKey);if(h?.input!==void 0)y.set("input",h.input);let b=y.size===0?"":`?${y.toString()}`;return a("GET",u(`/context${b}`))}}}return{agent:m,agents:()=>a("GET","/v1/agents"),health:()=>a("GET","/v1/health"),async ready(){try{return await s("GET","/v1/ready"),!0}catch(g){if(g instanceof de&&g.status===503)return!1;throw g}},provision:()=>a("GET","/v1/provision"),keys:()=>a("GET","/v1/keys"),createKey:(g)=>a("POST","/v1/keys",{body:g}),revokeKey:(g)=>a("DELETE",`/v1/keys/${encodeURIComponent(g)}`),createAgent:(g)=>a("POST","/v1/agents",{body:{answers:g}}),usage:(g)=>a("GET",`/v1/usage${Fs(g)}`),activity:()=>a("GET","/v1/activity"),webhooks:async()=>(await a("GET","/v1/webhooks")).webhooks,createWebhook:(g)=>a("POST","/v1/webhooks",{body:g}),deleteWebhook:(g)=>a("DELETE",`/v1/webhooks/${encodeURIComponent(g)}`),templates:async()=>(await a("GET","/v1/templates")).templates,createAgentFromTemplate:(g)=>a("POST","/v1/agents",{body:g}),async*events(g){let u=new URLSearchParams;if(g?.agentId!==void 0)u.set("agentId",g.agentId);if(g?.types!==void 0&&g.types.length>0)u.set("types",g.types.join(","));if(g?.chunks===!0)u.set("chunks","true");let h=u.size===0?"":`?${u.toString()}`,y=await d(`/v1/events${h}`,g?.signal);yield*Hi(y)}}}function Fs(e){let r=new URLSearchParams;if(e?.by!==void 0)r.set("by",e.by.join(","));if(e?.from!==void 0)r.set("from",e.from);if(e?.to!==void 0)r.set("to",e.to);return r.size===0?"":`?${r.toString()}`}function xe(e,r){let o=[];for(let i of e){if(i.origin!==void 0&&i.origin!=="call")continue;if(i.role!=="user"&&i.role!=="assistant")continue;let s=Qi(i,r);if(s==="")continue;o.push({role:i.role,text:s})}return o}function Ms(e){let r=e.ref??"<your agent>",o=`${A.slug} run ${r} --session ${e.sessionKey}`;return`
196
+ ${ns}Resume this session with:
197
+ ${o}${qn}
198
+ `}function Dn(e,r){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 r===void 0?"new conversation — the one you left is still in the store, under its own key.":`new conversation — the one you left is ${r}, still in the store. /sessions goes back to it.`}}function qi(e){return e==="nlt"?Mo():bo()}function Ds(e){return{kind:"embedded",agentId:e.agent.id,describe:()=>e.description,subscribe:(r)=>e.bus.on("*",r,{chunks:!0}),send:(r,o)=>e.send(r,{...o,source:"repl"}),streamFilter:e.streamFilter,history:e.history,sessions:e.sessions,clearSession:e.clearSession,tools:async()=>co(e.agent),context:e.context,close:async()=>{}}}function Hs(e){let r=e.client.agent(e.agentId),o=new Set,i=new AbortController,s,a=()=>{if(s!==void 0)return;s=(async()=>{for await(let d of e.client.events({agentId:e.agentId,chunks:!0,signal:i.signal})){if(d.kind!=="event"||d.event===void 0)continue;for(let l of o)l(d.event)}})().catch(()=>{})};return{kind:"attached",agentId:e.agentId,host:e.host,describe:()=>e.description,subscribe:(d)=>(o.add(d),a(),()=>o.delete(d)),send:async(d,l)=>{let m=!1,g,u=()=>{if(m=!0,g!==void 0)r.turn(g).stop().catch(()=>{})};l.signal.addEventListener("abort",u,{once:!0});let h,y=new Promise((b)=>{let R=(w)=>{if(g!==void 0&&w.turnId!==void 0&&w.turnId!==g)return;if(w.type==="error"){h=w.data;return}if(w.type!=="turn.end")return;o.delete(R),b({text:"",reason:w.data.reason,steps:w.data.steps,durationMs:w.data.durationMs,tokens:w.data.tokens,...h===void 0?{}:{error:h}})};o.add(R),a()});try{if(g=(await r.send(d,{sessionKey:l.sessionKey})).turnId,m)r.turn(g).stop().catch(()=>{});return await y}finally{l.signal.removeEventListener("abort",u)}},streamFilter:()=>qi(e.description.dialect),history:async(d)=>{let l=await r.messages(d);return xe([...l.messages].reverse().map((m)=>({role:m.role,content:m.content,...m.origin===void 0?{}:{origin:m.origin}})),e.description.dialect)},sessions:()=>r.sessions(),clearSession:async(d)=>{await r.clearSession(d)},tools:async()=>{let d=await r.tools();return{dialect:e.description.dialect,catalogueTokens:e.description.catalogueTokens,tools:d.map((l)=>({slug:l.slug,mutating:l.mutating,trust:l.trust,...l.trustReason===void 0?{}:{trustReason:l.trustReason},summary:l.summary}))}},context:async(d)=>{let l=await r.context({sessionKey:d});return{...l,windowSource:"as the host resolved it",...l.lastCompaction===void 0&&l.compactions!==void 0?{lastCompaction:l.compactions===0?void 0:`${l.compactions} stage${l.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await r.reload()).adopted,close:async()=>{i.abort(),o.clear()}}}function Ws(e){if(e?.baseUrl===void 0||e.baseUrl==="")return;return{baseUrl:e.baseUrl,pid:e.pid}}async function Ji(e,r,o,i,s,a=[],d){let l=e.describe(),[m,g]=await Promise.all([e.turns(r,1),e.store.messages.count(e.id,r)]),u=[`${A.name} ${H} · ${l.id} · ${l.model}`,`session ${r} · ${g} message(s) · window ${l.window} · store ${o}`,`ready in ${i.toFixed(0)} ms · /help for commands and keys · /exit to leave`],h=Dn(s,d);if(h!==void 0)u.push(h);if(m[0]?.errorCode==="turn_abandoned")u.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let y of[...e.warnings,...e.tools.warnings])u.push(`note: ${y.message}
199
+ ${y.hint}`);if(a.length>0)u.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"}.
200
+ 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 u}async function Wn(e){let r=e.once!==void 0,o=Je({json:!1,plain:e.plain===!0,oneShot:r}),{mode:i}=o;if(e.manifestPath===void 0){let w=await Yi(i,o.because,e);if(typeof w==="number")return w;return Wn({...e,manifestPath:w})}let s=fi();if(e.store===void 0&&e.ephemeral!==!0&&Vi(s))process.stdout.write(`note: a session store exists at ${s} from an earlier version — pass --store ${s} to keep using it; the default is now ${G()}
201
+ `);let a;P(()=>a?.stop("cli-exit"));let d={current:void 0},l={current:""},m={current:e.sessionKey},g={current:!1},u={current:void 0},h=e.quiet===!0,y="first",b={current:void 0},R=e.ephemeral===!0?void 0:Ws(await ke(Ie(e.manifestPath),e.store));if(R!==void 0)return await ta({...e,host:R,mode:i==="rich"?"rich":"plain",quiet:h,oneShot:r,reader:d,draft:l,session:m,random:Hn});for(;;){let w=await ge.create({agents:[e.manifestPath],toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath]),store:e.ephemeral===!0?":memory:":e.store??G()});a=w;let v=w.list()[0];if(v===void 0)throw Error("The manifest produced no agent.");if(m.current===void 0||m.current===""){let D=await qs({list:()=>_.sessions(),mode:i,asked:m.current,wantsContinue:e.continueSession===!0,random:Hn});if(typeof D==="number")return await w.stop("cli-exit"),D;m.current=D.sessionKey,g.current=D.fresh}let U=m.current,k=v.roles.main.capabilities.thinking!=="none",j=e.noReasoning===!0?!1:k,T=h||r?[]:await Ji(v,U,w.store.location,y==="first"?w.boot.processMs:w.boot.bootMs,y,Gr([e.manifestPath]),u.current),O=i==="rich"&&!h&&!r?xe(await v.history(U),v.describe().dialect):[],_=Ds({agent:v,bus:w.bus,send:(D,te)=>v.send(D,te),history:async(D)=>xe(await v.history(D),v.describe().dialect),sessions:async()=>await v.store.sessions.list(v.id),clearSession:async(D)=>{await v.clearSession(D)},context:async(D)=>sa(v,D),streamFilter:()=>v.streamFilter(),description:{agentId:v.id,name:v.describe().name,model:v.describe().model,dialect:v.describe().dialect,window:v.describe().window,catalogueTokens:v.describe().catalogueTokens,thinking:v.roles.main.capabilities.thinking,warnings:[...v.warnings,...v.tools.warnings]}}),C={...e,source:_,embedded:{agent:v,runtime:w},sessionKey:U,banner:T,prior:O,quiet:h,reader:d,draft:l,showReasoning:j,freshSession:g.current,switchTo:b,random:Hn},B=i==="rich"?await Bs(C):await Vs(C);if(await w.stop(B===ce?"restart":"cli-exit"),B!==ce)return B;if(b.current===void 0)y="restart";else y=b.current.reason,u.current=U,m.current=b.current.key,b.current=void 0;g.current=!1}}function Xi(e,r){let o=[];for(let i of e)BA({action:"install",manifestPath:r,name:`${i.source}/${i.skill}`,quiet:!0,collect:o});return o}var ce=Symbol("restart");async function Yi(e,r,o){let i=X();if(i.length===0){if(e==="rich"){let u=await wn({plain:o.plain===!0});if(u.kind==="aborted")return process.stdout.write(`nothing to run
202
+ `),n;if(u.kind==="failed")return u.code;return u.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
203
+ `),i[0].manifestPath;if(e!=="rich"){for(let u of i)process.stdout.write(`${u.ref} ${u.problem??u.modelId??"?"} ${u.dir}
204
+ `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${r})
205
+ `),c}let[{render:s},{createElement:a},{Picker:d}]=await Promise.all([import("ink"),import("react"),import("./Picker-rq015kzc.js")]),l={kind:"quit"};yn();let m=s(a(d,{title:`${A.name} ${H}`,agents:i,onDone:(u)=>{l=u}}),{exitOnCtrlC:!1,...Oe(o.noEnhancedKeys)});P(()=>m.unmount()),await m.waitUntilExit(),m.unmount();let g=l;if(g.kind==="quit")return process.stdout.write(`nothing run
206
+ `),n;if(g.kind==="create"){let u=await wn({plain:o.plain===!0});if(u.kind==="aborted")return process.stdout.write(`nothing to run
207
+ `),n;if(u.kind==="failed")return u.code;return u.manifestPath}return g.manifestPath}async function qs(e){let r=()=>({sessionKey:Uo(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 o=await e.list(),i=Zi(o);if(i===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
208
+ `),r();return{sessionKey:i.sessionKey,fresh:!1}}if(e.asked===""){let o=await e.list();if(o.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
209
+ `),r();if(e.mode!=="rich"){for(let s of[...o].sort(Qe))process.stdout.write(`${s.sessionKey} ${s.messages} ${s.turns} ${s.lastActivityAt}
289
210
  `);return process.stderr.write(`pass --session <key> — the picker needs a terminal, and --continue takes the most recent without one
290
- `),s}let u=await Sa([...a].sort(Kn));return u===void 0?o():{sessionKey:u,fresh:!1}}return r.asked===void 0?o():{sessionKey:r.asked,fresh:!1}}function Kn(r,o){return Date.parse(o.lastActivityAt)-Date.parse(r.lastActivityAt)}function ka(r){return[...r].sort(Kn)[0]}async function Sa(r){let[{render:o},{createElement:a},{SessionPicker:u}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-zyqkg4dn.js")]),i;Wt();let f=o(a(u,{sessions:r.map((h)=>({sessionKey:h.sessionKey,messages:h.messages,turns:h.turns,lastActivityAt:h.lastActivityAt,phase:h.phase})),now:Date.now(),columns:q(process.stdout.columns,j),maxRows:Bt,onDone:(h)=>{i=h,f.unmount()}}),{exitOnCtrlC:!1,...Z()});return b(()=>f.unmount()),await f.waitUntilExit(),i}function xa(r,o,a,u,i){let f=r.describe(),h=[`${e.name} ${R} · ${f.agentId} · ${f.model}`,`session ${o} · window ${f.window} · attached to ${a.baseUrl} (pid ${a.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],g=Lt(u,i);if(g!==void 0)h.push(g);for(let v of f.warnings)h.push(`warning: ${v.message}`);return h}async function Pa(r){let o=r.manifestPath??"",a=xt(o),u=Je(o),i=Xs({baseUrl:r.host.baseUrl,...u===void 0?{}:{token:u}}),f=await i.agent(a).describe(),h=Ys({client:i,agentId:a,host:r.host,description:{agentId:a,name:f.name,model:f.model??"unknown",dialect:f.dialect??"nlt",window:f.window??0,catalogueTokens:f.catalogueTokens??0,thinking:"unknown",warnings:f.warnings??[]}}),g={current:void 0},v="first",k={current:void 0},y={current:!1};for(;;){if(r.session.current===void 0||r.session.current===""){let I=await eo({list:()=>h.sessions(),mode:r.mode,asked:r.session.current,wantsContinue:r.continueSession===!0,random:r.random});if(typeof I==="number")return I;r.session.current=I.sessionKey,y.current=I.fresh}let S=r.session.current??"",P=r.quiet||r.oneShot?[]:xa(h,S,r.host,v,k.current),U=r.mode==="rich"&&!r.quiet&&!r.oneShot?await h.history(S):[],W={...r,source:h,sessionKey:S,banner:P,prior:U,quiet:r.quiet,reader:r.reader,draft:r.draft,showReasoning:r.noReasoning!==!0,freshSession:y.current,switchTo:g,random:r.random},F=r.mode==="rich"?await no(W):await to(W);if(F!==Ne)return await h.close(),F;if(g.current===void 0)v="restart";else v=g.current.reason,k.current=S,r.session.current=g.current.key,g.current=void 0;y.current=!1}}async function no(r){let[{render:o},{createElement:a},{App:u}]=await Promise.all([import("ink"),import("react"),import("./App-b1yrwrcq.js")]),i=En();b(()=>{i.close()}),pe(),Zr(),process.stdout.write(`${ve}${Ko}`);let f=!1,h=o(a(u,{source:r.source,onSwitch:(g,v)=>{f=!0,r.switchTo.current={key:g,reason:"switch"},r.draft.current=v},onNew:(g)=>{f=!0,r.switchTo.current={key:Hn(r.random),reason:"new"},r.draft.current=g},sessions:async()=>[...await r.source.sessions()].sort(Kn).map((v)=>({sessionKey:v.sessionKey,messages:v.messages,turns:v.turns,lastActivityAt:v.lastActivityAt,phase:v.phase})),onRestart:(g)=>{f=!0,r.draft.current=g},sessionKey:r.sessionKey,model:r.source.describe().model,agentName:r.source.describe().agentId,freshSession:r.freshSession,warnings:r.source.describe().warnings.map((g)=>g.message),initial:So(ko(r.banner.slice(1)),r.prior),correctKeys:i.correct,showReasoning:r.showReasoning,quiet:r.quiet,...r.manifestPath===void 0?{}:{manifestPath:r.manifestPath},catalogue:{load:(g)=>nt({onStatus:g}),install:async(g,v)=>Et(va(g,v))},status:()=>r.embedded===void 0?so(r.source):ro(r.embedded),contextView:()=>oo(r,r.sessionKey),...r.draft.current===""?{}:{initialDraft:r.draft.current}}),{exitOnCtrlC:!1,...Z(r.noEnhancedKeys)});if(b(()=>h.unmount()),await h.waitUntilExit(),J(),!f)process.stdout.write(Js({ref:r.source.describe().agentId,sessionKey:r.sessionKey}));return f?Ne:n}async function to(r){let{source:o,sessionKey:a,quiet:u}=r,i=!0,f=(z)=>{if(z==="")return;process.stdout.write(z),i=z.endsWith(`
291
- `)},h=(z)=>{if(!i)f(`
292
- `);f(`${z}
293
- `)};if(r.banner.length>0)f(`${r.banner.join(`
211
+ `),c}let i=await ea([...o].sort(Qe));return i===void 0?r():{sessionKey:i,fresh:!1}}return e.asked===void 0?r():{sessionKey:e.asked,fresh:!1}}function Qe(e,r){return Date.parse(r.lastActivityAt)-Date.parse(e.lastActivityAt)}function Zi(e){return[...e].sort(Qe)[0]}async function ea(e){let[{render:r},{createElement:o},{SessionPicker:i}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-03zyvd2f.js")]),s;yn();let a=r(o(i,{sessions:e.map((d)=>({sessionKey:d.sessionKey,messages:d.messages,turns:d.turns,lastActivityAt:d.lastActivityAt,phase:d.phase})),now:Date.now(),columns:Se(process.stdout.columns,Ce),maxRows:xt,onDone:(d)=>{s=d,a.unmount()}}),{exitOnCtrlC:!1,...Oe()});return P(()=>a.unmount()),await a.waitUntilExit(),s}function na(e,r,o,i,s){let a=e.describe(),d=[`${A.name} ${H} · ${a.agentId} · ${a.model}`,`session ${r} · window ${a.window} · attached to ${o.baseUrl} (pid ${o.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],l=Dn(i,s);if(l!==void 0)d.push(l);for(let m of a.warnings)d.push(`warning: ${m.message}`);return d}async function ta(e){let r=e.manifestPath??"",o=Ie(r),i=st(r),s=Us({baseUrl:e.host.baseUrl,...i===void 0?{}:{token:i}}),a=await s.agent(o).describe(),d=Hs({client:s,agentId:o,host:e.host,description:{agentId:o,name:a.name,model:a.model??"unknown",dialect:a.dialect??"nlt",window:a.window??0,catalogueTokens:a.catalogueTokens??0,thinking:"unknown",warnings:a.warnings??[]}}),l={current:void 0},m="first",g={current:void 0},u={current:!1};for(;;){if(e.session.current===void 0||e.session.current===""){let v=await qs({list:()=>d.sessions(),mode:e.mode,asked:e.session.current,wantsContinue:e.continueSession===!0,random:e.random});if(typeof v==="number")return v;e.session.current=v.sessionKey,u.current=v.fresh}let h=e.session.current??"",y=e.quiet||e.oneShot?[]:na(d,h,e.host,m,g.current),b=e.mode==="rich"&&!e.quiet&&!e.oneShot?await d.history(h):[],R={...e,source:d,sessionKey:h,banner:y,prior:b,quiet:e.quiet,reader:e.reader,draft:e.draft,showReasoning:e.noReasoning!==!0,freshSession:u.current,switchTo:l,random:e.random},w=e.mode==="rich"?await Bs(R):await Vs(R);if(w!==ce)return await d.close(),w;if(l.current===void 0)m="restart";else m=l.current.reason,g.current=h,e.session.current=l.current.key,l.current=void 0;u.current=!1}}async function Bs(e){let[{render:r},{createElement:o},{App:i}]=await Promise.all([import("ink"),import("react"),import("./App-ez7ve0yp.js")]),s=De();P(()=>{s.close()}),tA(),ur(),process.stdout.write(`${sA}${Wr}`);let a=!1,d=r(o(i,{source:e.source,onSwitch:(l,m)=>{a=!0,e.switchTo.current={key:l,reason:"switch"},e.draft.current=m},onNew:(l)=>{a=!0,e.switchTo.current={key:Uo(e.random),reason:"new"},e.draft.current=l},sessions:async()=>[...await e.source.sessions()].sort(Qe).map((m)=>({sessionKey:m.sessionKey,messages:m.messages,turns:m.turns,lastActivityAt:m.lastActivityAt,phase:m.phase})),onRestart:(l)=>{a=!0,e.draft.current=l},sessionKey:e.sessionKey,model:e.source.describe().model,agentName:e.source.describe().agentId,freshSession:e.freshSession,warnings:e.source.describe().warnings.map((l)=>l.message),initial:zi(Wi(e.banner.slice(1)),e.prior),correctKeys:s.correct,showReasoning:e.showReasoning,quiet:e.quiet,...e.manifestPath===void 0?{}:{manifestPath:e.manifestPath},catalogue:{load:(l)=>It({onStatus:l}),install:async(l,m)=>Ht(Xi(l,m))},status:()=>e.embedded===void 0?Xs(e.source):Js(e.embedded),contextView:()=>zs(e,e.sessionKey),...e.draft.current===""?{}:{initialDraft:e.draft.current}}),{exitOnCtrlC:!1,...Oe(e.noEnhancedKeys)});if(P(()=>d.unmount()),await d.waitUntilExit(),Le(),!a)process.stdout.write(Ms({ref:e.source.describe().agentId,sessionKey:e.sessionKey}));return a?ce:n}async function Vs(e){let{source:r,sessionKey:o,quiet:i}=e,s=!0,a=(T)=>{if(T==="")return;process.stdout.write(T),s=T.endsWith(`
212
+ `)},d=(T)=>{if(!s)a(`
213
+ `);a(`${T}
214
+ `)};if(e.banner.length>0)a(`${e.banner.join(`
294
215
  `)}
295
216
 
296
- `);let g=!u&&r.once===void 0,v=!1,k,y=o.streamFilter(),S=(z)=>{if(z==="")return;f(z),v=!0},P=r.source.subscribe((z)=>{switch(z.type){case"model.result":S(y.endStep());return;case"model.chunk":{let{delta:V,kind:Q}=z.data;if(Q==="reasoning"&&r.showReasoning!==!0)return;if(Q!==k){if(k!==void 0)f(`
217
+ `);let l=!i&&e.once===void 0,m=!1,g,u=r.streamFilter(),h=(T)=>{if(T==="")return;a(T),m=!0},y=e.source.subscribe((T)=>{switch(T.type){case"model.result":h(u.endStep());return;case"model.chunk":{let{delta:O,kind:_}=T.data;if(_==="reasoning"&&e.showReasoning!==!0)return;if(_!==g){if(g!==void 0)a(`
297
218
 
298
- `);if(r.showReasoning===!0)f(Q==="reasoning"?`· reasoning ·
219
+ `);if(e.showReasoning===!0)a(_==="reasoning"?`· reasoning ·
299
220
  `:`· reply ·
300
- `);k=Q}if(Q==="reasoning"){f(V),v=!0;return}S(y.push(V));return}case"tool.result":{if(!g)return;let{slug:V,ok:Q,latencyMs:re,truncated:he}=z.data;h(` · ${V} — ${Q?"ok":"failed"} · ${re} ms${he?" · observation trimmed":""}`);return}case"agent.warning":h(` · ${z.data.message}
301
- ${z.data.hint}`);return;case"tool.repair":if(g)h(` · ${z.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":h(` · ${z.data.slug} — blocked: ${z.data.reason}`);return;case"context.dropped":h(` · context: ${z.data.messages} older message(s) did not fit the ${z.data.budget}-token budget and were left out`);return;default:return}}),U=async(z)=>{let V=on(z);if(V===void 0)return"prompt";switch(V.kind){case"exit":return"exit";case"restart":{let Q=o.reload;if(Q===void 0)return"restart";try{let re=await Q();h(`reloaded ${re.join(", ")} — this conversation continues`)}catch(re){h(`could not reload: ${re instanceof Error?re.message:String(re)}`)}return"handled"}case"new":return r.switchTo.current={key:Hn(r.random),reason:"new"},"restart";case"help":return h(sn()),"handled";case"tools":return h(lt(await o.tools())),"handled";case"status":return h(r.embedded===void 0?await so(o):await ro(r.embedded)),"handled";case"context":return h(await oo(r,a)),"handled";case"reset":return await o.clearSession(a),h("session cleared — memory files on disk are untouched"),"handled";case"unknown":return h($t(V)),"handled";case"command":return h(`${V.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${e.slug} ${V.name}${V.rest===""?"":` ${V.rest}`}\``),"handled"}},W,F=0,I=n,de=(z=r.reader.current)=>{if(W!==void 0&&!W.signal.aborted){F=performance.now(),W.abort();return}z?.close(),f(`
302
- `)},oe=async(z)=>{W=new AbortController,v=!1,k=void 0,y=o.streamFilter();let V=await o.send(z,{sessionKey:a,signal:W.signal});if(W=void 0,S(y.end()),v&&!i)f(`
303
- `);else if(!v&&V.text!=="")f(`${V.text}
304
- `);let Q=ze(V.reason,{steps:V.steps,durationMs:V.durationMs,...F===0?{}:{cancelledAfterMs:performance.now()-F}});if(Q!==void 0)f(`
305
- (${Q})
306
- `);if(V.reason==="error"&&V.error!==void 0)process.stderr.write(`
307
- ${V.error.code}: ${V.error.message}
308
- hint: ${V.error.hint}
309
- `);if(xr(V.reason))I=s;if(!u&&V.reason==="final")f(` ${V.tokens.prompt} prompt · ${V.tokens.output} output · ${V.durationMs} ms
221
+ `);g=_}if(_==="reasoning"){a(O),m=!0;return}h(u.push(O));return}case"tool.result":{if(!l)return;let{slug:O,ok:_,latencyMs:C,truncated:B}=T.data;d(` · ${O} — ${_?"ok":"failed"} · ${C} ms${B?" · observation trimmed":""}`);return}case"agent.warning":d(` · ${T.data.message}
222
+ ${T.data.hint}`);return;case"tool.repair":if(l)d(` · ${T.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":d(` · ${T.data.slug} — blocked: ${T.data.reason}`);return;case"context.dropped":d(` · context: ${T.data.messages} older message(s) did not fit the ${T.data.budget}-token budget and were left out`);return;default:return}}),b=async(T)=>{let O=sn(T,gn());if(O===void 0)return"prompt";switch(O.kind){case"exit":return"exit";case"restart":{let _=r.reload;if(_===void 0)return"restart";try{let C=await _();d(`reloaded ${C.join(", ")} — this conversation continues`)}catch(C){d(`could not reload: ${C instanceof Error?C.message:String(C)}`)}return"handled"}case"new":return e.switchTo.current={key:Uo(e.random),reason:"new"},"restart";case"help":return d(an()),"handled";case"tools":return d(tt(await r.tools())),"handled";case"status":return d(e.embedded===void 0?await Xs(r):await Js(e.embedded)),"handled";case"context":return d(await zs(e,o)),"handled";case"reset":return await r.clearSession(o),d("session cleared — memory files on disk are untouched"),"handled";case"unknown":return d(Ot(O)),"handled";case"command":return d(`${O.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${A.slug} ${O.name}${O.rest===""?"":` ${O.rest}`}\``),"handled"}},R,w=0,v=n,U=(T=e.reader.current)=>{if(R!==void 0&&!R.signal.aborted){w=performance.now(),R.abort();return}T?.close(),a(`
223
+ `)},k=async(T)=>{R=new AbortController,m=!1,g=void 0,u=r.streamFilter();let O=await r.send(T,{sessionKey:o,signal:R.signal});if(R=void 0,h(u.end()),m&&!s)a(`
224
+ `);else if(!m&&O.text!=="")a(`${O.text}
225
+ `);let _=PA(O.reason,{steps:O.steps,durationMs:O.durationMs,...w===0?{}:{cancelledAfterMs:performance.now()-w}});if(_!==void 0)a(`
226
+ (${_})
227
+ `);if(O.reason==="error"&&O.error!==void 0)process.stderr.write(`
228
+ ${O.error.code}: ${O.error.message}
229
+ hint: ${O.error.hint}
230
+ `);if(Ei(O.reason))v=c;if(!i&&O.reason==="final")a(` ${O.tokens.prompt} prompt · ${O.tokens.output} output · ${O.durationMs} ms
310
231
 
311
- `);await ue()},ge=()=>de();process.on("SIGINT",ge);try{if(r.once!==void 0)return await oe(r.once),I;if(process.stdin.isTTY!==!0){let V=r.reader.current??Zs({input:process.stdin});r.reader.current=V;for await(let Q of V){let re=Q.trim();if(re==="")continue;let he=await U(re);if(he==="exit")break;if(he==="restart"){I=Ne;break}if(he==="handled")continue;await oe(re)}return I}let z=r.reader.current??Zs({input:process.stdin,output:process.stdout,prompt:An,terminal:!1});r.reader.current=z,z.prompt();for await(let V of z){let Q=V.trim();if(Q===""){z.prompt();continue}let re=await U(Q);if(re==="exit")break;if(re==="restart"){I=Ne;break}if(re==="handled"){z.prompt();continue}await oe(Q),z.prompt()}if(I!==Ne)z.close(),r.reader.current=void 0;return I}finally{process.off("SIGINT",ge),P()}}async function ro(r){let{agent:o,runtime:a}=r,u=o.describe(),i=o.manifest,f=i.channels.filter((y)=>y.enabled).map((y)=>`${y.id} (${y.type})`).join(", "),h=f===""?"none — reached through this session and the HTTP API only":a.channels.started?`${f} — connected in this session`:`${f} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,g=!i.server.enabled?"off":`enabled on ${i.server.host}:${i.server.port}, NOT bound here — \`serve\` binds it`,v=ye(i),k=v.filter((y)=>y.role!=="main"&&y.role===y.configuredAs);return l([{label:"agent",value:`${u.id} (${u.name})`},{label:"model",value:`${u.model} · ${i.tools.dialect} · ${u.window} token window (${je(v[0]?.window)})`},...k.map((y)=>({label:y.role,value:`${y.modelId} · ${y.window.contextWindow} token window (${je(y.window)})`})),{label:"channels",value:h},{label:"http api",value:g},{label:"store",value:a.store.location},{label:"background",value:await Ra(a,u.id)}])}async function so(r){let o=r.describe(),a=r.host,[u,i]=await Promise.all([r.tools(),r.sessions()]);return l([{label:"agent",value:`${o.agentId} (${o.name})`},{label:"attached to",value:a===void 0?"a host":`${a.baseUrl} · pid ${a.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${o.model} · ${o.window} token window`},{label:"dialect",value:o.dialect},{label:"tools",value:`${u.tools.length} pinned · ${u.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${i.length} on this agent`},{label:"warnings",value:o.warnings.length===0?"none":o.warnings.map((f)=>f.message).join("; ")}])}async function Ea(r,o){let a=await r.previewContext({sessionKey:o}),[u]=ye(r.manifest);return{slots:a.slots,history:a.history,cache:a.cache,total:a.total,window:a.window,windowSource:je(u?.window),wireTokens:a.wireTokens,reserveOutput:a.reserveOutput,calibration:a.calibration,lastCompaction:a.compactions===0?void 0:`${a.compactions} stage${a.compactions===1?"":"s"} run this session`}}async function oo(r,o){return bo(await r.source.context(o))}async function Ra(r,o){if(r.owned.includes(o))return"this session is serving this agent";let a=await r.store.leases.get(o);if(a!==void 0&&_(a.pid))return a.mode==="daemon"?`running as a background service · pid ${a.pid} · \`${e.slug} daemon status ${o}\``:`served by another session · pid ${a.pid} (${a.mode})`;return`not supervised — \`${e.slug} daemon install ${o}\` keeps it running without a terminal`}function be(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function Ia(r,o){if(!r.enabled)return"off";if(r.nextRunAt===void 0)return"done";let a=Date.parse(r.nextRunAt)-o;if(a<=0)return"due";let u=Math.round(a/60000);if(u<60)return`in ${u}m`;let i=Math.round(a/3600000);return i<48?`in ${i}h`:`in ${Math.round(i/24)}d`}function Ta(r,o){if(r.lastFiredAt===void 0)return"never run";let a=qe(r.lastFiredAt,o);if(r.lastStatus==="error")return`FAILED ${a}`;return`ok ${a}`}function Aa(r,o){if(r.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let a=Math.max(8,...r.map((f)=>f.id.length)),u=Math.max(4,...r.map((f)=>`${f.kind} ${f.expr}`.length));process.stdout.write(`${be("SCHEDULE",a)} ${be("WHEN",u)} ${be("NEXT",7)} LAST
312
- `);for(let f of r)process.stdout.write(`${be(f.id,a)} ${be(`${f.kind} ${f.expr}`,u)} ${be(Ia(f,o),7)} ${Ta(f,o)}
313
- `);let i=r.filter((f)=>f.lastStatus==="error");if(i.length>0)process.stdout.write(`
314
- ${i.length} failing — \`schedules --id ${i[0]?.id}\` for the error
315
- `)}function Oa(r){let o=[["kind",`${r.kind} ${r.expr}`],["timezone",r.timezone??"(host)"],["task",r.task],["deliver",r.deliverChannel===void 0?"none — the reply reaches the event stream only":`${r.deliverChannel} → ${r.deliverTo}`],["session",r.sessionMode],["model role",r.role??"main"],["enabled",r.enabled?"yes":"no"],["declared in",r.origin==="manifest"?"agent.yaml":"the API"],["next run",r.nextRunAt??"(never again)"],["runs",String(r.runs)],["last run",r.lastFiredAt??"never"],["last status",r.lastStatus??"-"]];if(r.lastError!==void 0)o.push(["last error",r.lastError]);let a=Math.max(...o.map(([u])=>u.length));process.stdout.write(`${r.id}
316
- `);for(let[u,i]of o)process.stdout.write(` ${be(u,a)} ${i}
317
- `)}function _a(r,o){let a=new Set(o),u=new Map;for(let i of r){if(!a.has(i.channel))continue;let f=`${i.channel}\x00${i.peerId}`,h=u.get(f);if(h!==void 0&&h.lastSeen>=i.lastActivityAt)continue;u.set(f,{channelId:i.channel,address:i.peerId,lastSeen:i.lastActivityAt})}return[...u.values()].sort((i,f)=>i.channelId===f.channelId?f.lastSeen.localeCompare(i.lastSeen):i.channelId.localeCompare(f.channelId))}function Ca(r,o){if(r.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
232
+ `);await Xe()},j=()=>U();process.on("SIGINT",j);try{if(e.once!==void 0)return await k(e.once),v;if(process.stdin.isTTY!==!0){let O=e.reader.current??Gs({input:process.stdin});e.reader.current=O;for await(let _ of O){let C=_.trim();if(C==="")continue;let B=await b(C);if(B==="exit")break;if(B==="restart"){v=ce;break}if(B==="handled")continue;await k(C)}return v}let T=e.reader.current??Gs({input:process.stdin,output:process.stdout,prompt:zn,terminal:!1});e.reader.current=T,T.prompt();for await(let O of T){let _=O.trim();if(_===""){T.prompt();continue}let C=await b(_);if(C==="exit")break;if(C==="restart"){v=ce;break}if(C==="handled"){T.prompt();continue}await k(_),T.prompt()}if(v!==ce)T.close(),e.reader.current=void 0;return v}finally{process.off("SIGINT",j),y()}}async function Js(e){let{agent:r,runtime:o}=e,i=r.describe(),s=r.manifest,a=s.channels.filter((u)=>u.enabled).map((u)=>`${u.id} (${u.type})`).join(", "),d=a===""?"none — reached through this session and the HTTP API only":o.channels.started?`${a} — connected in this session`:`${a} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,l=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,m=oA(s),g=m.filter((u)=>u.role!=="main"&&u.role===u.configuredAs);return E([{label:"agent",value:`${i.id} (${i.name})`},{label:"model",value:`${i.model} · ${s.tools.dialect} · ${i.window} token window (${GA(m[0]?.window)})`},...g.map((u)=>({label:u.role,value:`${u.modelId} · ${u.window.contextWindow} token window (${GA(u.window)})`})),{label:"channels",value:d},{label:"http api",value:l},{label:"store",value:o.store.location},{label:"background",value:await ra(o,i.id)}])}async function Xs(e){let r=e.describe(),o=e.host,[i,s]=await Promise.all([e.tools(),e.sessions()]);return E([{label:"agent",value:`${r.agentId} (${r.name})`},{label:"attached to",value:o===void 0?"a host":`${o.baseUrl} · pid ${o.pid}`},{label:"this session",value:"a view — the agent runs in the host, and stays running when this exits"},{label:"model",value:`${r.model} · ${r.window} token window`},{label:"dialect",value:r.dialect},{label:"tools",value:`${i.tools.length} pinned · ${i.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:r.warnings.length===0?"none":r.warnings.map((a)=>a.message).join("; ")}])}async function sa(e,r){let o=await e.previewContext({sessionKey:r}),[i]=oA(e.manifest);return{slots:o.slots,history:o.history,cache:o.cache,total:o.total,window:o.window,windowSource:GA(i?.window),wireTokens:o.wireTokens,reserveOutput:o.reserveOutput,calibration:o.calibration,lastCompaction:o.compactions===0?void 0:`${o.compactions} stage${o.compactions===1?"":"s"} run this session`}}async function zs(e,r){return ji(await e.source.context(r))}async function ra(e,r){if(e.owned.includes(r))return"this session is serving this agent";let o=await e.store.leases.get(r);if(o!==void 0&&J(o.pid))return o.mode==="daemon"?`running as a background service · pid ${o.pid} · \`${A.slug} daemon status ${r}\``:`served by another session · pid ${o.pid} (${o.mode})`;return`not supervised — \`${A.slug} daemon install ${r}\` keeps it running without a terminal`}function Q(e,r){return e.length>=r?e:e+" ".repeat(r-e.length)}function oa(e,r){if(!e.enabled)return"off";if(e.nextRunAt===void 0)return"done";let o=Date.parse(e.nextRunAt)-r;if(o<=0)return"due";let i=Math.round(o/60000);if(i<60)return`in ${i}m`;let s=Math.round(o/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function ia(e,r){if(e.lastFiredAt===void 0)return"never run";let o=YA(e.lastFiredAt,r);if(e.lastStatus==="error")return`FAILED ${o}`;return`ok ${o}`}function aa(e,r){if(e.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let o=Math.max(8,...e.map((a)=>a.id.length)),i=Math.max(4,...e.map((a)=>`${a.kind} ${a.expr}`.length));process.stdout.write(`${Q("SCHEDULE",o)} ${Q("WHEN",i)} ${Q("NEXT",7)} LAST
233
+ `);for(let a of e)process.stdout.write(`${Q(a.id,o)} ${Q(`${a.kind} ${a.expr}`,i)} ${Q(oa(a,r),7)} ${ia(a,r)}
234
+ `);let s=e.filter((a)=>a.lastStatus==="error");if(s.length>0)process.stdout.write(`
235
+ ${s.length} failing — \`schedules --id ${s[0]?.id}\` for the error
236
+ `)}function da(e){let r=[["kind",`${e.kind} ${e.expr}`],["timezone",e.timezone??"(host)"],["task",e.task],["deliver",e.deliverChannel===void 0?"none — the reply reaches the event stream only":`${e.deliverChannel} → ${e.deliverTo}`],["session",e.sessionMode],["model role",e.role??"main"],["enabled",e.enabled?"yes":"no"],["declared in",e.origin==="manifest"?"agent.yaml":"the API"],["next run",e.nextRunAt??"(never again)"],["runs",String(e.runs)],["last run",e.lastFiredAt??"never"],["last status",e.lastStatus??"-"]];if(e.lastError!==void 0)r.push(["last error",e.lastError]);let o=Math.max(...r.map(([i])=>i.length));process.stdout.write(`${e.id}
237
+ `);for(let[i,s]of r)process.stdout.write(` ${Q(i,o)} ${s}
238
+ `)}function la(e,r){let o=new Set(r),i=new Map;for(let s of e){if(!o.has(s.channel))continue;let a=`${s.channel}\x00${s.peerId}`,d=i.get(a);if(d!==void 0&&d.lastSeen>=s.lastActivityAt)continue;i.set(a,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...i.values()].sort((s,a)=>s.channelId===a.channelId?a.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(a.channelId))}function ca(e,r){if(e.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
318
239
  `+` An address appears here once a first message arrives on one.
319
- `);return}let a=Math.max(7,...r.map((i)=>i.channelId.length)),u=Math.max(7,...r.map((i)=>i.address.length));process.stdout.write(`${be("CHANNEL",a)} ${be("ADDRESS",u)} LAST SEEN
320
- `);for(let i of r)process.stdout.write(`${be(i.channelId,a)} ${be(i.address,u)} ${qe(i.lastSeen,o)}
240
+ `);return}let o=Math.max(7,...e.map((s)=>s.channelId.length)),i=Math.max(7,...e.map((s)=>s.address.length));process.stdout.write(`${Q("CHANNEL",o)} ${Q("ADDRESS",i)} LAST SEEN
241
+ `);for(let s of e)process.stdout.write(`${Q(s.channelId,o)} ${Q(s.address,i)} ${YA(s.lastSeen,r)}
321
242
  `);process.stdout.write(`
322
243
  Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
323
244
  `+`never a person — a private chat is reached by the numeric id above.
324
- `)}async function io(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath]),lease:!1});b(()=>o.stop("cli-exit"));let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=Date.now();for(let[f,h]of[[r.enable,!0],[r.disable,!1]]){if(f===void 0)continue;let g=await a.store.schedules.get(a.id,f);if(g===void 0)return process.stderr.write(`no schedule "${f}" on ${a.id}
245
+ `)}async function Qs(e){let r=await ge.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath]),lease:!1});P(()=>r.stop("cli-exit"));let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let i=Date.now();for(let[a,d]of[[e.enable,!0],[e.disable,!1]]){if(a===void 0)continue;let l=await o.store.schedules.get(o.id,a);if(l===void 0)return process.stderr.write(`no schedule "${a}" on ${o.id}
325
246
  hint: run \`schedules\` with no flags to see what this agent has.
326
- `),s;if(g.origin==="manifest")return process.stderr.write(`${f} is declared in agent.yaml, so the manifest decides whether it runs.
247
+ `),c;if(l.origin==="manifest")return process.stderr.write(`${a} is declared in agent.yaml, so the manifest decides whether it runs.
327
248
  `+` Writing it here would last until the next start — reconciliation restores every
328
249
  `+` field from the file, enabled included.
329
250
 
330
- hint: set \`enabled: ${h}\` on the "${f}" entry under schedules: in
331
- ${r.manifestPath}
332
- `),s;await a.store.schedules.setEnabled(a.id,f,h,new Date(u).toISOString()),process.stdout.write(h?`${f} enabled — it fires at its next occurrence, not now
333
- `:`${f} disabled — still listed, and it keeps its place in the sequence
334
- `)}if(r.recipients===!0){let f=_a(await a.store.sessions.list(a.id),a.manifest.channels.map((h)=>h.id));if(r.json===!0)return process.stdout.write(`${JSON.stringify({recipients:f},null,2)}
335
- `),n;return Ca(f,u),n}let i=await a.store.schedules.list(a.id);if(r.json)return process.stdout.write(`${JSON.stringify({schedules:i},null,2)}
336
- `),n;if(r.id!==void 0){let f=i.find((h)=>h.id===r.id);if(f===void 0)return process.stderr.write(`no schedule "${r.id}" on ${a.id}
337
- `),s;return Oa(f),n}if(r.enable===void 0&&r.disable===void 0)Aa(i,u);return n}import{dirname as lo,resolve as Dt}from"node:path";function Na(){return mt.shape.server.parse({})}async function co(r){let o=m(r.manifestPaths),a=r.store??w(),u=await zr(r.manifestPaths,o,a),i=u.filter((D)=>!D.enabled),f=u.filter((D)=>D.enabled),h=r.manifestPaths.length===0,g=[],v=[];for(let D of f)try{let ne=T(D.manifestPath),se=await yt({refs:ne.plugins??[],agentId:ne.id??D.manifestPath,paths:{workspace:lo(Dt(D.manifestPath)),state:lo(Dt(D.manifestPath)),manifest:Dt(D.manifestPath)},env:o,bus:new _e({runtimeId:"serve-preload"}),builtIn:C,base:{toolProviders:A,channels:N}});g.push({path:D.manifestPath,loaded:x(D.manifestPath,{knownProviders:Object.keys(se.toolProviders),knownChannels:Object.keys(se.channels),env:o})})}catch(ne){if(!h)throw ne;v.push({path:D.manifestPath,detail:tr(ne)?ne.message:String(ne),...tr(ne)&&ne.hint!==void 0?{hint:ne.hint}:{}})}let k=g[0],y=k?.loaded,S=y?.manifest.server??Na();for(let D of g.slice(1)){let ne=D.loaded.manifest.server;for(let[se,De,rn,Le]of[["server.port",S.port,ne.port,r.port!==void 0],["server.host",S.host,ne.host,r.host!==void 0],["server.tokenEnv",S.tokenEnv,ne.tokenEnv,!1]]){if(Le||De===rn)continue;throw new t({code:"serve_bind_conflict",message:`${k?.path??"the first manifest"} sets ${se} to ${String(De)} and ${D.path} sets it to ${String(rn)}.`,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:se})}}let P=r.port??S.port,U=r.host??S.host,W=y===void 0?o[S.tokenEnv]:y.env[S.tokenEnv],F=o[`${e.envPrefix}SERVICE`]!==void 0,I=new _e({runtimeId:`rt_${Date.now().toString(36)}`});if(r.json!==!0)I.on("agent.channel.status",(D)=>{let ne=D.data,se=ne.input===void 0?"":` (${ne.input.kind}${ne.input.expiresAt===void 0?"":`, expires ${ne.input.expiresAt}`} — GET /v1/agents/${D.agentId??""} carries it)`;process.stdout.write(` ${ne.channelId}: ${ne.status}${ne.detail===void 0?"":` — ${ne.detail}`}${se}
338
- `)}),I.on("agent.channel.error",(D)=>{let ne=D.data;process.stderr.write(` ${ne.channelId}: ${ne.message}
339
- hint: ${ne.hint}
340
- `)}),I.on("agent.channel.rejected",(D)=>{let ne=D.data;process.stdout.write(` ${ne.channelId}: ${ne.reason} — ${ne.detail}
341
- `)});let de=cr(),oe=await L.create({agents:g.map((D)=>D.path),approve:de.approver,env:o,bus:I,toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,startChannels:!0,startSchedules:!0,store:a,mode:F?"daemon":"terminal"});Vr();let ge=Fa(),z=await oe.store.operatorKeys.liveCount(),V=z===0||r.claim===!0?Lr():void 0,Q;try{Q=await Ur({runtime:oe,host:U,port:P,approvals:de,allowedOrigins:S.allowedOrigins,allowedHosts:S.allowedHosts,resolveAgent:(D)=>Kt(D,o),provision:{steps:()=>es({agentDirBase:B(o)}),create:(D)=>ns({answers:D,defaults:{agentDirBase:B(o)}})},...V===void 0?{}:{claim:V},...W===void 0||W===""?{}:{token:W}})}catch(D){if(await oe.stop("server failed to bind"),D instanceof t)throw D;throw new t({code:"server_bind_failed",message:`Could not bind ${U}:${P}: ${D instanceof Error?D.message:String(D)}`,hint:"Another process is probably on that port. Pass --port, or set server.port in the manifest.",cause:D})}await oe.publishAddress(Q.url);let re=oe.list(),he=re[0];if(he!==void 0)process.title=re.length===1?`${e.slug} ${he.id}`:`${e.slug} ${re.length} agents`;for(let D of re)D.reportRuntimeState({serverListening:!0});if(r.json===!0)process.stdout.write(`${JSON.stringify({url:Q.url,websocket:Q.websocket,authenticated:W!==void 0&&W!=="",keys:z,...V===void 0?{}:{claim:V.token},agents:re.map((D)=>({id:D.id,channels:oe.channels.statusOf(D.id)})),declined:oe.declined.map((D)=>({agentId:D.agentId,pid:D.pid,mode:D.mode,since:D.startedAt})),disabled:i.map((D)=>({agentId:D.agentId,...D.reason===void 0?{}:{reason:D.reason}})),broken:v.map((D)=>({path:D.path,detail:D.detail,...D.hint===void 0?{}:{hint:D.hint}}))})}
342
- `);else{let D=`http://${Xe(U)}:${Q.port}`,ne=D===Q.url?"":` (bound ${U} — every interface)`;process.stdout.write(`${e.name} serving on ${D}${ne}
343
- `),process.stdout.write(` web UI ${D}/ · API reference ${D}/docs
344
- `);for(let se of re){let De=oe.channels.statusOf(se.id),rn=De.length===0?"no channels":De.map((an)=>`${an.id} (${an.type})`).join(", "),Le=se.manifest.schedules.filter((an)=>an.enabled),Po=se.manifest.schedules.length===0?"":`, ${Le.length} schedule${Le.length===1?"":"s"}${se.manifest.schedules.length>Le.length?` (+${se.manifest.schedules.length-Le.length} disabled)`:""}`;process.stdout.write(` ${se.id} — ${rn}${Po}
345
- `)}for(let se of i)process.stdout.write(` ${se.agentId} — stopped${se.reason===void 0?"":` (${se.reason})`}, \`${e.slug} start ${se.agentId}\`
346
- `);for(let se of v)if(process.stdout.write(` ${se.path} — NOT served: ${se.detail}
347
- `),se.hint!==void 0)process.stdout.write(` hint: ${se.hint}
348
- `);for(let se of oe.declined)process.stdout.write(` ${se.agentId} — NOT served here: pid ${se.pid} (${se.mode}) already has it
349
- `);if(oe.declined.length>0)process.stdout.write(` \`${e.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
350
- `);if(V!==void 0){if(process.stdout.write(` open once to claim this server:
351
- ${Dr(U,Q.port,V.token)}
352
- without a browser: ${Fr(U,Q.port,V.token)}
353
- `),W===void 0||W==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
354
- `)}if(W===void 0||W==="")process.stdout.write(` unauthenticated — loopback only. Set ${S.tokenEnv} to bind a public host.
355
- `);if(!Q.websocket)process.stdout.write(` /v1/ws unavailable under Node — SSE and HTTP are unaffected.
356
- `);if(F)process.stdout.write(` running as a background service · ${e.slug} daemon status ${re[0]?.id??""}
357
- `);else if(dt())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
358
- `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${e.slug} daemon install${re[0]?.id===void 0?"":` ${re[0].id}`}\` keeps it running.
359
- `)}let fe=!1,Ae=async()=>{if(fe)return;fe=!0,await Q.stop(),await oe.stop("interrupted")};return b(Ae),await ge,process.stdout.write(`stopping
360
- `),await Ae(),n}function Fa(){return new Promise((r)=>{let o=()=>{process.off("SIGINT",o),process.off("SIGTERM",o),r()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function me(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function La(r){let o=new Map,a=[];for(let u of r){let i=u.sessionKey.split(":"),f={sessionKey:u.sessionKey,phase:u.phase,messages:u.messages,turns:u.turns,lastActivityAt:u.lastActivityAt};if(i.length!==3||i[0]!=="schedule"){a.push(f);continue}let h=`schedule:${i[1]}`,g=o.get(h);if(g===void 0){let v={...f,sessionKey:`${h}:*`,runs:1};o.set(h,v),a.push(v);continue}if(g.runs=(g.runs??1)+1,g.messages+=u.messages,g.turns+=u.turns,u.lastActivityAt>g.lastActivityAt)g.lastActivityAt=u.lastActivityAt}return a}function ja(r){if(r.length===0){process.stdout.write(`no sessions yet
361
- `);return}let o=La(r),a=Math.max(7,...o.map((u)=>u.sessionKey.length));process.stdout.write(`${me("SESSION",a)} ${me("MSGS",5)} ${me("TURNS",5)} ${me("PHASE",8)} LAST
362
- `);for(let u of o){let i=u.runs===void 0?"":` (${u.runs} run${u.runs===1?"":"s"})`;process.stdout.write(`${me(u.sessionKey,a)} ${me(String(u.messages),5)} ${me(String(u.turns),5)} ${me(u.phase??"-",8)} ${qe(u.lastActivityAt,Date.now())}${i}
363
- `)}}async function Ma(r,o,a){let u=await r.store.messages.page(r.id,o,{limit:a});if(u.messages.length===0){process.stdout.write(`no messages in ${o}
364
- `);return}for(let i of[...u.messages].reverse())process.stdout.write(`${i.role}: ${i.content}
365
- `);if(u.nextBefore!==void 0)process.stdout.write(`
251
+ hint: set \`enabled: ${d}\` on the "${a}" entry under schedules: in
252
+ ${e.manifestPath}
253
+ `),c;await o.store.schedules.setEnabled(o.id,a,d,new Date(i).toISOString()),process.stdout.write(d?`${a} enabled — it fires at its next occurrence, not now
254
+ `:`${a} disabled — still listed, and it keeps its place in the sequence
255
+ `)}if(e.recipients===!0){let a=la(await o.store.sessions.list(o.id),o.manifest.channels.map((d)=>d.id));if(e.json===!0)return process.stdout.write(`${JSON.stringify({recipients:a},null,2)}
256
+ `),n;return ca(a,i),n}let s=await o.store.schedules.list(o.id);if(e.json)return process.stdout.write(`${JSON.stringify({schedules:s},null,2)}
257
+ `),n;if(e.id!==void 0){let a=s.find((d)=>d.id===e.id);if(a===void 0)return process.stderr.write(`no schedule "${e.id}" on ${o.id}
258
+ `),c;return da(a),n}if(e.enable===void 0&&e.disable===void 0)aa(s,i);return n}import{readFileSync as ua}from"node:fs";var fa="server.tokenEnv";function Bn(e){let r=ua(e,"utf8"),o=EA(e),i=new Map,s=new Set(pt(r).filter((a)=>a.path===fa).map((a)=>a.name));for(let a of pt(r)){if(s.has(a.name))continue;let d=i.get(a.name)??[];d.push(a.path),i.set(a.name,d)}return[...i].map(([a,d])=>({name:a,set:bt(o,a),usedBy:d}))}function Ys(e,r){let o=Bn(e).map((d)=>d.name);for(let[d,l]of Object.entries(r)){if(!o.includes(d))throw new t({code:"secret_not_referenced",message:`"${d}" is not a variable this agent's manifest reads.`,hint:o.length===0?"This agent's manifest reads no variables a caller may set.":`It reads ${o.join(", ")}. A variable is settable when the manifest names it, as \${NAME} or through an *Env field; the server's own token never is. GET /v1/agents/:id/secrets lists them.`,field:`values.${d}`});if(l==="")throw new t({code:"secret_value_empty",message:`An empty value for ${d} would not start the agent.`,hint:"A variable set to nothing fails the load exactly as a missing one does. Nothing was written.",field:`values.${d}`})}let i=M([e]),s=[],a=[];for(let[d,l]of Object.entries(r))if(Re(e,d,l),s.push(d),bt(i,d))a.push(d);return{written:s,shadowed:a}}import{existsSync as Vn,lstatSync as Xn,mkdirSync as Zs,readdirSync as dr,readFileSync as fr,renameSync as ma,rmSync as pa}from"node:fs";import{basename as Jn,dirname as ha,join as ne}from"node:path";var Pe="template.yaml",mr=/^[a-z0-9][a-z0-9-]*$/;function Yn(e){let r;try{r=dr(e)}catch{return[]}let o=[];for(let i of r.sort()){if(!mr.test(i))continue;let s=ne(e,i);if(!Xn(s).isDirectory())continue;try{let a=hr(s);o.push({name:i,...a.description===void 0?{}:{description:a.description},vars:a.vars.map((d)=>({name:d.name,...d.description===void 0?{}:{description:d.description},required:d.required,...d.default===void 0?{}:{default:d.default},secret:d.secret!==void 0}))})}catch(a){if(!Ge(a))throw a;o.push({name:i,vars:[],problem:{code:a.code,message:a.message,hint:a.hint}})}}return o}function hr(e){let r=ne(e,Pe);if(!Vn(r))throw new t({code:"template_spec_missing",message:`${Jn(e)} has no ${Pe}.`,hint:`A template is an agent directory with a ${Pe} beside agent.yaml declaring its variables. An empty one (\`vars: {}\`) is valid.`});return di(fr(r,"utf8"),`${Jn(e)}/${Pe}`)}function yr(e,r=""){let o=[];for(let i of dr(ne(e,r)).sort()){let s=r===""?i:`${r}/${i}`;if(s===Pe)continue;let a=ne(e,s),d=Xn(a);if(d.isSymbolicLink())throw new t({code:"template_symlink",message:`${s} in the template is a symbolic link.`,hint:"A template is copied into every agent made from it, and a link would copy whatever it points at. Replace it with the file itself.",field:s});if(d.isDirectory()){o.push(...yr(e,s));continue}let l=fr(a);if(l.includes(0))throw new t({code:"template_binary_file",message:`${s} in the template is not a text file.`,hint:"Templates are rendered by text substitution, which would corrupt a binary file. Leave it out of the template and add it to the agent afterwards.",field:s});o.push({relPath:s,contents:l.toString("utf8")})}return o}function wr(e){if(!mr.test(e.template))throw ar(e.template,e.templatesDir);let r=ne(e.templatesDir,e.template);if(!Vn(r)||!Xn(r).isDirectory())throw ar(e.template,e.templatesDir);let o=e.name.trim();if(o==="")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=je(o),s=ne(e.agentDirBase,i);if(Vn(s))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=Bi({spec:hr(r),files:yr(r),id:i,name:o,vars:e.vars}),d=ne(ha(e.agentDirBase),`.${Jn(e.agentDirBase)}-staging`,`${i}-${crypto.randomUUID().slice(0,8)}`);Zs(d,{recursive:!0});try{$e(d,a.files);let l=ne(d,"agent.yaml");for(let[u,h]of Object.entries(a.env))Re(l,u,h);let m=a.files.find((u)=>u.relPath==="agent.yaml"),g={};for(let u of pt(m?.contents??""))if(a.env[u.name]===void 0)g[u.name]="(pending)";Ke(l,g),Zs(e.agentDirBase,{recursive:!0}),ma(d,s)}catch(l){throw pa(d,{recursive:!0,force:!0}),l}return{agentId:i,dir:s,manifestPath:ne(s,"agent.yaml"),files:[...a.files.map((l)=>l.relPath),...Object.keys(a.env).length>0?[".env"]:[]]}}function ar(e,r){let o=Yn(r).map((i)=>i.name);return new t({code:"template_not_found",message:`No template called ${JSON.stringify(e)}.`,hint:o.length===0?`This server has no templates. An operator adds one as a directory under ${r}.`:`Templates here: ${o.join(", ")}. GET /v1/templates lists them with their variables.`,field:"template"})}function ga(){return Bt.shape.server.parse({})}async function br(e){let r=M(e.manifestPaths),o=e.store??G(),i=await cr(e.manifestPaths,r,o),s=i.filter((S)=>!S.enabled),a=i.filter((S)=>S.enabled),d=e.manifestPaths.length===0,l=[],m=[];for(let S of a)try{l.push({path:S.manifestPath,loaded:K(S.manifestPath,{env:r})})}catch(I){if(!d)throw I;m.push({path:S.manifestPath,detail:Ge(I)?I.message:String(I),...Ge(I)&&I.hint!==void 0?{hint:I.hint}:{}})}let g=l[0],u=g?.loaded,h=u?.manifest.server??ga();for(let S of l.slice(1)){let I=S.loaded.manifest.server;for(let[F,ye,Te,ue]of[["server.port",h.port,I.port,e.port!==void 0],["server.host",h.host,I.host,e.host!==void 0],["server.tokenEnv",h.tokenEnv,I.tokenEnv,!1]]){if(ue||ye===Te)continue;throw new t({code:"serve_bind_conflict",message:`${g?.path??"the first manifest"} sets ${F} to ${String(ye)} and ${S.path} sets it to ${String(Te)}.`,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:F})}}let y=e.port??h.port,b=e.port===void 0,R=e.host??h.host,w=u===void 0?r[h.tokenEnv]:u.env[h.tokenEnv],v=r[`${A.envPrefix}SERVICE`]!==void 0,U=new _A({runtimeId:`rt_${Date.now().toString(36)}`});if(e.json!==!0)U.on("agent.channel.status",(S)=>{let I=S.data,F=I.input===void 0?"":I.input.kind==="pairing_code"?`
259
+
260
+ ${I.input.payload}
261
+ ${I.input.expiresAt===void 0?"":`
262
+ expires ${I.input.expiresAt}`}`:` (${I.input.kind}${I.input.expiresAt===void 0?"":`, expires ${I.input.expiresAt}`} — GET /v1/agents/${S.agentId??""} carries it)`;process.stdout.write(` ${I.channelId}: ${I.status}${I.detail===void 0?"":` — ${I.detail}`}${F}
263
+ `)}),U.on("agent.channel.error",(S)=>{let I=S.data;process.stderr.write(` ${I.channelId}: ${I.message}
264
+ hint: ${I.hint}
265
+ `)}),U.on("error",(S)=>{let I=S.data,F=S.sessionKey===void 0?"":` [${S.sessionKey}]`;process.stderr.write(` turn failed${F}: ${I.code}: ${I.message}
266
+ hint: ${I.hint}
267
+ `)}),U.on("agent.channel.rejected",(S)=>{let I=S.data;process.stdout.write(` ${I.channelId}: ${I.reason} — ${I.detail}
268
+ `)});let k=Ai(),j=await ge.create({agents:l.map((S)=>S.path),approve:k.approver,env:r,bus:U,toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,startChannels:!0,startSchedules:!0,store:o,mode:v?"daemon":"terminal"});Br();let T=ya(),O=await j.store.operatorKeys.liveCount(),_=O===0||e.claim===!0?nr():void 0,C,B=[];try{C=await ba(y,b,(S)=>(B.push(S),rr({runtime:j,host:R,port:S,approvals:k,allowedOrigins:h.allowedOrigins,allowedHosts:h.allowedHosts,resolveAgent:(I)=>hn(I,r),provision:{steps:()=>wt({agentDirBase:le(r)}),create:(I)=>$t({answers:I,defaults:{agentDirBase:le(r)}}),templates:()=>Yn(ai(r)),createFromTemplate:(I)=>wr({...I,templatesDir:ai(r),agentDirBase:le(r)})},secrets:{status:Bn,write:Ys},channels:{setEnabled:Cn,setCredential:un,unpair:dn},..._===void 0?{}:{claim:_},...w===void 0||w===""?{}:{token:w}})))}catch(S){if(await j.stop("server failed to bind"),S instanceof t)throw S;let I=B.length>1?` — also tried ${B.slice(1).join(", ")}`:"";throw new t({code:"server_bind_failed",message:`Could not bind ${R}:${y}${I}: ${S instanceof Error?S.message:String(S)}`,hint:b?`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:S})}await j.publishAddress(C.url);let D=j.list(),te=D[0];if(te!==void 0)process.title=D.length===1?`${A.slug} ${te.id}`:`${A.slug} ${D.length} agents`;for(let S of D)S.reportRuntimeState({serverListening:!0});if(e.json===!0)process.stdout.write(`${JSON.stringify({url:C.url,websocket:C.websocket,authenticated:w!==void 0&&w!=="",keys:O,..._===void 0?{}:{claim:_.token},agents:D.map((S)=>({id:S.id,channels:j.channels.statusOf(S.id)})),declined:j.declined.map((S)=>({agentId:S.agentId,pid:S.pid,mode:S.mode,since:S.startedAt})),disabled:s.map((S)=>({agentId:S.agentId,...S.reason===void 0?{}:{reason:S.reason}})),broken:m.map((S)=>({path:S.path,detail:S.detail,...S.hint===void 0?{}:{hint:S.hint}}))})}
269
+ `);else{let S=`http://${Tt(R)}:${C.port}`,I=S===C.url?"":` (bound ${R} — every interface)`;if(process.stdout.write(`${A.name} serving on ${S}${I}
270
+ `),C.port!==y)process.stdout.write(` moved from ${y} — something else is on it. \`--port ${y}\` would refuse instead of moving.
271
+ `);process.stdout.write(` web UI ${S}/ · API reference ${S}/docs
272
+ `);for(let F of D){let ye=j.channels.statusOf(F.id),Te=ye.length===0?"no channels":ye.map((be)=>`${be.id} (${be.type}${be.status==="error"?", BROKEN":""})`).join(", "),ue=F.manifest.schedules.filter((be)=>be.enabled),Fr=F.manifest.schedules.length===0?"":`, ${ue.length} schedule${ue.length===1?"":"s"}${F.manifest.schedules.length>ue.length?` (+${F.manifest.schedules.length-ue.length} disabled)`:""}`;process.stdout.write(` ${F.id} — ${Te}${Fr}
273
+ `)}for(let F of s)process.stdout.write(` ${F.agentId} — stopped${F.reason===void 0?"":` (${F.reason})`}, \`${A.slug} start ${F.agentId}\`
274
+ `);for(let F of m)if(process.stdout.write(` ${F.path} — NOT served: ${F.detail}
275
+ `),F.hint!==void 0)process.stdout.write(` hint: ${F.hint}
276
+ `);for(let F of j.declined)process.stdout.write(` ${F.agentId} — NOT served here: pid ${F.pid} (${F.mode}) already has it
277
+ `);if(j.declined.length>0)process.stdout.write(` \`${A.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
278
+ `);if(_!==void 0){if(process.stdout.write(` open once to claim this server:
279
+ ${or(R,C.port,_.token)}
280
+ without a browser: ${ir(R,C.port,_.token)}
281
+ `),w===void 0||w==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
282
+ `)}if(w===void 0||w==="")process.stdout.write(` unauthenticated — loopback only. Set ${h.tokenEnv} to bind a public host.
283
+ `);if(v)process.stdout.write(` running as a background service · ${A.slug} daemon status ${D[0]?.id??""}
284
+ `);else if(Xo())process.stdout.write(` supervised by the container runtime — it stops with the container, and SIGTERM finishes the delivery in flight.
285
+ `);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${A.slug} daemon install${D[0]?.id===void 0?"":` ${D[0].id}`}\` keeps it running.
286
+ `)}let me=!1,he=async()=>{if(me)return;me=!0,await C.stop(),await j.stop("interrupted")};return P(he),await T,process.stdout.write(`stopping
287
+ `),await he(),n}function ya(){return new Promise((e)=>{let r=()=>{process.off("SIGINT",r),process.off("SIGTERM",r),e()};process.once("SIGINT",r),process.once("SIGTERM",r)})}var wa=16;async function ba(e,r,o){let i=r&&e!==0?e+wa:e;for(let s=e;;s+=1)try{return await o(s)}catch(a){if(s>=i||!$a(a))throw a}}function $a(e){if(typeof e==="object"&&e!==null&&"code"in e){if(e.code==="EADDRINUSE")return!0}let r=e instanceof Error?e.message:String(e);return r.includes("EADDRINUSE")||r.includes("in use")}function q(e,r){return e.length>=r?e:e+" ".repeat(r-e.length)}function va(e){let r=new Map,o=[];for(let i of e){let s=i.sessionKey.split(":"),a={sessionKey:i.sessionKey,phase:i.phase,messages:i.messages,turns:i.turns,lastActivityAt:i.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){o.push(a);continue}let d=`schedule:${s[1]}`,l=r.get(d);if(l===void 0){let m={...a,sessionKey:`${d}:*`,runs:1};r.set(d,m),o.push(m);continue}if(l.runs=(l.runs??1)+1,l.messages+=i.messages,l.turns+=i.turns,i.lastActivityAt>l.lastActivityAt)l.lastActivityAt=i.lastActivityAt}return o}function ka(e){if(e.length===0){process.stdout.write(`no sessions yet
288
+ `);return}let r=va(e),o=Math.max(7,...r.map((i)=>i.sessionKey.length));process.stdout.write(`${q("SESSION",o)} ${q("MSGS",5)} ${q("TURNS",5)} ${q("PHASE",8)} LAST
289
+ `);for(let i of r){let s=i.runs===void 0?"":` (${i.runs} run${i.runs===1?"":"s"})`;process.stdout.write(`${q(i.sessionKey,o)} ${q(String(i.messages),5)} ${q(String(i.turns),5)} ${q(i.phase??"-",8)} ${YA(i.lastActivityAt,Date.now())}${s}
290
+ `)}}async function Sa(e,r,o){let i=await e.store.messages.page(e.id,r,{limit:o});if(i.messages.length===0){process.stdout.write(`no messages in ${r}
291
+ `);return}for(let s of[...i.messages].reverse())process.stdout.write(`${s.role}: ${s.content}
292
+ `);if(i.nextBefore!==void 0)process.stdout.write(`
366
293
  … older messages exist; raise --limit
367
- `)}async function Ka(r,o,a){let u=await r.turns(o,a);if(u.length===0){process.stdout.write(`no turns in ${o}
368
- `);return}process.stdout.write(`${me("TURN",22)} ${me("STATUS",9)} ${me("STEPS",5)} ${me("TOKENS",13)} ${me("MS",6)} SOURCE
369
- `);for(let i of u)if(process.stdout.write(`${me(i.turnId,22)} ${me(i.status,9)} ${me(String(i.steps),5)} ${me(`${i.promptTokens}/${i.outputTokens}`,13)} ${me(String(i.durationMs??"-"),6)} ${i.source}
370
- `),i.errorCode!==void 0){if(process.stdout.write(` ${i.errorCode}: ${i.errorMessage}
371
- `),i.errorHint!==void 0)process.stdout.write(` hint: ${i.errorHint}
372
- `)}}async function uo(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});b(()=>o.stop("cli-exit"));let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=r.limit??Cn;if(r.clear===!0){if(r.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let f=await a.store.messages.count(a.id,r.sessionKey);return await a.clearSession(r.sessionKey),process.stdout.write(`cleared ${r.sessionKey}: ${f} message(s) removed, memory files untouched
373
- `),n}if(r.json===!0){let f=r.sessionKey===void 0?{store:o.store.location,sessions:await a.sessions()}:{store:o.store.location,session:await a.store.sessions.get(a.id,r.sessionKey),messages:(await a.store.messages.page(a.id,r.sessionKey,{limit:u})).messages,turns:await a.turns(r.sessionKey,u)};return process.stdout.write(`${JSON.stringify(f,null,2)}
374
- `),n}if(process.stdout.write(`store: ${o.store.location}
294
+ `)}async function Ea(e,r,o){let i=await e.turns(r,o);if(i.length===0){process.stdout.write(`no turns in ${r}
295
+ `);return}process.stdout.write(`${q("TURN",22)} ${q("STATUS",9)} ${q("STEPS",5)} ${q("TOKENS",13)} ${q("MS",6)} SOURCE
296
+ `);for(let s of i)if(process.stdout.write(`${q(s.turnId,22)} ${q(s.status,9)} ${q(String(s.steps),5)} ${q(`${s.promptTokens}/${s.outputTokens}`,13)} ${q(String(s.durationMs??"-"),6)} ${s.source}
297
+ `),s.errorCode!==void 0){if(process.stdout.write(` ${s.errorCode}: ${s.errorMessage}
298
+ `),s.errorHint!==void 0)process.stdout.write(` hint: ${s.errorHint}
299
+ `)}}async function $r(e){let r=await ge.create({agents:[e.manifestPath],store:e.store??G(),toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath])});P(()=>r.stop("cli-exit"));let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let i=e.limit??Ao;if(e.clear===!0){if(e.sessionKey===void 0)throw Error("--clear needs a session. hint: pass --session <key>; there is deliberately no way to clear every session at once.");let a=await o.store.messages.count(o.id,e.sessionKey);return await o.clearSession(e.sessionKey),process.stdout.write(`cleared ${e.sessionKey}: ${a} message(s) removed, memory files untouched
300
+ `),n}if(e.json===!0){let a=e.sessionKey===void 0?{store:r.store.location,sessions:await o.sessions()}:{store:r.store.location,session:await o.store.sessions.get(o.id,e.sessionKey),messages:(await o.store.messages.page(o.id,e.sessionKey,{limit:i})).messages,turns:await o.turns(e.sessionKey,i)};return process.stdout.write(`${JSON.stringify(a,null,2)}
301
+ `),n}if(process.stdout.write(`store: ${r.store.location}
375
302
 
376
- `),r.sessionKey===void 0)return ja(await a.sessions()),n;if(await a.store.sessions.get(a.id,r.sessionKey)===void 0)return process.stderr.write(`no session "${r.sessionKey}" for agent ${a.id}
377
- hint: run \`sessions ${r.manifestPath}\` to list the keys that exist
378
- `),s;if(r.turns===!0)await Ka(a,r.sessionKey,u);else await Ma(a,r.sessionKey,u);return n}import{existsSync as Ua,readFileSync as Da,writeFileSync as Ha}from"node:fs";import{basename as Ba,dirname as Wa,join as Ga}from"node:path";var qa=/^(#{1,6})\s+(.*)$/,Va=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Xa=/^[ \t]*<\/rules>[ \t]*$/,Ja=/^\s*(?:```|~~~)/;function fo(r){if(r.action!=="distill")throw new t({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${r.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let o;try{o=Da(r.file,"utf8")}catch{throw new t({code:"cli_soul_file_missing",message:`${r.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let a=Ba(r.file),u=r.out??Ga(Wa(r.file),`${a.replace(/\.md$/i,"")}.compact.md`);if(Ua(u))throw new t({code:"cli_soul_out_exists",message:`${u} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:i}=fn(a,o),f=za(a,i);return Ha(u,f,"utf8"),process.stdout.write(`wrote ${u}
303
+ `),e.sessionKey===void 0)return ka(await o.sessions()),n;if(await o.store.sessions.get(o.id,e.sessionKey)===void 0)return process.stderr.write(`no session "${e.sessionKey}" for agent ${o.id}
304
+ hint: run \`sessions ${e.manifestPath}\` to list the keys that exist
305
+ `),c;if(e.turns===!0)await Ea(o,e.sessionKey,i);else await Sa(o,e.sessionKey,i);return n}import{existsSync as xa,readFileSync as Pa,writeFileSync as Ra}from"node:fs";import{basename as Ia,dirname as Ta,join as Aa}from"node:path";var Oa=/^(#{1,6})\s+(.*)$/,_a=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Ca=/^[ \t]*<\/rules>[ \t]*$/,Na=/^\s*(?:```|~~~)/;function vr(e){if(e.action!=="distill")throw new t({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${e.action}".`,hint:"Usage: soul distill <file> [--out <path>]. It scaffolds a compact identity file from a long-form document; the scaffold is edited by hand and named in context.soul.distilled."});let r;try{r=Pa(e.file,"utf8")}catch{throw new t({code:"cli_soul_file_missing",message:`${e.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let o=Ia(e.file),i=e.out??Aa(Ta(e.file),`${o.replace(/\.md$/i,"")}.compact.md`);if(xa(i))throw new t({code:"cli_soul_out_exists",message:`${i} already exists, and a scaffold must not overwrite a file someone has edited.`,hint:"The compact file is the hand-edited artefact — regenerating it over someone's edits is exactly the loss automatic distillation would cause. Pass --out with a fresh path, or delete the file first if it really is disposable."});let{body:s}=Tn(o,r),a=ja(o,s);return Ra(i,a,"utf8"),process.stdout.write(`wrote ${i}
379
306
 
380
- The scaffold copies ${a}'s headings and its <rules> blocks verbatim, and leaves a
307
+ The scaffold copies ${o}'s headings and its <rules> blocks verbatim, and leaves a
381
308
  {{PLACEHOLDER}} under each heading. Now:
382
309
  `+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
383
310
  `+` document's own voice. The workspace command warns until none are left.
384
311
  2. Name the file in context.soul.distilled.
385
- `),n}function za(r,o){let a=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${r}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],u=!1,i=!1,f=0,h=!1;for(let g of o.split(`
386
- `)){if(Ja.test(g)){if(u=!u,i)a.push(g);continue}if(u){if(i)a.push(g);continue}if(Va.test(g)){i=!0,a.push(g);continue}if(i){if(a.push(g),Xa.test(g))i=!1,a.push("");continue}if(qa.exec(g)!==null)h=!0,f+=1,a.push(g),a.push(""),a.push(`{{SECTION_${f}}}`),a.push("")}if(!h)a.push("{{ESSENCE}}"),a.push("");return`${a.join(`
312
+ `),n}function ja(e,r){let o=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${e}. This file is the one small models actually`,"run on, so every sentence here is paid for on every turn — keep it to the few that","produce the voice. The long document stays the source of truth; edit it first, then","re-derive this by hand. These comments are stripped before injection and cost nothing.","-->",""],i=!1,s=!1,a=0,d=!1;for(let l of r.split(`
313
+ `)){if(Na.test(l)){if(i=!i,s)o.push(l);continue}if(i){if(s)o.push(l);continue}if(_a.test(l)){s=!0,o.push(l);continue}if(s){if(o.push(l),Ca.test(l))s=!1,o.push("");continue}if(Oa.exec(l)!==null)d=!0,a+=1,o.push(l),o.push(""),o.push(`{{SECTION_${a}}}`),o.push("")}if(!d)o.push("{{ESSENCE}}"),o.push("");return`${o.join(`
387
314
  `).replace(/\n{3,}/g,`
388
315
 
389
316
  `).trimEnd()}
390
- `}var Ya=["list","add","remove","update","search"],Qa=12;async function mo(r){try{switch(r.action){case"list":return Za(r);case"add":return ed(r);case"remove":return td(r);case"update":return await rd(r);case"search":return await sd(r);default:throw new t({code:"sources_action_unknown",message:`${r.action} is not a sources action`,hint:`One of: ${Ya.join(", ")}.`})}}catch(o){if(o instanceof t)return process.stdout.write(`${o.message}
317
+ `}var Fa=["list","add","remove","update","search"],Ka=12;async function kr(e){try{switch(e.action){case"list":return La(e);case"add":return Ua(e);case"remove":return Da(e);case"update":return await Ha(e);case"search":return await Wa(e);default:throw new t({code:"sources_action_unknown",message:`${e.action} is not a sources action`,hint:`One of: ${Fa.join(", ")}.`})}}catch(r){if(r instanceof t)return process.stdout.write(`${r.message}
391
318
 
392
- ${o.hint}
393
- `),s;throw o}}function Za(r){let a=G(r.env).map((u)=>{let i=Mn(u.name,r.env);return{...u,cached:ce(u.name,r.env),commit:i.commit,fetchedAt:i.fetchedAt,skills:i.skills}});if(r.json===!0)return process.stdout.write(`${JSON.stringify({registry:Ht(r.env),sources:a},null,2)}
394
- `),n;if(a.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
319
+ ${r.hint}
320
+ `),c;throw r}}function La(e){let o=we(e.env).map((i)=>{let s=ho(i.name,e.env);return{...i,cached:Ze(i.name,e.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(e.json===!0)return process.stdout.write(`${JSON.stringify({registry:Qn(e.env),sources:o},null,2)}
321
+ `),n;if(o.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
395
322
 
396
- \`sources add <name> <url>\` to add one, or \`sources add ${et[0]?.name??"anthropic"} ${et[0]?.url??""}\` to put a built-in back.
397
- `),n;process.stdout.write(p("sources",!0));for(let u of a)process.stdout.write(`
398
- ${d(`${u.name}${u.builtin===!0?" (built-in)":""}`)}
399
- `),process.stdout.write(c(l([{label:"url",value:u.url},...u.path===void 0?[]:[{label:"path",value:u.path}],...u.ref===void 0?[]:[{label:"branch",value:u.ref}],{label:"cached",value:u.cached?`${u.skills??"?"} skills at ${u.commit??"?"}, fetched ${u.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
400
- ${p("registry")}
401
- ${c(Ht(r.env))}
402
- `),n}function ed(r){let[o,a]=r.rest;if(o===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 u=a!==void 0,i=u?a:o,f=Wr(i),h=u?o:nd(f.url);if(!hr(h))throw new t({code:"sources_name_invalid",message:`${JSON.stringify(h)} 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 g=G(r.env).find((S)=>S.name===h);if(g!==void 0&&!u)throw new t({code:"sources_name_taken",message:`${h} is already a source, pointing at ${g.url}`,hint:`Give this one its own name: \`sources add <name> ${i}\`.`});let v=r.path??f.path,k=r.ref??f.ref,y={name:h,url:f.url,...v===void 0?{}:{path:v},...k===void 0?{}:{ref:k}};if(Kr(y,r.env),r.json===!0)return process.stdout.write(`${JSON.stringify({added:y},null,2)}
403
- `),n;return process.stdout.write(`${l([{label:g===void 0?"added":"replaced",value:h},{label:"url",value:y.url},...y.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:y.path}],...y.ref===void 0?[]:[{label:"branch",value:y.ref}]])}
404
- `),process.stdout.write(`${p("next")}
405
- ${d(`sources update ${h}`)}
406
- ${d("sources search <what you need>")}
407
- `),n}function nd(r){let o=r.replace(/\.git$/,"").split(/[:/]/).filter((u)=>u.length>0);return(o[o.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function td(r){let o=r.rest[0];if(o===void 0)throw new t({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let a=G(r.env).map((i)=>i.name);if(!Hr(o,r.env)){let i=E(o,a);throw new t({code:"sources_unknown",message:`no source called ${o}`,hint:i===void 0?`Configured: ${a.join(", ")||"none"}.`:`Did you mean ${i}?`})}let u=et.some((i)=>i.name===o);return process.stdout.write(`removed ${o}${u?" — a built-in, so it stays out until `sources add` puts it back":""}
323
+ \`sources add <name> <url>\` to add one, or \`sources add ${at[0]?.name??"anthropic"} ${at[0]?.url??""}\` to put a built-in back.
324
+ `),n;process.stdout.write(N("sources",!0));for(let i of o)process.stdout.write(`
325
+ ${f(`${i.name}${i.builtin===!0?" (built-in)":""}`)}
326
+ `),process.stdout.write(p(E([{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(`
327
+ ${N("registry")}
328
+ ${p(Qn(e.env))}
329
+ `),n}function Ua(e){let[r,o]=e.rest;if(r===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=o!==void 0,s=i?o:r,a=fo(s),d=i?r:Ma(a.url);if(!gt(d))throw new t({code:"sources_name_invalid",message:`${JSON.stringify(d)} is not usable as a source name`,hint:"Lowercase letters, digits and single hyphens — it becomes a directory in the cache and the prefix in `install <agent> <source>/<skill>`."});let l=we(e.env).find((h)=>h.name===d);if(l!==void 0&&!i)throw new t({code:"sources_name_taken",message:`${d} is already a source, pointing at ${l.url}`,hint:`Give this one its own name: \`sources add <name> ${s}\`.`});let m=e.path??a.path,g=e.ref??a.ref,u={name:d,url:a.url,...m===void 0?{}:{path:m},...g===void 0?{}:{ref:g}};if(Ir(u,e.env),e.json===!0)return process.stdout.write(`${JSON.stringify({added:u},null,2)}
330
+ `),n;return process.stdout.write(`${E([{label:l===void 0?"added":"replaced",value:d},{label:"url",value:u.url},...u.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:u.path}],...u.ref===void 0?[]:[{label:"branch",value:u.ref}]])}
331
+ `),process.stdout.write(`${N("next")}
332
+ ${f(`sources update ${d}`)}
333
+ ${f("sources search <what you need>")}
334
+ `),n}function Ma(e){let r=e.replace(/\.git$/,"").split(/[:/]/).filter((i)=>i.length>0);return(r[r.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function Da(e){let r=e.rest[0];if(r===void 0)throw new t({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let o=we(e.env).map((s)=>s.name);if(!lr(r,e.env)){let s=x(r,o);throw new t({code:"sources_unknown",message:`no source called ${r}`,hint:s===void 0?`Configured: ${o.join(", ")||"none"}.`:`Did you mean ${s}?`})}let i=at.some((s)=>s.name===r);return process.stdout.write(`removed ${r}${i?" — a built-in, so it stays out until `sources add` puts it back":""}
408
335
  `),process.stdout.write(`
409
336
  The cached copy is left on disk; nothing already installed into an agent is touched.
410
- `),n}async function rd(r){let o=G(r.env),a=r.rest.length===0?o:r.rest.map((f)=>{let h=o.find((g)=>g.name===f);if(h===void 0){let g=E(f,o.map((v)=>v.name));throw new t({code:"sources_unknown",message:`no source called ${f}`,hint:g===void 0?`Configured: ${o.map((v)=>v.name).join(", ")||"none"}.`:`Did you mean ${g}?`})}return h});if(a.length===0)return process.stdout.write(`no sources configured
337
+ `),n}async function Ha(e){let r=we(e.env),o=e.rest.length===0?r:e.rest.map((a)=>{let d=r.find((l)=>l.name===a);if(d===void 0){let l=x(a,r.map((m)=>m.name));throw new t({code:"sources_unknown",message:`no source called ${a}`,hint:l===void 0?`Configured: ${r.map((m)=>m.name).join(", ")||"none"}.`:`Did you mean ${l}?`})}return d});if(o.length===0)return process.stdout.write(`no sources configured
411
338
 
412
339
  \`sources add <url>\` to add one.
413
- `),n;let u=[],i=[];for(let f of a){if(r.json!==!0)process.stdout.write(`fetching ${f.name} … `);try{let h=await tt(f,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});if(u.push({name:f.name,commit:h.commit,skills:h.skills}),r.json!==!0)process.stdout.write(`${h.skills} skills at ${h.commit}${h.unfiltered&&f.path!==void 0?" (full clone — the server refused a partial one)":""}
414
- `)}catch(h){let g=h instanceof Error?h.message:String(h);if(i.push({name:f.name,reason:g}),r.json!==!0)process.stdout.write(`failed
415
- `);if(r.json!==!0&&h instanceof t)process.stdout.write(`${c(h.message)}
416
- ${c(h.hint,4)}
417
- `)}}if(r.json===!0)process.stdout.write(`${JSON.stringify({updated:u,failed:i},null,2)}
418
- `);return u.length===0?s:n}async function sd(r){let o=r.rest.join(" ").trim(),a=G(r.env);if(a.length===0)return process.stdout.write(`no sources configured
340
+ `),n;let i=[],s=[];for(let a of o){if(e.json!==!0)process.stdout.write(`fetching ${a.name} … `);try{let d=await ct(a,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(i.push({name:a.name,commit:d.commit,skills:d.skills}),e.json!==!0)process.stdout.write(`${d.skills} skills at ${d.commit}${d.unfiltered&&a.path!==void 0?" (full clone — the server refused a partial one)":""}
341
+ `)}catch(d){let l=d instanceof Error?d.message:String(d);if(s.push({name:a.name,reason:l}),e.json!==!0)process.stdout.write(`failed
342
+ `);if(e.json!==!0&&d instanceof t)process.stdout.write(`${p(d.message)}
343
+ ${p(d.hint,4)}
344
+ `)}}if(e.json===!0)process.stdout.write(`${JSON.stringify({updated:i,failed:s},null,2)}
345
+ `);return i.length===0?c:n}async function Wa(e){let r=e.rest.join(" ").trim(),o=we(e.env);if(o.length===0)return process.stdout.write(`no sources configured
419
346
 
420
347
  \`sources add <url>\` to add one.
421
- `),s;let u=a.filter((g)=>!ce(g.name,r.env));for(let g of u){if(r.json!==!0)process.stdout.write(`fetching ${g.name} for the first time … `);try{let v=await tt(g,{...r.env===void 0?{}:{env:r.env},...r.git===void 0?{}:{git:r.git}});if(r.json!==!0)process.stdout.write(`${v.skills} skills
422
- `)}catch(v){if(r.json!==!0){if(process.stdout.write(`failed
423
- `),v instanceof t)process.stdout.write(`${c(v.message)}
424
- `)}}}let i=a.flatMap((g)=>ke(g,r.env));if(i.length===0)return process.stdout.write(`
348
+ `),c;let i=o.filter((l)=>!Ze(l.name,e.env));for(let l of i){if(e.json!==!0)process.stdout.write(`fetching ${l.name} for the first time … `);try{let m=await ct(l,{...e.env===void 0?{}:{env:e.env},...e.git===void 0?{}:{git:e.git}});if(e.json!==!0)process.stdout.write(`${m.skills} skills
349
+ `)}catch(m){if(e.json!==!0){if(process.stdout.write(`failed
350
+ `),m instanceof t)process.stdout.write(`${p(m.message)}
351
+ `)}}}let s=o.flatMap((l)=>dA(l,e.env));if(s.length===0)return process.stdout.write(`
425
352
  nothing to search — no source has been fetched successfully
426
353
 
427
354
  \`sources update\` reports why.
428
- `),s;let f=o.length===0?i:od(o,i);if(f.length===0)return process.stdout.write(`
429
- nothing in ${i.length} skills across ${a.length} sources matches ${JSON.stringify(o)}
355
+ `),c;let a=r.length===0?s:Ga(r,s);if(a.length===0)return process.stdout.write(`
356
+ nothing in ${s.length} skills across ${o.length} sources matches ${JSON.stringify(r)}
430
357
 
431
358
  Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
432
- `),n;if(r.json===!0)return process.stdout.write(`${JSON.stringify({query:o,searched:i.length,results:f.map((g)=>({source:g.source,skill:g.skill,description:g.description,tokens:g.tokens,scripts:g.scripts.length,repoPath:g.repoPath,...g.problem===void 0?{}:{problem:g.problem}}))},null,2)}
433
- `),n;let h=f.slice(0,Qa);process.stdout.write(`
434
- ${p(o.length===0?`${i.length} skills`:`${f.length} of ${i.length} skills match ${JSON.stringify(o)}`,!0)}
435
- `);for(let g of h){process.stdout.write(`${d(`${g.source}/${g.skill}`)} ${g.tokens} tokens${g.scripts.length===0?"":`, ${g.scripts.length} runnable file${g.scripts.length===1?"":"s"}`}${g.problem===void 0?"":" — will not load"}
436
- `);let v=g.problem??g.description;process.stdout.write(`${c(v.length>160?`${v.slice(0,157)}…`:v,4)}
437
- `)}if(f.length>h.length)process.stdout.write(`
438
- ${c(`… and ${f.length-h.length} more; narrow the query or use --json`)}
359
+ `),n;if(e.json===!0)return process.stdout.write(`${JSON.stringify({query:r,searched:s.length,results:a.map((l)=>({source:l.source,skill:l.skill,description:l.description,tokens:l.tokens,scripts:l.scripts.length,repoPath:l.repoPath,...l.problem===void 0?{}:{problem:l.problem}}))},null,2)}
360
+ `),n;let d=a.slice(0,Ka);process.stdout.write(`
361
+ ${N(r.length===0?`${s.length} skills`:`${a.length} of ${s.length} skills match ${JSON.stringify(r)}`,!0)}
362
+ `);for(let l of d){process.stdout.write(`${f(`${l.source}/${l.skill}`)} ${l.tokens} tokens${l.scripts.length===0?"":`, ${l.scripts.length} runnable file${l.scripts.length===1?"":"s"}`}${l.problem===void 0?"":" — will not load"}
363
+ `);let m=l.problem??l.description;process.stdout.write(`${p(m.length>160?`${m.slice(0,157)}…`:m,4)}
364
+ `)}if(a.length>d.length)process.stdout.write(`
365
+ ${p(`… and ${a.length-d.length} more; narrow the query or use --json`)}
439
366
  `);return process.stdout.write(`
440
- ${p("install")}
441
- ${c(`skills install <agent> ${h[0]?.source}/${h[0]?.skill}`)}
442
- `),n}function od(r,o){let a=new Map,u=o.map((i)=>{let f=`${i.source}/${i.skill}`;return a.set(f,i),{name:f,dir:i.dir,tokens:i.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:f,description:i.description,metadata:{}}}});return wt(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}async function po(r){let o=id(r.manifestPath),a=await Br(o,r.store),u=[];if(a?.enabled===!0)u.push("was already switched on");await Pn(o,!0,void 0,r.store);let i=await Pe(r.store),f=!1;if(i===void 0)u.push("nothing is serving yet — it will be hosted at the next start");else if(i.baseUrl===void 0)u.push(`pid ${i.pid} is a ${i.mode} session, which serves no HTTP to adopt into`);else{let h=await Qe(i,`/v1/agents/${encodeURIComponent(o)}/start`,{},r.manifestPath);if(h.ok)f=!0,u.push(`adopted by pid ${i.pid}, live now`);else if(h.status===501)u.push(`pid ${i.pid} cannot look up manifests — restart it to pick this up`);else if(h.status===401)u.push(`pid ${i.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else u.push(`pid ${i.pid} could not adopt it${h.detail===void 0?"":`: ${h.detail}`}`)}if(r.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:o,enabled:!0,running:f,...i===void 0?{}:{pid:i.pid,mode:i.mode},note:u.join(" · ")}]},null,2)}
443
- `);else if(process.stdout.write(`${l([{label:o,value:f?"running":"switched on",note:u.join(" · ")}])}
444
- `),!f&&i!==void 0&&i.baseUrl!==void 0)process.stdout.write(`
445
- Switched on but not yet running. \`${e.slug} daemon restart\` picks it up.
446
- `);return i!==void 0&&i.baseUrl!==void 0&&!f?s:n}function id(r){let o=T(r);if(o.id===void 0||o.id==="")throw new t({code:"cli_start_agent_id_missing",message:`${r} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return o.id}import{copyFileSync as ad,existsSync as dd,mkdirSync as ld,readFileSync as cd,writeFileSync as ud}from"node:fs";import{dirname as fd,join as ho}from"node:path";async function go(r){let o=r.env??m([]),a=r.home??o.HOME??"",u=Rn(o),i=In(u);if(r.json===!0)return process.stdout.write(`${JSON.stringify({terminal:u,how:i?.how??"unknown",configPath:i?.configPath===void 0?void 0:ho(a,i.configPath),line:i?.line,steps:i?.steps},null,2)}
447
- `),i===void 0?s:n;if(process.stdout.write(`${p("shift+enter",!0)}
448
- ${c("⌥ 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.")}
449
- `),i===void 0)return process.stdout.write(`
450
- ${p("this terminal was not recognised")}
451
- ${c(`TERM_PROGRAM=${o.TERM_PROGRAM??"(unset)"} TERM=${o.TERM??"(unset)"}`)}
452
- ${c(`known: ${os().map((f)=>f.name).join(", ")}`)}
453
- ${d("⌥⏎ works here regardless — nothing needs configuring for it")}
454
- `),s;if(process.stdout.write(`
455
- ${p(i.name)}
456
- `),i.how!=="write"){process.stdout.write(`${c(i.how==="unverified"?`no verified recipe for this one — ${i.reason??"nobody has checked it"}`:`this one has to be done by hand — ${i.reason??"its settings are not a text file"}`)}
367
+ ${N("install")}
368
+ ${p(`skills install <agent> ${d[0]?.source}/${d[0]?.skill}`)}
369
+ `),n}function Ga(e,r){let o=new Map,i=r.map((s)=>{let a=`${s.source}/${s.skill}`;return o.set(a,s),{name:a,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:a,description:s.description,metadata:{}}}});return ft(e,i).filter((s)=>s.score>0).map((s)=>o.get(s.skill.name)).filter((s)=>s!==void 0)}async function Sr(e){let r=qa(e.manifestPath),o=await po(r,e.store),i=[];if(o?.enabled===!0)i.push("was already switched on");await Bo(r,!0,void 0,e.store);let s=await _e(e.store),a=!1;if(s===void 0)i.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)i.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let d=await ze(s,`/v1/agents/${encodeURIComponent(r)}/start`,{},e.manifestPath);if(d.ok)a=!0,i.push(`adopted by pid ${s.pid}, live now`);else if(d.status===501)i.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(d.status===401)i.push(`pid ${s.pid} refused the request — set ${A.envPrefix}API_TOKEN to the server's token`);else i.push(`pid ${s.pid} could not adopt it${d.detail===void 0?"":`: ${d.detail}`}`)}if(e.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:r,enabled:!0,running:a,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:i.join(" · ")}]},null,2)}
370
+ `);else if(process.stdout.write(`${E([{label:r,value:a?"running":"switched on",note:i.join(" · ")}])}
371
+ `),!a&&s!==void 0&&s.baseUrl!==void 0)process.stdout.write(`
372
+ Switched on but not yet running. \`${A.slug} daemon restart\` picks it up.
373
+ `);return s!==void 0&&s.baseUrl!==void 0&&!a?c:n}function qa(e){let r=L(e);if(r.id===void 0||r.id==="")throw new t({code:"cli_start_agent_id_missing",message:`${e} declares no id, so there is nothing to switch on.`,hint:"Add `id: <name>` to the manifest. The id is what the switch, the sessions and the API paths are all keyed by."});return r.id}async function xr(e){let r=await nn(e.store),o=new Map;for(let a of r){if(a.serving===void 0)continue;let d=await Nt(a.manifestPath,e.store);if(d!==void 0)o.set(a.ref,d)}if(e.json===!0)return process.stdout.write(`${JSON.stringify({agents:r.map((a)=>({...a,channels:[...o.get(a.ref)?.values()??[]]}))},null,2)}
374
+ `),n;let i=await CA({action:"status",...e.store===void 0?{}:{store:e.store}});process.stdout.write(`${E(tn(r))}
375
+ `);let s=[];for(let[a,d]of o)for(let l of d.values())s.push({label:`${a} / ${l.id}`,value:l.status,note:l.input!==void 0?`${l.detail??"enter this code"}: ${l.input.payload}`:l.detail??""});if(s.length>0)process.stdout.write(`
376
+ ${E(s)}
377
+ `);return i}import{copyFileSync as Ba,existsSync as Va,mkdirSync as Ja,readFileSync as Xa,writeFileSync as za}from"node:fs";import{dirname as Qa,join as Pr}from"node:path";async function Tr(e){let r=e.env??M([]),o=e.home??r.HOME??"",i=He(r),s=We(i);if(e.json===!0)return process.stdout.write(`${JSON.stringify({terminal:i,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:Pr(o,s.configPath),line:s?.line,steps:s?.steps},null,2)}
378
+ `),s===void 0?c:n;if(process.stdout.write(`${N("shift+enter",!0)}
379
+ ${p("⌥ 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.")}
380
+ `),s===void 0)return process.stdout.write(`
381
+ ${N("this terminal was not recognised")}
382
+ ${p(`TERM_PROGRAM=${r.TERM_PROGRAM??"(unset)"} TERM=${r.TERM??"(unset)"}`)}
383
+ ${p(`known: ${_t().map((a)=>a.name).join(", ")}`)}
384
+ ${f("⌥⏎ works here regardless — nothing needs configuring for it")}
385
+ `),c;if(process.stdout.write(`
386
+ ${N(s.name)}
387
+ `),s.how!=="write"){process.stdout.write(`${p(s.how==="unverified"?`no verified recipe for this one — ${s.reason??"nobody has checked it"}`:`this one has to be done by hand — ${s.reason??"its settings are not a text file"}`)}
457
388
 
458
- `);for(let[f,h]of(i.steps??[]).entries())process.stdout.write(`${c(`${f+1}. ${h}`)}
459
- `);return process.stdout.write(i.how==="unverified"?`
460
- ${d("⌥⏎ works here today — nothing has to be configured for it")}
389
+ `);for(let[a,d]of(s.steps??[]).entries())process.stdout.write(`${p(`${a+1}. ${d}`)}
390
+ `);return process.stdout.write(s.how==="unverified"?`
391
+ ${f("⌥⏎ works here today — nothing has to be configured for it")}
461
392
  `:`
462
- ${d("then restart the terminal and press shift+⏎ in a session to check it")}
463
- `),n}return await md(i,{...r,env:o,home:a})}async function md(r,o){let a=ho(o.home,r.configPath??""),u=dd(a)?cd(a,"utf8"):"";if(is(u,r))return process.stdout.write(`${c("already configured — a binding for shift+enter is present")}
464
- ${c(vt(a,o.home),4)}
465
- `),n;let i=as(u,r);if(i===void 0)return process.stdout.write(`${c("this file is not in a shape this command can edit safely:")}
466
- ${c(vt(a,o.home),4)}
467
- ${d("add the line below by hand:")}
468
- ${c(r.line??"",4)}
469
- `),s;if(process.stdout.write(`${l([{label:"file",value:vt(a,o.home)},{label:"exists",value:u===""?"no — it will be created":"yes"},{label:"add",value:r.line??""}])}
470
- `),o.dryRun===!0)return process.stdout.write(`
471
- ${d("--dry-run: nothing was written")}
472
- `),n;if(o.yes!==!0){if(!(o.confirm===void 0?!1:await o.confirm("write this change?")))return process.stdout.write(`
473
- ${d("nothing was written")}
474
- `),n}try{if(ld(fd(a),{recursive:!0}),u!=="")ad(a,`${a}.${e.slug}-backup`);ud(a,i,"utf8")}catch(f){return process.stderr.write(`could not write ${a}: ${f instanceof Error?f.message:String(f)}
475
- `),s}return process.stdout.write(`
476
- ${p("done")}
477
- ${u===""?"":`${c(`a copy of the old file is at ${vt(`${a}.${e.slug}-backup`,o.home)}`)}
478
- `}${d("restart the terminal, then press shift+⏎ in a session to check it")}
479
- `),n}async function yo(r){return r.warm===!0?await pd(r):await hd(r)}async function pd(r){let o=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),a=we(o.manifest.tools).selections,u=o.manifest.tools.pinned;if(a.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
480
- `),n;if(u.length===0)return process.stdout.write(`nothing to warm — ${a.map((g)=>g.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
481
- `),n;let i=[],f=new Set;for(let g of a){let v=A[g.id];if(v===void 0)return s;let k=v({dir:o.dir,env:o.env,config:g.config,agentId:o.manifest.id});if(k.refresh===void 0){for(let S of await k.resolve(u))f.add(S.spec.slug);if(r.json!==!0)process.stdout.write(`${g.id}: nothing to warm — it resolves without a cache.
482
- `);continue}let y=await k.refresh(u);for(let S of u)if(!y.missing.includes(S))f.add(S);i.push({provider:g.id,fetched:y.fetched,changed:[...y.changed],missing:[...y.missing],cachePath:"cachePath"in y&&typeof y.cachePath==="string"?y.cachePath:""})}if(r.json===!0)process.stdout.write(`${JSON.stringify(i,null,2)}
483
- `);else for(let g of i){if(process.stdout.write(`${g.fetched} of ${u.length} pinned tools fetched from ${g.provider}
484
- `),g.changed.length>0)process.stdout.write(` changed: ${g.changed.join(", ")}
485
- `);if(g.cachePath!=="")process.stdout.write(` cache: ${g.cachePath}
486
- `)}let h=u.filter((g)=>!f.has(g));for(let g of h)process.stdout.write(` missing: ${g} — no configured provider has a tool with that slug
487
- `);return h.length>0?s:n}async function hd(r){let o=await L.create({agents:[r.manifestPath],toolProviders:A,builtInPlugins:C,scriptRunner:O(),channels:N,env:m([r.manifestPath])});try{let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=Xn(a);return process.stdout.write(r.json===!0?`${JSON.stringify(u,null,2)}
488
- `:`${lt(u)}
489
- `),n}finally{await o.stop("cli-exit")}}import{dirname as wo,isAbsolute as gd,resolve as Bn}from"node:path";async function vo(r){try{let o=T(r.manifestPath),a=await yt({refs:o.plugins??[],agentId:o.id??r.manifestPath,paths:{workspace:wo(Bn(r.manifestPath)),state:wo(Bn(r.manifestPath)),manifest:Bn(r.manifestPath)},env:m([r.manifestPath]),bus:new _e({runtimeId:"validate"}),builtIn:C,base:{toolProviders:A,channels:N}}),u=x(r.manifestPath,{knownProviders:Object.keys(a.toolProviders),knownChannels:Object.keys(a.channels),env:m([r.manifestPath])}),{manifest:i}=u,f=H(i.model.main.id,i.model.main.capabilities),{workspace:h,warnings:g}=We(u,f.promptStyle);yn(u,{channels:a.channels});let v=Ie(h,i.context.rules);if(v!==void 0&&i.context.rules.onExceed==="fail")throw v;let k=[...g,...mn(i),...v===void 0?[]:[v.toDetail()]],y=i.knowledge===void 0?void 0:gn({dir:gd(i.knowledge.dir)?i.knowledge.dir:Bn(u.dir,i.knowledge.dir),maxActive:i.knowledge.maxActive,budget:i.knowledge.budget,style:f.promptStyle}),S=["static","volatile","reminder"].map((I)=>{let de=h.files.filter((oe)=>oe.tier===I).map((oe)=>oe.name);if(de.length===0)return;return`${I}=${de.join(",")} (${h.tokens[I]}/${i.context.budgets[I]})`}).filter((I)=>I!==void 0).join(" ");if(r.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:u.path,id:i.id,model:i.model.main.id,window:u.window,capabilities:f,workspace:{files:h.files.map((I)=>({name:I.name,tier:I.tier,editable:I.editable,tokens:I.tokens,budget:I.budget})),tokens:h.tokens},knowledge:y===void 0?[]:y.entries.map((I)=>({name:I.name,keywords:I.keywords,tokens:I.tokens})),warnings:k},null,2)}
490
- `),n;let P=ye(i),U=P.map((I)=>I.role===I.configuredAs?`${I.role}=${I.modelId}`:`${I.role}=→main`).join(" "),W=P.filter((I)=>I.role===I.configuredAs),F=$o({manifestPath:r.manifestPath,rawModelId:o.modelId,apiKeyEnv:i.model.main.apiKeyEnv}).flatMap((I)=>{let de=_o(I.origin);return de===void 0?[]:[` env ${I.variable} — ${de}
491
- `]}).join("");return process.stdout.write(`ok ${u.path}
492
- id ${i.id}${i.name===void 0?"":` (${i.name})`}
493
- models ${U}
494
- `+F+` window ${u.window} ${je(P[0]?.window)} (reserveOutput ${i.context.reserveOutput}, maxOutput ${f.maxOutput})
495
- `+(W.length<2?"":`${W.slice(1).map((I)=>` ${I.role.padEnd(12)} ${I.modelId} · window ${I.window.contextWindow} ${je(I.window)}
496
- `).join("")}`)+` capabilities thinking=${f.thinking} promptCache=${f.promptCache} nativeTools=${f.nativeTools} strictSchema=${f.strictSchema}
497
- `+yd(f.promptCache,i.model.main.id)+` dialect ${i.tools.dialect}
498
- workspace ${S===""?"(none)":S}
393
+ ${f("then restart the terminal and press shift+⏎ in a session to check it")}
394
+ `),n}return await Ya(s,{...e,env:r,home:o})}async function Ya(e,r){let o=Pr(r.home,e.configPath??""),i=Va(o)?Xa(o,"utf8"):"";if(jt(i,e))return process.stdout.write(`${p("already configured — a binding for shift+enter is present")}
395
+ ${p(xA(o,r.home),4)}
396
+ `),n;let s=Ft(i,e);if(s===void 0)return process.stdout.write(`${p("this file is not in a shape this command can edit safely:")}
397
+ ${p(xA(o,r.home),4)}
398
+ ${f("add the line below by hand:")}
399
+ ${p(e.line??"",4)}
400
+ `),c;if(process.stdout.write(`${E([{label:"file",value:xA(o,r.home)},{label:"exists",value:i===""?"no — it will be created":"yes"},{label:"add",value:e.line??""}])}
401
+ `),r.dryRun===!0)return process.stdout.write(`
402
+ ${f("--dry-run: nothing was written")}
403
+ `),n;if(r.yes!==!0){if(!(r.confirm===void 0?!1:await r.confirm("write this change?")))return process.stdout.write(`
404
+ ${f("nothing was written")}
405
+ `),n}try{if(Ja(Qa(o),{recursive:!0}),i!=="")Ba(o,`${o}.${A.slug}-backup`);za(o,s,"utf8")}catch(a){return process.stderr.write(`could not write ${o}: ${a instanceof Error?a.message:String(a)}
406
+ `),c}return process.stdout.write(`
407
+ ${N("done")}
408
+ ${i===""?"":`${p(`a copy of the old file is at ${xA(`${o}.${A.slug}-backup`,r.home)}`)}
409
+ `}${f("restart the terminal, then press shift+⏎ in a session to check it")}
410
+ `),n}async function Or(e){return e.warm===!0?await Za(e):await ed(e)}async function Za(e){let r=K(e.manifestPath,{env:M([e.manifestPath])}),o=iA(r.manifest.tools).selections,i=r.manifest.tools.pinned;if(o.length===0)return process.stdout.write(`nothing to warm — this manifest configures no tools.providers, so every tool it pins resolves locally.
411
+ `),n;if(i.length===0)return process.stdout.write(`nothing to warm — ${o.map((l)=>l.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
412
+ `),n;let s=[],a=new Set;for(let l of o){let m=oe[l.id];if(m===void 0)return c;let g=m({dir:r.dir,env:r.env,config:l.config,agentId:r.manifest.id});if(g.refresh===void 0){for(let h of await g.resolve(i))a.add(h.spec.slug);if(e.json!==!0)process.stdout.write(`${l.id}: nothing to warm — it resolves without a cache.
413
+ `);continue}let u=await g.refresh(i);for(let h of i)if(!u.missing.includes(h))a.add(h);s.push({provider:l.id,fetched:u.fetched,changed:[...u.changed],missing:[...u.missing],cachePath:"cachePath"in u&&typeof u.cachePath==="string"?u.cachePath:""})}if(e.json===!0)process.stdout.write(`${JSON.stringify(s,null,2)}
414
+ `);else for(let l of s){if(process.stdout.write(`${l.fetched} of ${i.length} pinned tools fetched from ${l.provider}
415
+ `),l.changed.length>0)process.stdout.write(` changed: ${l.changed.join(", ")}
416
+ `);if(l.cachePath!=="")process.stdout.write(` cache: ${l.cachePath}
417
+ `)}let d=i.filter((l)=>!a.has(l));for(let l of d)process.stdout.write(` missing: ${l} — no configured provider has a tool with that slug
418
+ `);return d.length>0?c:n}async function ed(e){let r=await ge.create({agents:[e.manifestPath],toolProviders:oe,builtInPlugins:ae,pluginRoot:V(),scriptRunner:Ae(),channels:Z,env:M([e.manifestPath])});try{let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let i=co(o);return process.stdout.write(e.json===!0?`${JSON.stringify(i,null,2)}
419
+ `:`${tt(i)}
420
+ `),n}finally{await r.stop("cli-exit")}}import{dirname as _r,isAbsolute as nd,resolve as en}from"node:path";async function Nr(e){try{let r=L(e.manifestPath),o=await Gn({refs:r.plugins??[],agentId:r.id??e.manifestPath,paths:{workspace:_r(en(e.manifestPath)),state:_r(en(e.manifestPath)),manifest:en(e.manifestPath)},env:M([e.manifestPath]),bus:new _A({runtimeId:"validate"}),builtIn:ae,pluginRoot:V(),base:{toolProviders:oe,channels:Z}}),i=K(e.manifestPath,{env:M([e.manifestPath])}),{manifest:s}=i,a=fe(s.model.main.id,s.model.main.capabilities),{workspace:d,warnings:l}=HA(i,a.promptStyle),m=Un(vn(i,{channels:o.channels})),g=await Fn(i,{toolProviders:o.toolProviders,channels:o.channels,scriptRunner:o.scriptRunner,middleware:o.middleware});for(let k of g.providers)await k.stop?.();let u=DA(d,s.context.rules);if(u!==void 0&&s.context.rules.onExceed==="fail")throw u;let h=[...l,...o.failed,...g.warnings,...g.registry.warnings,...m,...kn(s),...u===void 0?[]:[u.toDetail()]],y=s.knowledge===void 0?void 0:Pn({dir:nd(s.knowledge.dir)?s.knowledge.dir:en(i.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:a.promptStyle}),b=["static","volatile","reminder"].map((k)=>{let j=d.files.filter((T)=>T.tier===k).map((T)=>T.name);if(j.length===0)return;return`${k}=${j.join(",")} (${d.tokens[k]}/${s.context.budgets[k]})`}).filter((k)=>k!==void 0).join(" ");if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:i.path,id:s.id,model:s.model.main.id,window:i.window,capabilities:a,workspace:{files:d.files.map((k)=>({name:k.name,tier:k.tier,editable:k.editable,tokens:k.tokens,budget:k.budget})),tokens:d.tokens},knowledge:y===void 0?[]:y.entries.map((k)=>({name:k.name,keywords:k.keywords,tokens:k.tokens})),warnings:h},null,2)}
421
+ `),n;let R=oA(s),w=R.map((k)=>k.role===k.configuredAs?`${k.role}=${k.modelId}`:`${k.role}=→main`).join(" "),v=R.filter((k)=>k.role===k.configuredAs),U=er({manifestPath:e.manifestPath,rawModelId:r.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((k)=>{let j=$i(k.origin);return j===void 0?[]:[` env ${k.variable} — ${j}
422
+ `]}).join("");return process.stdout.write(`ok ${i.path}
423
+ id ${s.id}${s.name===void 0?"":` (${s.name})`}
424
+ models ${w}
425
+ `+U+` window ${i.window} ${GA(R[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${a.maxOutput})
426
+ `+(v.length<2?"":`${v.slice(1).map((k)=>` ${k.role.padEnd(12)} ${k.modelId} · window ${k.window.contextWindow} ${GA(k.window)}
427
+ `).join("")}`)+` capabilities thinking=${a.thinking} promptCache=${a.promptCache} nativeTools=${a.nativeTools} strictSchema=${a.strictSchema}
428
+ `+td(a.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
429
+ workspace ${b===""?"(none)":b}
499
430
  `+(y===void 0?"":` knowledge ${y.entries.length} entries, maxActive=${y.maxActive}, budget=${y.budget}
500
- `)+` memory ${i.memory===void 0?"none — nothing is retrieved across sessions":`${i.memory.retriever} at ${i.memory.dir}, maxActive=${i.memory.maxActive}, threshold=${i.memory.threshold}, budget=${i.memory.budget}, history=${i.memory.includeHistory}`}
501
- schedules ${i.schedules.length===0?"none":i.schedules.map((I)=>`${I.id} (${I.kind} ${I.expr}${I.timezone===void 0?"":` ${I.timezone}`}${I.role===void 0?"":` role=${I.role}`}${I.enabled?"":", disabled"})`).join(" ")}
502
- team ${i.team===void 0?"none — no delegation; `handoff` is not registered":`${i.team.members.map((I)=>`${I.id} (${I.manifest})`).join(" ")} — run one at a time`}
503
- limits maxSteps=${i.limits.maxSteps} turnTimeoutMs=${i.limits.turnTimeoutMs}
504
- `+k.map((I)=>` warning ${I.message}
505
- `).join("")),n}catch(o){if(r.json===!0&&o instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:o.toDetail(),details:o.details},null,2)}
506
- `),s;throw o}}function yd(r,o){if(r!=="none")return"";return/(^|\/)claude-/i.test(o)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
431
+ `)+` memory ${s.memory===void 0?"none — nothing is retrieved across sessions":`${s.memory.retriever} at ${s.memory.dir}, maxActive=${s.memory.maxActive}, threshold=${s.memory.threshold}, budget=${s.memory.budget}, history=${s.memory.includeHistory}`}
432
+ schedules ${s.schedules.length===0?"none":s.schedules.map((k)=>`${k.id} (${k.kind} ${k.expr}${k.timezone===void 0?"":` ${k.timezone}`}${k.role===void 0?"":` role=${k.role}`}${k.enabled?"":", disabled"})`).join(" ")}
433
+ team ${s.team===void 0?"none — no delegation; `handoff` is not registered":`${s.team.members.map((k)=>`${k.id} (${k.manifest})`).join(" ")} — run one at a time`}
434
+ limits maxSteps=${s.limits.maxSteps} turnTimeoutMs=${s.limits.turnTimeoutMs}
435
+ `+h.map((k)=>` warning ${k.message}
436
+ `).join("")),n}catch(r){if(e.json===!0&&r instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:r.toDetail(),details:r.details},null,2)}
437
+ `),c;throw r}}function td(e,r){if(e!=="none")return"";return/(^|\/)claude-/i.test(r)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
507
438
  `+` caching at all, so no request field reaches it. Caching lives on the native
508
439
  Messages API, which this runtime does not speak.
509
440
  `:` promptCache none — this runtime sends no cache directives. Many endpoints cache
510
- `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function xo(r){try{let o=x(r.manifestPath,{knownProviders:Y,knownChannels:X,env:m([r.manifestPath])}),{manifest:a}=o,u=H(a.model.main.id,a.model.main.capabilities),{workspace:i,warnings:f}=We(o,u.promptStyle),h=[...f,...Ir(i.files.map((k)=>({name:k.name,authored:k.authored,tier:k.tier,field:k.field})))],g=Ie(i,a.context.rules);if(g!==void 0)h.push(g.toDetail());if(r.json===!0)return process.stdout.write(`${JSON.stringify({ok:h.length===0,path:o.path,promptStyle:u.promptStyle,files:i.files.map((k)=>({name:k.name,tier:k.tier,editable:k.editable,tokens:k.tokens,budget:k.budget})),tokens:i.tokens,findings:h},null,2)}
511
- `),r.strict===!0&&h.length>0?s:n;let v=u.promptStyle;process.stdout.write(`${o.path}
512
- rendering delimiters=${v.delimiters} intensity=${v.intensity} examplesIn=${v.examplesIn}
513
- total ${i.tokens.total} tokens (static ${i.tokens.static}, volatile ${i.tokens.volatile}, reminder ${i.tokens.reminder})
514
- `);for(let k of i.files)process.stdout.write(` ${k.name.padEnd(14)} ${k.tier.padEnd(9)} ${String(k.tokens).padStart(5)}/${k.budget} tokens, editable=${k.editable}
515
- `);if(h.length===0)return process.stdout.write(`
441
+ `+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function jr(e){try{let r=K(e.manifestPath,{env:M([e.manifestPath])}),{manifest:o}=r,i=fe(o.model.main.id,o.model.main.capabilities),{workspace:s,warnings:a}=HA(r,i.promptStyle),d=[...a,...yi(s.files.map((g)=>({name:g.name,authored:g.authored,tier:g.tier,field:g.field})))],l=DA(s,o.context.rules);if(l!==void 0)d.push(l.toDetail());if(e.json===!0)return process.stdout.write(`${JSON.stringify({ok:d.length===0,path:r.path,promptStyle:i.promptStyle,files:s.files.map((g)=>({name:g.name,tier:g.tier,editable:g.editable,tokens:g.tokens,budget:g.budget})),tokens:s.tokens,findings:d},null,2)}
442
+ `),e.strict===!0&&d.length>0?c:n;let m=i.promptStyle;process.stdout.write(`${r.path}
443
+ rendering delimiters=${m.delimiters} intensity=${m.intensity} examplesIn=${m.examplesIn}
444
+ total ${s.tokens.total} tokens (static ${s.tokens.static}, volatile ${s.tokens.volatile}, reminder ${s.tokens.reminder})
445
+ `);for(let g of s.files)process.stdout.write(` ${g.name.padEnd(14)} ${g.tier.padEnd(9)} ${String(g.tokens).padStart(5)}/${g.budget} tokens, editable=${g.editable}
446
+ `);if(d.length===0)return process.stdout.write(`
516
447
  no findings
517
- `),n;for(let k of h)process.stdout.write(`
518
- ${k.code}: ${k.message}
519
- `),process.stdout.write(` hint: ${k.hint}
448
+ `),n;for(let g of d)process.stdout.write(`
449
+ ${g.code}: ${g.message}
450
+ `),process.stdout.write(` hint: ${g.hint}
520
451
  `);return process.stdout.write(`
521
- ${h.length} finding(s)
522
- `),r.strict===!0?s:n}catch(o){if(r.json===!0&&o instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:o.toDetail(),details:o.details},null,2)}
523
- `),s;throw o}}function wd(r){if(r instanceof t)process.stderr.write(`${r.format()}
524
- `);else if(r instanceof Error){if(process.stderr.write(`${r.message}
525
- `),Ee().debug&&r.stack!==void 0)process.stderr.write(`${r.stack}
526
- `)}else process.stderr.write(`${String(r)}
527
- `);return s}async function bd(){let r=process.stdout.write.bind(process.stdout);process.stdout.write=()=>!0;try{let o=await Ze({action:"install"});if(o!==n)return{kind:"failed",message:`daemon install exited ${o}`,hint:`Run \`${e.slug} daemon install\` to see what it said.`};return{kind:"started",label:`${e.slug}.server`}}finally{process.stdout.write=r}}async function vd(r){let o=jr(r);switch(o.kind){case"version":return process.stdout.write(`${R}
528
- `),n;case"help":return process.stdout.write(It(o.command)),n;case"usage":return process.stdout.write(It()),s;case"command":break}let{command:a,positionals:u,flags:i}=o.parsed,f=u[0],h=()=>te(f),g=a.flags.some((y)=>y.name==="store")?i.str("store"):void 0,v=await ls({needsServer:a.needsServer,disabled:i.bool("no-bootstrap"),install:()=>bd(),...g===void 0?{}:{store:g}}),k=cs(v);if(k!==void 0)process.stderr.write(k);switch(a.name){case"init":{let y=i.str("dir"),S=i.str("user"),P=i.str("name"),U=i.str("purpose"),W=i.str("preset"),F=i.str("model"),I=i.str("base-url"),de=i.str("api-key-env"),oe=i.str("system"),ge=i.str("web"),z=i.str("web-backend"),V=i.str("composio"),Q=i.str("telegram"),re=i.str("telegram-allow"),he=i.str("server"),fe=i.str("schedules"),Ae=i.str("skills"),D=i.str("daemon");return await ts({...y===void 0?{}:{dir:y},...S===void 0?{}:{user:S},...P===void 0?{}:{name:P},...U===void 0?{}:{purpose:U},...W===void 0?{}:{preset:W},...F===void 0?{}:{model:F},...I===void 0?{}:{baseUrl:I},...de===void 0?{}:{apiKeyEnv:de},...oe===void 0?{}:{system:oe},...ge===void 0?{}:{web:ge},...z===void 0?{}:{webBackend:z},...V===void 0?{}:{composio:V},...Q===void 0?{}:{telegram:Q},...fe===void 0?{}:{schedules:fe},...re===void 0?{}:{telegramAllow:re},...he===void 0?{}:{server:he},...Ae===void 0?{}:{skills:Ae},...D===void 0?{}:{daemon:D},yes:i.bool("yes"),plain:i.bool("plain")})}case"run":{let y=i.str("session"),S=i.str("input"),P=i.str("store");return await Ut({...u[0]===void 0?{}:{manifestPath:h()},...y===void 0?{}:{sessionKey:y},continueSession:i.bool("continue"),...S===void 0?{}:{once:S},...P===void 0?{}:{store:P},ephemeral:i.bool("ephemeral"),quiet:i.bool("quiet"),showReasoning:i.bool("show-reasoning"),noReasoning:i.bool("no-reasoning"),...i.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:i.bool("plain")})}case"schedules":{let y=i.str("store"),S=i.str("id"),P=i.str("enable"),U=i.str("disable");return await io({manifestPath:h(),...y===void 0?{}:{store:y},...S===void 0?{}:{id:S},...P===void 0?{}:{enable:P},...U===void 0?{}:{disable:U},recipients:i.bool("recipients"),json:i.bool("json")})}case"sessions":{let y=i.str("session"),S=i.str("store"),P=i.num("limit");return await uo({manifestPath:h(),...y===void 0?{}:{sessionKey:y},...S===void 0?{}:{store:S},...P===void 0?{}:{limit:P},json:i.bool("json"),clear:i.bool("clear"),turns:i.bool("turns")})}case"memory":{let y=i.num("limit"),S=i.str("store");return await ws({action:f,manifestPath:te(u[1]??""),...u[2]===void 0?{}:{query:u[2]},...y===void 0?{}:{limit:y},...S===void 0?{}:{store:S},all:i.bool("all"),json:i.bool("json")})}case"config":{let{configCommand:y,readAction:S}=await import("./config-g7za9x13.js"),P=S(f,u[1]);return await y({action:P.action,...P.ref===void 0?{}:{ref:P.ref},...u[2]===void 0?{}:{name:u[2]},...u[3]===void 0?{}:{value:u[3]},...i.str("channel")===void 0?{}:{channel:i.str("channel")},remove:i.bool("remove"),yes:i.bool("yes"),...i.str("store")===void 0?{}:{store:i.str("store")}})}case"validate":return await vo({manifestPath:h(),json:i.bool("json")});case"workspace":return xo({manifestPath:h(),json:i.bool("json"),strict:i.bool("strict")});case"soul":{let y=i.str("out");return fo({action:f,file:u[1],...y===void 0?{}:{out:y}})}case"skills":{if(u.length===0)return await Gr({plain:i.bool("plain"),json:i.bool("json")});let y=u[2];return Se({action:f,manifestPath:te(u[1]??""),...y===void 0?{}:{name:y},json:i.bool("json"),strict:i.bool("strict")})}case"sources":{let y=i.str("path"),S=i.str("ref");return await mo({action:f,rest:u.slice(1),...y===void 0?{}:{path:y},...S===void 0?{}:{ref:S},json:i.bool("json")})}case"plugins":return await _s({manifestPath:te(u[0]??""),json:i.bool("json")});case"agents":return await Gt({manifestPaths:u.map((y)=>te(y)),json:i.bool("json")});case"serve":{let y=i.num("port"),S=i.str("host"),P=i.str("store");return await co({manifestPaths:u.map((U)=>te(U)),...y===void 0?{}:{port:y},...S===void 0?{}:{host:S},...P===void 0?{}:{store:P},claim:i.bool("claim"),json:i.bool("json")})}case"keys":return await ds({noEnhancedKeys:i.bool("no-enhanced-keys")});case"terminal-setup":return await go({dryRun:i.bool("dry-run"),yes:i.bool("yes"),json:i.bool("json"),confirm:Ye});case"remove":return await Ds({...f===void 0?{}:{ref:f},dryRun:i.bool("dry-run"),filesOnly:i.bool("files-only"),prune:i.bool("prune"),all:i.bool("all"),yes:i.bool("yes"),json:i.bool("json"),...i.str("store")===void 0?{}:{store:i.str("store")},confirm:Pr});case"stop":{let y=i.str("reason");return await Nn({...f===void 0?{}:{manifestPath:h()},dryRun:i.bool("dry-run"),...y===void 0?{}:{reason:y},...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"start":return await po({manifestPath:h(),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")});case"web":{let{webCommand:y}=await import("./web-vkb16r62.js");return await y({action:f,...u[1]===void 0?{}:{manifestPath:te(u[1])},noOpen:i.bool("no-open"),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"credential":{let{credentialCommand:y}=await import("./credential-npr6z8c8.js");return await y({action:f??"",...u[1]===void 0?{}:{keyId:u[1]},...i.str("label")===void 0?{}:{label:i.str("label")},...i.str("agents")===void 0?{}:{agents:i.str("agents")},...i.str("sessions")===void 0?{}:{sessions:i.str("sessions")},...i.str("can")===void 0?{}:{can:i.str("can")},...i.str("expires")===void 0?{}:{expires:i.str("expires")},...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"daemon":{let y=i.num("lines");return await Ze({action:f,...u[1]===void 0?{}:{manifestPath:te(u[1])},...y===void 0?{}:{lines:y},follow:i.bool("follow"),truncate:i.bool("truncate"),dryRun:i.bool("dry-run"),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")})}case"model":{let y=i.num("price");return await Os({manifestPath:te(u[1]),window:i.bool("window"),...y===void 0?{}:{price:y},write:i.bool("write"),yes:i.bool("yes"),json:i.bool("json")})}case"tools":return await yo({manifestPath:h(),warm:i.bool("warm"),json:i.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${a.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}hs();Yr();await vd(process.argv.slice(2)).catch(wd).then((r)=>Dn(r));
452
+ ${d.length} finding(s)
453
+ `),e.strict===!0?c:n}catch(r){if(e.json===!0&&r instanceof t)return process.stdout.write(`${JSON.stringify({ok:!1,error:r.toDetail(),details:r.details},null,2)}
454
+ `),c;throw r}}function sd(e){if(e instanceof t)process.stderr.write(`${e.format()}
455
+ `);else if(e instanceof Error){if(process.stderr.write(`${e.message}
456
+ `),QA().debug&&e.stack!==void 0)process.stderr.write(`${e.stack}
457
+ `)}else process.stderr.write(`${String(e)}
458
+ `);return c}async function rd(e){let r=sr(e);switch(r.kind){case"version":return process.stdout.write(`${H}
459
+ `),n;case"help":return process.stdout.write(xn(r.command)),n;case"usage":return process.stdout.write(xn()),c;case"command":break}let{command:o,positionals:i,flags:s}=r.parsed,a=i[0],d=()=>Me(a),l=o.flags.some((u)=>u.name==="store")?s.str("store"):void 0,m=await Eo({needsServer:o.needsServer,disabled:s.bool("no-bootstrap"),install:()=>Co(),...l===void 0?{}:{store:l}}),g=nt(m);if(g!==void 0)process.stderr.write(g);switch(o.name){case"init":{let u=s.str("dir"),h=s.str("user"),y=s.str("name"),b=s.str("purpose"),R=s.str("preset"),w=s.str("model"),v=s.str("base-url"),U=s.str("api-key-env"),k=s.str("system"),j=s.str("web"),T=s.str("web-backend"),O=s.str("composio"),_=s.str("telegram"),C=s.str("telegram-allow"),B=s.str("whatsapp"),D=s.str("whatsapp-number"),te=s.str("server"),me=s.str("schedules"),he=s.str("skills"),S=s.str("daemon");return await vt({...u===void 0?{}:{dir:u},...h===void 0?{}:{user:h},...y===void 0?{}:{name:y},...b===void 0?{}:{purpose:b},...R===void 0?{}:{preset:R},...w===void 0?{}:{model:w},...v===void 0?{}:{baseUrl:v},...U===void 0?{}:{apiKeyEnv:U},...k===void 0?{}:{system:k},...j===void 0?{}:{web:j},...T===void 0?{}:{webBackend:T},...O===void 0?{}:{composio:O},..._===void 0?{}:{telegram:_},...me===void 0?{}:{schedules:me},...C===void 0?{}:{telegramAllow:C},...B===void 0?{}:{whatsapp:B},...D===void 0?{}:{whatsappNumber:D},...te===void 0?{}:{server:te},...he===void 0?{}:{skills:he},...S===void 0?{}:{daemon:S},yes:s.bool("yes"),plain:s.bool("plain"),installServer:Co})}case"run":{let u=s.str("session"),h=s.str("input"),y=s.str("store");return await Wn({...i[0]===void 0?{}:{manifestPath:d()},...u===void 0?{}:{sessionKey:u},continueSession:s.bool("continue"),...h===void 0?{}:{once:h},...y===void 0?{}:{store:y},ephemeral:s.bool("ephemeral"),quiet:s.bool("quiet"),showReasoning:s.bool("show-reasoning"),noReasoning:s.bool("no-reasoning"),...s.bool("no-enhanced-keys")?{noEnhancedKeys:!0}:{},plain:s.bool("plain")})}case"schedules":{let u=s.str("store"),h=s.str("id"),y=s.str("enable"),b=s.str("disable");return await Qs({manifestPath:d(),...u===void 0?{}:{store:u},...h===void 0?{}:{id:h},...y===void 0?{}:{enable:y},...b===void 0?{}:{disable:b},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let u=s.str("session"),h=s.str("store"),y=s.num("limit");return await $r({manifestPath:d(),...u===void 0?{}:{sessionKey:u},...h===void 0?{}:{store:h},...y===void 0?{}:{limit:y},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"memory":{let u=s.num("limit"),h=s.str("store");return await zt({action:a,manifestPath:Me(i[1]??""),...i[2]===void 0?{}:{query:i[2]},...u===void 0?{}:{limit:u},...h===void 0?{}:{store:h},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:u,readAction:h}=await import("./config-wvjeejgd.js"),y=h(a,i[1]);return await u({action:y.action,...y.ref===void 0?{}:{ref:y.ref},...i[2]===void 0?{}:{name:i[2]},...i[3]===void 0?{}:{value:i[3]},...s.str("channel")===void 0?{}:{channel:s.str("channel")},remove:s.bool("remove"),yes:s.bool("yes"),...s.str("store")===void 0?{}:{store:s.str("store")}})}case"validate":return await Nr({manifestPath:d(),json:s.bool("json")});case"workspace":return jr({manifestPath:d(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let u=s.str("out");return vr({action:a,file:i[1],...u===void 0?{}:{out:u}})}case"skills":{if(i.length===0)return await Cr({plain:s.bool("plain"),json:s.bool("json")});let u=i[2];return BA({action:a,manifestPath:Me(i[1]??""),...u===void 0?{}:{name:u},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let u=s.str("path"),h=s.str("ref");return await kr({action:a,rest:i.slice(1),...u===void 0?{}:{path:u},...h===void 0?{}:{ref:h},json:s.bool("json")})}case"channels":{let u=gr("channels",a),h=u.ref??i[1]??"",{channelsCommand:y}=await import("./channels-gx951qdp.js");return await y({...u.action===void 0?{}:{action:u.action},manifestPath:Me(h),...i[2]===void 0?{}:{channelId:i[2]},json:s.bool("json"),installServer:Co})}case"plugins":{let u=s.str("ref"),h=s.str("name");return await $s({action:a,manifestPath:Me(i[1]??""),rest:i.slice(2),...u===void 0?{}:{ref:u},...h===void 0?{}:{name:h},json:s.bool("json")})}case"agents":{let u=s.str("store");return await Zn({manifestPaths:i.map((h)=>Me(h)),...u===void 0?{}:{store:u},json:s.bool("json")})}case"restart":{let u=s.str("store");return await js({...a===void 0?{}:{manifestPath:d()},...u===void 0?{}:{store:u},json:s.bool("json")})}case"status":{let u=s.str("store");return await xr({...u===void 0?{}:{store:u},json:s.bool("json")})}case"logs":{let u=s.num("lines"),h=s.str("store");return await CA({action:"logs",...a===void 0?{}:{manifestPath:d()},...u===void 0?{}:{lines:u},follow:s.bool("follow"),truncate:s.bool("truncate"),...h===void 0?{}:{store:h},json:s.bool("json")})}case"serve":{let u=s.num("port"),h=s.str("host"),y=s.str("store");return await br({manifestPaths:i.map((b)=>Me(b)),...u===void 0?{}:{port:u},...h===void 0?{}:{host:h},...y===void 0?{}:{store:y},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await Ut({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await Tr({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:it});case"remove":return await As({...a===void 0?{}:{ref:a},dryRun:s.bool("dry-run"),filesOnly:s.bool("files-only"),prune:s.bool("prune"),all:s.bool("all"),yes:s.bool("yes"),json:s.bool("json"),...s.str("store")===void 0?{}:{store:s.str("store")},confirm:tr});case"stop":{let u=s.str("reason");return await Ve({...a===void 0?{}:{manifestPath:d()},dryRun:s.bool("dry-run"),...u===void 0?{}:{reason:u},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await Sr({manifestPath:d(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:u}=await import("./web-61cjhpv2.js");return await u({action:a,...i[1]===void 0?{}:{manifestPath:Me(i[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:u}=await import("./credential-10dn3fxj.js");return await u({action:a??"",...i[1]===void 0?{}:{keyId:i[1]},...s.str("label")===void 0?{}:{label:s.str("label")},...s.str("agents")===void 0?{}:{agents:s.str("agents")},...s.str("sessions")===void 0?{}:{sessions:s.str("sessions")},...s.str("can")===void 0?{}:{can:s.str("can")},...s.str("expires")===void 0?{}:{expires:s.str("expires")},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"daemon":{let u=s.num("lines");return await CA({action:a,...i[1]===void 0?{}:{manifestPath:Me(i[1])},...u===void 0?{}:{lines:u},follow:s.bool("follow"),truncate:s.bool("truncate"),dryRun:s.bool("dry-run"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"model":{let u=s.num("price");return await cs({manifestPath:Me(i[1]),window:s.bool("window"),...u===void 0?{}:{price:u},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await Or({manifestPath:d(),warm:s.bool("warm"),json:s.bool("json")});default:throw new t({code:"cli_command_unwired",message:`Command "${o.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}Vt();pr();await rd(process.argv.slice(2)).catch(sd).then((e)=>mo(e));
529
460
 
530
- //# debugId=92EA07B9DCA0055664756E2164756E21
461
+ //# debugId=91371D7403BDA82864756E2164756E21
531
462
  //# sourceMappingURL=index.js.map