dispach 0.1.2 → 0.1.3

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 (195) hide show
  1. package/README.md +134 -85
  2. package/dist/App-qfqvx9c7.js +11 -0
  3. package/dist/{App-b1yrwrcq.js.map → App-qfqvx9c7.js.map} +6 -7
  4. package/dist/ConfigEditor-apcnj4nj.js +6 -0
  5. package/dist/{ConfigEditor-n8hdw6r7.js.map → ConfigEditor-apcnj4nj.js.map} +2 -2
  6. package/dist/KeyProbe-ya5t3v3v.js +5 -0
  7. package/dist/{KeyProbe-9jjeze5r.js.map → KeyProbe-ya5t3v3v.js.map} +2 -2
  8. package/dist/Picker-b7mn0mjg.js +5 -0
  9. package/dist/{Picker-hfeh1g6m.js.map → Picker-b7mn0mjg.js.map} +1 -1
  10. package/dist/SessionPicker-vacfwczg.js +5 -0
  11. package/dist/{SessionPicker-zyqkg4dn.js.map → SessionPicker-vacfwczg.js.map} +2 -2
  12. package/dist/SkillBrowser-66ntwaa9.js +5 -0
  13. package/dist/{SkillBrowser-3qdp8080.js.map → SkillBrowser-66ntwaa9.js.map} +1 -1
  14. package/dist/WizardApp-123998yh.js +5 -0
  15. package/dist/{WizardApp-vzpbydy3.js.map → WizardApp-123998yh.js.map} +3 -3
  16. package/dist/agents.d.ts +19 -3
  17. package/dist/agents.d.ts.map +1 -1
  18. package/dist/channels-q4fwqq87.js +31 -0
  19. package/dist/channels-q4fwqq87.js.map +10 -0
  20. package/dist/channels.d.ts +26 -0
  21. package/dist/channels.d.ts.map +1 -0
  22. package/dist/client.js +10 -10
  23. package/dist/client.js.map +3 -3
  24. package/dist/config-64q4mgxc.js +24 -0
  25. package/dist/{config-g7za9x13.js.map → config-64q4mgxc.js.map} +2 -2
  26. package/dist/{credential-npr6z8c8.js → credential-2sj7vsmw.js} +5 -5
  27. package/dist/{credential-npr6z8c8.js.map → credential-2sj7vsmw.js.map} +1 -1
  28. package/dist/daemon.d.ts.map +1 -1
  29. package/dist/index-0k3w2mxf.js +6 -0
  30. package/dist/{index-hwpvhaza.js.map → index-0k3w2mxf.js.map} +1 -1
  31. package/dist/index-1s81qstp.js +6 -0
  32. package/dist/{index-v8e92nfw.js.map → index-1s81qstp.js.map} +1 -1
  33. package/dist/index-2rycma8x.js +12 -0
  34. package/dist/{index-258d8bzg.js.map → index-2rycma8x.js.map} +4 -3
  35. package/dist/index-2zye08c4.js +6 -0
  36. package/dist/{index-vgc3y3rm.js.map → index-2zye08c4.js.map} +2 -2
  37. package/dist/{index-gme2egyq.js → index-3km1jwh7.js} +4 -4
  38. package/dist/{index-gme2egyq.js.map → index-3km1jwh7.js.map} +1 -1
  39. package/dist/index-3mtgcvkq.js +429 -0
  40. package/dist/index-3mtgcvkq.js.map +11 -0
  41. package/dist/index-4knb5vjm.js +90 -0
  42. package/dist/index-4knb5vjm.js.map +13 -0
  43. package/dist/{index-3g3ny01d.js → index-5nwwekk0.js} +4 -4
  44. package/dist/{index-3g3ny01d.js.map → index-5nwwekk0.js.map} +1 -1
  45. package/dist/index-5rm7dwq4.js +6 -0
  46. package/dist/index-5rm7dwq4.js.map +11 -0
  47. package/dist/index-79epttpm.js +6 -0
  48. package/dist/index-79epttpm.js.map +10 -0
  49. package/dist/{index-4cf6v9nb.js → index-7yk1zvds.js} +4 -4
  50. package/dist/{index-4cf6v9nb.js.map → index-7yk1zvds.js.map} +1 -1
  51. package/dist/index-81gb4ey4.js +6 -0
  52. package/dist/{index-4z7axw4r.js.map → index-81gb4ey4.js.map} +1 -1
  53. package/dist/index-8a5d8sfe.js +6 -0
  54. package/dist/{index-0d93hyfc.js.map → index-8a5d8sfe.js.map} +1 -1
  55. package/dist/index-a21zyy54.js +6 -0
  56. package/dist/index-a21zyy54.js.map +9 -0
  57. package/dist/index-b6da6c16.js +92 -0
  58. package/dist/index-b6da6c16.js.map +15 -0
  59. package/dist/index-byxrc961.js +903 -0
  60. package/dist/{index-tv4yv7d2.js.map → index-byxrc961.js.map} +16 -15
  61. package/dist/{index-ammv5st7.js → index-cgfg6t5a.js} +6 -6
  62. package/dist/{index-ammv5st7.js.map → index-cgfg6t5a.js.map} +1 -1
  63. package/dist/{index-s9mbq7h6.js → index-ehzwdnc3.js} +4 -4
  64. package/dist/{index-s9mbq7h6.js.map → index-ehzwdnc3.js.map} +1 -1
  65. package/dist/index-fzmmhmk2.js +7 -0
  66. package/dist/index-fzmmhmk2.js.map +11 -0
  67. package/dist/index-g3pk0kc0.js +6 -0
  68. package/dist/{index-9r0wyj6w.js.map → index-g3pk0kc0.js.map} +2 -2
  69. package/dist/index-h828nk24.js +153 -0
  70. package/dist/index-h828nk24.js.map +20 -0
  71. package/dist/{index-02dn6m2j.js → index-jq999vcw.js} +5 -5
  72. package/dist/{index-02dn6m2j.js.map → index-jq999vcw.js.map} +2 -2
  73. package/dist/index-k2aq5bg0.js +9 -0
  74. package/dist/{index-6p999cx4.js.map → index-k2aq5bg0.js.map} +4 -6
  75. package/dist/{index-cqqb6gaq.js → index-k3y8y3wj.js} +5 -5
  76. package/dist/{index-cqqb6gaq.js.map → index-k3y8y3wj.js.map} +1 -1
  77. package/dist/index-k59wwdgz.js +9 -0
  78. package/dist/{index-ff514z3y.js.map → index-k59wwdgz.js.map} +3 -5
  79. package/dist/index-nmnnwa02.js +6 -0
  80. package/dist/{index-6q4wf8e3.js.map → index-nmnnwa02.js.map} +1 -1
  81. package/dist/index-nn3tk25c.js +6 -0
  82. package/dist/{index-d4x6yvqh.js.map → index-nn3tk25c.js.map} +3 -4
  83. package/dist/index-q0hxh57v.js +126 -0
  84. package/dist/index-q0hxh57v.js.map +14 -0
  85. package/dist/index-srmhk9g5.js +11 -0
  86. package/dist/index-srmhk9g5.js.map +11 -0
  87. package/dist/index-swtyfhha.js +6 -0
  88. package/dist/{index-fex44816.js.map → index-swtyfhha.js.map} +2 -2
  89. package/dist/index-whq42sat.js +6 -0
  90. package/dist/{index-h9mw7b9d.js.map → index-whq42sat.js.map} +1 -1
  91. package/dist/{index-j7gyr5nx.js → index-wzsmh5j0.js} +7 -7
  92. package/dist/{index-j7gyr5nx.js.map → index-wzsmh5j0.js.map} +1 -1
  93. package/dist/{index-j55s3ehk.js → index-x7v1zq89.js} +7 -7
  94. package/dist/{index-j55s3ehk.js.map → index-x7v1zq89.js.map} +2 -2
  95. package/dist/index-xhzmv4dh.js +66 -0
  96. package/dist/index-xhzmv4dh.js.map +12 -0
  97. package/dist/index-xmv47vs0.js +6 -0
  98. package/dist/{index-gz9x25tz.js.map → index-xmv47vs0.js.map} +2 -2
  99. package/dist/index-y4c32wn7.js +6 -0
  100. package/dist/{index-qdbq8crg.js.map → index-y4c32wn7.js.map} +2 -2
  101. package/dist/index-yjcdp72k.js +6 -0
  102. package/dist/{index-tf71ap9v.js.map → index-yjcdp72k.js.map} +1 -1
  103. package/dist/index-zn24991r.js +6 -0
  104. package/dist/index-zn24991r.js.map +10 -0
  105. package/dist/index.js +374 -443
  106. package/dist/index.js.map +23 -27
  107. package/dist/init.d.ts.map +1 -1
  108. package/dist/lib/channel-actions.d.ts +103 -0
  109. package/dist/lib/channel-actions.d.ts.map +1 -0
  110. package/dist/lib/chat-frame.d.ts +12 -1
  111. package/dist/lib/chat-frame.d.ts.map +1 -1
  112. package/dist/lib/commands.d.ts +13 -0
  113. package/dist/lib/commands.d.ts.map +1 -1
  114. package/dist/lib/const.d.ts +1 -1
  115. package/dist/lib/host-actions.d.ts +121 -0
  116. package/dist/lib/host-actions.d.ts.map +1 -0
  117. package/dist/lib/init-flow.d.ts +32 -0
  118. package/dist/lib/init-flow.d.ts.map +1 -1
  119. package/dist/lib/init-whatsapp.d.ts +52 -0
  120. package/dist/lib/init-whatsapp.d.ts.map +1 -0
  121. package/dist/lib/plugin-install.d.ts +120 -0
  122. package/dist/lib/plugin-install.d.ts.map +1 -0
  123. package/dist/lib/providers.d.ts.map +1 -1
  124. package/dist/lib/provision.d.ts.map +1 -1
  125. package/dist/lib/readme-table.d.ts +15 -0
  126. package/dist/lib/readme-table.d.ts.map +1 -0
  127. package/dist/lib/sandbox.d.ts +15 -0
  128. package/dist/lib/sandbox.d.ts.map +1 -1
  129. package/dist/lib/schema.d.ts +34 -1
  130. package/dist/lib/schema.d.ts.map +1 -1
  131. package/dist/lib/subcommand.d.ts.map +1 -1
  132. package/dist/lib/web-url.d.ts +15 -0
  133. package/dist/lib/web-url.d.ts.map +1 -0
  134. package/dist/lib/wizard.d.ts.map +1 -1
  135. package/dist/memory.d.ts.map +1 -1
  136. package/dist/model.d.ts.map +1 -1
  137. package/dist/plugins.d.ts +27 -8
  138. package/dist/plugins.d.ts.map +1 -1
  139. package/dist/restart.d.ts +21 -0
  140. package/dist/restart.d.ts.map +1 -0
  141. package/dist/run.d.ts.map +1 -1
  142. package/dist/schedules.d.ts.map +1 -1
  143. package/dist/serve.d.ts.map +1 -1
  144. package/dist/sessions.d.ts.map +1 -1
  145. package/dist/skills.d.ts.map +1 -1
  146. package/dist/status.d.ts +16 -0
  147. package/dist/status.d.ts.map +1 -0
  148. package/dist/tools.d.ts.map +1 -1
  149. package/dist/validate.d.ts.map +1 -1
  150. package/dist/web-923c7f5e.js +14 -0
  151. package/dist/{web-vkb16r62.js.map → web-923c7f5e.js.map} +3 -3
  152. package/dist/web.d.ts +2 -13
  153. package/dist/web.d.ts.map +1 -1
  154. package/dist/workspace.d.ts.map +1 -1
  155. package/dist/wrapper-0w9b3my0.js +11 -0
  156. package/dist/wrapper-0w9b3my0.js.map +23 -0
  157. package/package.json +6 -3
  158. package/dist/App-b1yrwrcq.js +0 -11
  159. package/dist/ConfigEditor-n8hdw6r7.js +0 -6
  160. package/dist/KeyProbe-9jjeze5r.js +0 -5
  161. package/dist/Picker-hfeh1g6m.js +0 -5
  162. package/dist/SessionPicker-zyqkg4dn.js +0 -5
  163. package/dist/SkillBrowser-3qdp8080.js +0 -5
  164. package/dist/WizardApp-vzpbydy3.js +0 -5
  165. package/dist/config-g7za9x13.js +0 -24
  166. package/dist/index-0d93hyfc.js +0 -6
  167. package/dist/index-1c5113t4.js +0 -66
  168. package/dist/index-1c5113t4.js.map +0 -12
  169. package/dist/index-258d8bzg.js +0 -12
  170. package/dist/index-4z7axw4r.js +0 -6
  171. package/dist/index-6p999cx4.js +0 -9
  172. package/dist/index-6q4wf8e3.js +0 -6
  173. package/dist/index-9r0wyj6w.js +0 -6
  174. package/dist/index-d4x6yvqh.js +0 -6
  175. package/dist/index-fecm8xe7.js +0 -77
  176. package/dist/index-fecm8xe7.js.map +0 -12
  177. package/dist/index-fex44816.js +0 -6
  178. package/dist/index-ff514z3y.js +0 -14
  179. package/dist/index-gz9x25tz.js +0 -6
  180. package/dist/index-h9mw7b9d.js +0 -6
  181. package/dist/index-hwpvhaza.js +0 -6
  182. package/dist/index-mtn0g9vc.js +0 -7
  183. package/dist/index-mtn0g9vc.js.map +0 -11
  184. package/dist/index-qdbq8crg.js +0 -6
  185. package/dist/index-tf71ap9v.js +0 -6
  186. package/dist/index-ttwyrdjs.js +0 -427
  187. package/dist/index-ttwyrdjs.js.map +0 -11
  188. package/dist/index-tv4yv7d2.js +0 -903
  189. package/dist/index-ty24n0jh.js +0 -167
  190. package/dist/index-ty24n0jh.js.map +0 -19
  191. package/dist/index-v8e92nfw.js +0 -6
  192. package/dist/index-vgc3y3rm.js +0 -6
  193. package/dist/index-whaw4b18.js +0 -6
  194. package/dist/index-whaw4b18.js.map +0 -10
  195. 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")}
2
+ import{e,S,Te,A,We,kt,Ke,MA,Xe,q,Ot,Ao,to,me,no,$e,De,Nt,ae,p,b,M,vt,Gt,tA,kA,Ft,nA,k,L,so,U,Tt,Lt,Pt,go,co,C,li}from"./index-byxrc961.js";import{wn,je,mn,Dn,_e,bn,Sn,Mn}from"./index-xhzmv4dh.js";import{F,v,N,P,Vn}from"./index-b6da6c16.js";import{Di}from"./index-nn3tk25c.js";import{WA}from"./index-3km1jwh7.js";import{pA,QA,pt,Z,xo,Yo,En,zn,pn,Ee,Qn,hA,Ne,hn,Re,yA,Jo,jo}from"./index-q0hxh57v.js";import{In,PA,ke,Jn,un,uA,dn,rt,dA,st,UA,at,gt,Ro,ct,lt,It}from"./index-h828nk24.js";import{mA,DA,bt,JA,St,bA,vn,jA,we,Ve,Ge,SA,Gn}from"./index-3mtgcvkq.js";import{qn,Go,KA,Fo,To,Lo,Je}from"./index-4knb5vjm.js";import{HA,Ie,xA,Ko}from"./index-79epttpm.js";import{nt,ot,TA,cn,IA,yo,it,Do,bo}from"./index-2rycma8x.js";import"./index-k3y8y3wj.js";import{Oo,No}from"./index-yjcdp72k.js";import{CA,vo}from"./index-cgfg6t5a.js";import"./index-srmhk9g5.js";import{Po}from"./index-0k3w2mxf.js";import{Ho,Bn,fn,ne,oe,Oe,H,fA,fe,Bt}from"./index-y4c32wn7.js";import{X,ue}from"./index-5rm7dwq4.js";import{Qt,he,_o,h,zo,ie,pe,yn,Vo}from"./index-k2aq5bg0.js";import{Fe,z,_,Q,O,Fn,_A,si,R,Ae}from"./index-fzmmhmk2.js";import{V}from"./index-whq42sat.js";import{Pn}from"./index-7yk1zvds.js";import{g,B,l,c,iA,ZA,rA,sA}from"./index-wzsmh5j0.js";import{hi,wi}from"./index-5nwwekk0.js";import{Xt,vi,Me,J,An,sn,t,i,At}from"./index-2zye08c4.js";async function _n(n){let r=await Oe(n),o=[];for(let a of R()){let s=a.id??a.ref,d=await fn(s,n)??{enabled:!0},u=r.find((y)=>y.agentId===s),f=u===void 0?Number.NaN:Date.now()-Date.parse(u.startedAt);o.push({...a,enabled:d.enabled,...d.reason===void 0?{}:{reason:d.reason},...u===void 0?{}:{pid:u.pid,serving:`serving · ${u.mode} · pid ${u.pid}${Number.isFinite(f)?` · up ${ZA(f)}`:""}`}})}return o}function Cn(n){if(n.length===0)return[{label:"agents",value:"none in the sandbox",note:"init creates one"}];return n.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 $t(n){if(n.manifestPaths.length===0){let d=await _n(n.store);if(n.json===!0)process.stdout.write(`${JSON.stringify({agents:d},null,2)}
3
+ `);else process.stdout.write(`${g(Cn(d))}
4
+ `);return t}let r=await U.create({agents:[...n.manifestPaths],toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C(n.manifestPaths),store:n.store??Q(),lease:!1});h(()=>r.stop("cli-exit"));let o=r.list().map((d)=>d.describe()),a=new Map;for(let d of await r.store.leases.all()){if(d.runtimeId===r.runtimeId||!k(d.pid))continue;let u=Date.now()-Date.parse(d.startedAt);a.set(d.agentId,`serving · ${d.mode} · pid ${d.pid}${Number.isFinite(u)?` · up ${ZA(u)}`:""}`)}if(n.json===!0)return process.stdout.write(`${JSON.stringify({agents:o.map((d)=>({...d,serving:a.get(d.id)??null}))},null,2)}
5
+ `),t;let s=o.map((d)=>({label:d.id,value:`${d.model} ${String(d.window).padStart(7)} window`,note:a.get(d.id)??d.name}));return process.stdout.write(`${g(s)}
6
+ `),t}import{basename as Hn,dirname as Ar,join as Pe,resolve as Tr}from"node:path";import{rmSync as gr}from"node:fs";import{isAbsolute as xt,join as yr,resolve as Et}from"node:path";var wr=3;async function Rt(n){if(n.answers.skills!=="find")return;let r=n.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=Z(n.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 a=[],s=[];for(let m of o){if(!Ee(m.name,n.env))try{await hA(m,{...n.env===void 0?{}:{env:n.env},...n.git===void 0?{}:{git:n.git}})}catch(w){s.push(`${m.name} — ${w instanceof A?w.message:String(w)}`);continue}a.push(...Ne(m,n.env))}for(let m of s)process.stdout.write(c(`could not fetch ${m}
9
+ `));if(a.length===0){process.stdout.write(`${c("no source could be read, so no skill was installed — the directory is there and empty")}
130
10
  ${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`)}
11
+ `);return}let d=br(r,a);if(d.length===0){process.stdout.write(`${c(`nothing in ${a.length} skills matches those words, so none was installed`)}
132
12
  ${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)}
13
+ `);return}let u=d[0],f=`${u.source}/${u.skill}`;if(process.stdout.write(`${c(`best of ${a.length}: ${f}`)}
14
+ `),d.length>1)process.stdout.write(`${c(`also matched: ${d.slice(1,1+wr).map((m)=>`${m.source}/${m.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)}
16
+ `),Re({action:"install",manifestPath:n.manifestPath,name:f,...n.env===void 0?{}:{sandboxEnv:n.env},...n.envOverlay===void 0?{}:{envOverlay:n.envOverlay}})!==t)return;let x=$r(n.manifestPath,n.envOverlay);if(x!==void 0)vr(n.manifestPath,u.skill,n.envOverlay),process.stdout.write(`
17
+ ${l(`${f} was removed again: it does not load on this machine`)}
18
+ ${c(x,4)}
139
19
  ${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?`
20
+ `)}function br(n,r){let o=new Map,a=r.filter((s)=>s.problem===void 0).map((s)=>{let d=`${s.source}/${s.skill}`;return o.set(d,s),{name:d,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:d,description:s.description,metadata:{}}}});return kA(n,a).filter((s)=>s.score>0).map((s)=>o.get(s.skill.name)).filter((s)=>s!==void 0)}function $r(n,r){try{let o=b(n,{...r===void 0?{}:{env:{...process.env,...r}}}),a=o.manifest.skills;if(a===void 0)return;let s=q(o.manifest.model.main.id,o.manifest.model.main.capabilities);tA({dir:xt(a.dir)?a.dir:Et(o.dir,a.dir),maxActive:a.maxActive,threshold:a.threshold,style:s.promptStyle,agentDir:o.dir,runner:v()});return}catch(o){return o instanceof A?o.message:String(o)}}function vr(n,r,o){try{let a=b(n,{...o===void 0?{}:{env:{...process.env,...o}}}),s=a.manifest.skills;if(s===void 0)return;let d=xt(s.dir)?s.dir:Et(a.dir,s.dir);gr(yr(d,r),{recursive:!0,force:!0}),hn(d,r)}catch{}}import{existsSync as kr,mkdirSync as Sr,writeFileSync as xr}from"node:fs";import{dirname as Pr,join as Nn,resolve as Er}from"node:path";var on={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 jn(n,r,o){let a=[];for(;;){let s=Ve(n,o);if(s===void 0)break;if(s.optional===!0){n[s.step]="";continue}if(s.fallback===""){a.push(s.step),n[s.step]="(missing)";continue}let d=Ge(s.step,s.fallback);if(d.ok)n[s.step]=d.value}if(a.length>0){let s=a.map((d)=>on[d]).join(", ");throw new A({code:"cli_init_missing_answers",message:`Not interactive (${r}), and ${a.join(", ")} ${a.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 Kn(n,r){let o=n,a=mA(o.preset),s=o.apiKeyEnv??a?.apiKeyEnv,d=o.server??"local",u=o.dir??DA(o.dirChoice,o.name,r);if(u===void 0)throw new A({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:d,skills:o.skills,...o.skillsSearch===void 0||o.skillsSearch===""?{}:{skillsSearch:o.skillsSearch},...o.skillsPick===void 0||o.skillsPick===""?{}:{skillsPick:o.skillsPick},daemon:o.daemon,...d==="local"?{serverToken:Rr()}:{},...s===void 0?{}:{apiKeyEnv:s},...o.apiKey===void 0||o.apiKey===""?{}:{apiKey:o.apiKey},...o.dirChoice===void 0?{}:{dirChoice:o.dirChoice},dir:u}}function Rr(){let n=new Uint8Array(32);return crypto.getRandomValues(n),[...n].map((r)=>r.toString(16).padStart(2,"0")).join("")}function Ln(n,r){let o=r.map((a)=>Nn(n,a.relPath)).filter((a)=>kr(a));if(o.length>0)throw new A({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 a of r){let s=Nn(n,a.relPath);Sr(Pr(s),{recursive:!0}),xr(s,a.contents,{encoding:"utf8",...a.relPath===".env"?{mode:384}:{}})}}var Ct=new Map([["dir",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["dirChoice",{code:"provision_directory_refused",hint:"A provisioned agent lands in this host's sandbox, because where an agent lives on disk is the operator's decision rather than a caller's. Use `init --dir` at a terminal to put one somewhere else."}],["daemon",{code:"provision_daemon_refused",hint:"This server is already hosting the agent you are creating — that is what `adopted` in the response means. Installing a service unit is `daemon install` at a terminal, and a route that writes one would be a web page installing a background process."}]]),Un=new Map([["skills",new Map([["find",{code:"provision_skills_search_refused",hint:"Searching the catalogues is an interactive picker, not an answer — over the wire it would write no skills and report success. Send `starter` or `none`, then `skills search` and `skills install` once the agent exists."}]])]]);function jt(n){let r=Ge(n.step,n.fallback);return r.ok?r.value:n.fallback}function Ir(n,r){let o=Un.get(n.step);return{step:n.step,prompt:n.prompt,fallback:jt(n),optional:n.optional===!0,secret:jA.has(n.step),...r===void 0?{}:{requires:r},...n.options===void 0?{}:{choices:n.options.filter((a)=>o?.has(a.value)!==!0).map((a)=>({value:a.value,label:a.label,...a.hint===void 0?{}:{hint:a.hint}}))}}}var _t=64;function Kt(n){let r=new Map,o=new Set,a=(d,u)=>{let f={...d},y=[];for(let x=0;x<_t;x+=1){let m=Ve(f,n);if(m===void 0)break;let w=jt(m);if(!Ct.has(m.step)&&!r.has(m.step))r.set(m.step,Ir(m,u));for(let E of m.options??[]){if(E.value===w)continue;if(Un.get(m.step)?.has(E.value)===!0)continue;y.push({seed:{...f,[m.step]:E.value},opened:{step:m.step,value:E.value}})}f[m.step]=w}return y},s=[...a({})];for(let d=0;d<_t&&s.length>0;d+=1){let u=s.splice(0,s.length);for(let f of u){let y=`${f.opened.step}=${f.opened.value}`;if(o.has(y))continue;o.add(y),s.push(...a(f.seed,f.opened))}}return[...r.values()].sort((d,u)=>vn.indexOf(d.step)-vn.indexOf(u.step))}function Ut(n){let r={};for(let[f,y]of Object.entries(n.answers)){let x=f;if(!(x in on))throw new A({code:"provision_unknown_answer",message:`"${f}" 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:f});let m=Ct.get(x);if(m!==void 0)throw new A({code:m.code,message:`"${f}" cannot be set over the API.`,hint:m.hint,field:f});let w=Un.get(x)?.get(y.trim().toLowerCase());if(w!==void 0)throw new A({code:w.code,message:`${f} is ${JSON.stringify(y)}, which this runtime cannot do over the API.`,hint:w.hint,field:f});let E=Ge(x,y);if(!E.ok)throw new A({code:"provision_answer_invalid",message:`${f} is ${JSON.stringify(y)}, which ${E.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:f});r[x]=E.value}jn(r,"this is the provisioning API",n.defaults);let o=Kn(r,n.defaults),a=we(o.name),s=DA("sandbox",o.name,n.defaults);if(s===void 0)throw new A({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 d=Er(s),u=Gn({...o,dir:d});return Ln(d,u),{agentId:a,dir:d,manifestPath:Nn(d,"agent.yaml"),files:u.map((f)=>f.relPath)}}function Or(n){if(n.web!=="search")return;return bt(n.webBackend??"tavily")?.apiKeyEnv}async function Mt(n){let r=await Dt(n);if(r.kind==="aborted")return process.stdout.write(`nothing written
21
+ `),t;return r.kind==="failed"?r.code:t}async function Wn(n){return Dt(n)}async function Dt(n){let r=Cr(n),o=ue({json:!1,plain:n.plain===!0,oneShot:!1}),a=o.mode==="rich"&&n.yes!==!0,s={agentDirBase:_()};if(a){let T=await Nr(r,s);if(T===void 0)return{kind:"aborted"};Object.assign(r,T)}else jn(r,n.yes===!0?"--yes was passed":o.because,s);let d=Kn(r,s),u=Tr(process.cwd(),d.dir),f=si(u);if(f!==void 0)process.stderr.write(`${f}
22
+ `);let y=Pe(u,"agent.yaml"),x=Gn(d);Ln(u,x);let m=d.apiKeyEnv,w=m!==void 0&&d.apiKey===void 0&&(process.env[m]===void 0||process.env[m]===""),E=w&&m!==void 0?{[m]:"(pending)"}:void 0,j=!1;try{let T=b(Pe(u,"agent.yaml"),{...w?{env:{...process.env,[m]:"(pending)"}}:{}}),de=q(T.manifest.model.main.id,T.manifest.model.main.capabilities),{workspace:K,warnings:re}=nA(T,de.promptStyle),G=Ke(K,T.manifest.context.rules);if(G!==void 0&&T.manifest.context.rules.onExceed==="fail")throw G;j=re.some((ee)=>ee.code==="soul_distilled")}catch(T){if(T instanceof A)return process.stderr.write(`init wrote ${x.length} files to ${u}, but the result does not load:
23
+ ${T.format()}
24
+ `),{kind:"failed",code:i};throw T}if(process.stdout.write(`wrote ${x.length} files to ${u} — validated ok
25
+ `),d.skills==="find"){let T=(d.skillsPick??"").split(",").map((de)=>de.trim()).filter((de)=>de!=="");if(T.length>0)Jo(T,y,{...E===void 0?{}:{envOverlay:E}});else if(!a)await Rt({answers:d,manifestPath:y,...E===void 0?{}:{envOverlay:E}})}let W;if(d.daemon==="service"){process.stdout.write(`
26
+ `);let{outcome:T,host:de}=await rt({...n.installServer===void 0?{}:{install:n.installServer}}),K=uA(T);if(K!==void 0)process.stderr.write(K);if(de?.baseUrl!==void 0){let re=await dA(de,y);if(re.ok)W=de.baseUrl;else process.stderr.write(`pid ${de.pid} did not adopt ${we(d.name)}${re.detail===void 0?"":`: ${re.detail}`}
27
+ `)}}let I;if(d.whatsapp==="connected"&&(d.whatsappNumber??"")!==""&&a)I=W!==void 0?await at({manifestPath:y,channelId:"wa"}):await gt({manifestPath:y,dir:u,number:d.whatsappNumber??"",channelId:"wa"});if(d.whatsapp==="connected"&&I!=="paired")process.stdout.write(`
28
+ ${Ro(we(d.name))}`);return process.stdout.write(jr(d,u,j,W)),{kind:"ok",manifestPath:Pe(u,"agent.yaml")}}function _r(n){if(n===void 0)return[];if(bA.some((r)=>r.value===n))return[["skills",n]];return[["skills","find"],["skillsSearch",n]]}function Cr(n){let r={},o=[["user",n.user],["name",n.name],["purpose",n.purpose],["preset",n.preset],["model",n.model],["baseUrl",n.baseUrl],["apiKeyEnv",n.apiKeyEnv],["system",n.system],["web",n.web],["webBackend",n.webBackend],["composio",n.composio],["telegram",n.telegram],["telegramAllow",n.telegramAllow],["whatsapp",n.whatsapp],["whatsappNumber",n.whatsappNumber],["server",n.server],["schedules",n.schedules],..._r(n.skills),["daemon",n.daemon],["dir",n.dir]];for(let[a,s]of o){if(s===void 0)continue;let d=Ge(a,s);if(!d.ok)throw new A({code:"cli_init_flag_invalid",message:`${on[a]} is ${JSON.stringify(s)}, which ${d.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[a]=d.value}return r}async function Nr(n,r){let[{render:o},{createElement:a},{WizardApp:s}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-123998yh.js")]),d;Qt();let u=o(a(s,{title:`${e.name} ${M}`,given:n,defaults:r,onDone:(f)=>{d=f}}),{exitOnCtrlC:!1,...X()});return h(()=>u.unmount()),await u.waitUntilExit(),u.unmount(),d}function jr(n,r,o,a){let s=a!==void 0,u=Ar(r)===_()?Hn(r):Pe(r,"agent.yaml"),f=Pe(r,"agent.yaml"),y=[];if(n.apiKeyEnv!==void 0&&n.apiKey===void 0)y.push(`Add your key: edit ${Pe(r,".env")} and set ${n.apiKeyEnv}=`);let x=Or(n);if(x!==void 0&&n.webKey===void 0)y.push(`Add your search key: edit ${Pe(r,".env")} and set ${x}= — web_fetch works without it, web_search does not`);if(SA(n)&&n.composioKey===void 0)y.push(`Add your Composio key: edit ${Pe(r,".env")} and set ${JA}=`);if(n.telegram==="connected"&&n.telegramToken===void 0)y.push(`Add your bot token: message @BotFather with /newbot, then edit ${Pe(r,".env")} and set ${St}=`);let m=[...n.telegram==="connected"?["the Telegram bot"]:[],...n.whatsapp==="connected"?["WhatsApp"]:[]],w=m.length>0||n.server==="local",E=[...m,...n.server==="local"?["the HTTP API"]:[]].join(" and ");if(s)y.push(`open ${Je(a,Hn(r))} — the web UI. The service is serving `+`${Hn(r)} now; ${E} ${m.length+(n.server==="local"?1:0)===1?"is":"are"} up.`),y.push(`${e.slug} run ${u} — talks to it here, attached to that same service.`);else y.push(`${e.slug} run ${u}`);if(w&&!s){if(y.push(`${e.slug} serve ${u} — starts ${E}; \`run\` starts neither`),n.daemon==="service")y.push(`${e.slug} daemon install — the same thing, supervised: one service hosts `+"every agent, starts at login and survives a reboot.")}if(n.telegram==="connected"&&n.telegramAllow===void 0)y.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(SA(n))y.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.");y.push(n.skills==="find"?`Add more skills: \`${e.slug} sources search <what it should do>\` ranks every skill in the catalogues, then \`${e.slug} skills install ${u} <source>/<skill>\`.`:n.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 ${u} <name>\` writes one.`),y.push("Make workspace/SOUL.md yours, then re-derive SOUL.compact.md to match — "+`\`${e.slug} workspace ${f}\` shows exactly what still reads as a template.`);let j=s?`
29
+ it is running in the background now — \`${e.slug} status\` at any time,
30
+ \`${e.slug} restart ${u}\` after editing it, and \`${e.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
+ `:""}${j}
35
+ `+y.map((I,T)=>` ${T+1}. ${I}
36
+ `).join("")}var an=16;function ln(n=process.stdin){let r=[],o=[],a=(s)=>{let d=typeof s==="string"?s:s.toString("utf8");if(o.push(d),o.length>an)o.splice(0,o.length-an);if(r.push(...hi(d)),r.length>an)r.splice(0,r.length-an)};return n.on("data",a),{correct:(s,d)=>wi(s,d,r),takeRaw:()=>o.shift(),close:()=>{n.off("data",a)}}}var Ht=[{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 gn(n){let r=n.TERM_PROGRAM??"";if(r==="vscode")return"vscode";if(r==="ghostty"||n.GHOSTTY_RESOURCES_DIR!==void 0)return"ghostty";if(n.KITTY_WINDOW_ID!==void 0||n.TERM==="xterm-kitty")return"kitty";if(n.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 $n(n){return Ht.find((r)=>r.id===n)}function Wt(){return Ht}function qt(n,r){return r.marker!==void 0&&n.includes(r.marker)}function Vt(n,r){let o=r.line;if(o===void 0)return;if(r.id!=="vscode"){let f=n.trimEnd();return f===""?`${o}
37
+ `:`${f}
38
+ ${o}
39
+ `}let a=n.trim();if(a===""||a==="[]")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=a.indexOf("[");if(s===-1)return;let u=a.slice(s+1).trimStart().startsWith("]")?"":",";return`${a.slice(0,s+1)}
43
+ ${o}${u}
44
+ ${a.slice(s+1)}`}async function Jt(n={}){let r=ue({plain:!1,json:!1,oneShot:!1});if(r.mode!=="rich")throw new A({code:"cli_keys_needs_terminal",message:"The key probe needs a terminal — it has nothing to read on a pipe.",hint:`Not one here (${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=X(n.noEnhancedKeys),a=o.kittyKeyboard!==void 0,s=gn(process.env),d=$n(s)?.name??s,[{render:u},{createElement:f},{KeyProbe:y}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-ya5t3v3v.js")]),x=()=>{},m=new Promise((j)=>{x=j}),w=ln();h(()=>{w.close()}),he(),process.stdout.write(Me);let E=u(f(y,{columns:V(process.stdout.columns,J),asked:a,terminal:d,takeRaw:w.takeRaw,correctKeys:w.correct,onDone:x}),{exitOnCtrlC:!1,...o});return h(()=>E.unmount()),await m,E.unmount(),w.close(),ie(),await pe(),t}var Fr=24,Xn=22;function Yn(n){let r=n.args.map((o)=>{let a=o.variadic===!0?`${o.name}...`:o.name;return o.required?`<${a}>`:`[${a}]`}).join(" ");return`${e.slug} ${n.name}${r===""?"":` ${r}`}`}function zt(n){let r=n.placeholder===void 0?`--${n.name}`:`--${n.name} <${n.placeholder}>`,o=n.short===void 0?r:`-${n.short}, ${r}`,a=n.defaultHelp===void 0?"":` (default ${n.defaultHelp})`;return` ${o.padEnd(Fr)}${n.help}${a}`}var Yt=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
45
+ delivery reads the channel back out of the key.`;function Kr(n){let r=[];for(let o of n.args){if(o.choices===void 0||o.choices.length===0)continue;let a=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(a)}${s.help}`)}return r}function Zn(n){if(n!==void 0){let o=[n.summary,"","usage:",` ${Yn(n)} [flags]`,...Kr(n),"","flags:",...xA(n).map(zt)];if(n.flags.some((a)=>a.name==="session"))o.push("",Yt);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(...Ie.map((o)=>Yn(o).length))+2;return`${[`${e.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...Ie.map((o)=>` ${Yn(o).padEnd(r)}${o.summary}`),` ${e.slug} --version`,` ${e.slug} --help`,"",`Per-command flags: ${e.slug} <command> --help`,"","global flags:",...HA.map(zt),"",Yt,"","environment:",` ${`${e.envPrefix}BRAND`.padEnd(Xn)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(Xn)}set to anything to force plain output`,` ${"DEBUG".padEnd(Xn)}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 Lr=[{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 Ur(n,r){return Lr.some((o)=>o.name===n&&r.includes(o.contains))}function Mr(n){return n.execArgv.includes("--trace-warnings")||(n.nodeOptions??"").includes("--trace-warnings")}var Zt;function es(n={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(Zt)return;if(Mr(n))return;let r=process.emitWarning;Zt=r,process.emitWarning=(o,...a)=>{let s=typeof o==="string"?Dr(a):o.name,d=typeof o==="string"?o:o.message;if(Ur(s,d))return;Reflect.apply(r,process,[o,...a])}}function Dr(n){let r=n[0];return typeof r==="string"?r:"Warning"}var ns=96;async function ss(n){let r=await U.create({agents:[n.manifestPath],store:n.store??Q(),toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C([n.manifestPath])});try{let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");if(n.action==="rebuild"){let y=await o.rebuildMemory();if(n.json===!0)return process.stdout.write(`${JSON.stringify(y,null,2)}
50
+ `),t;return process.stdout.write(g([{label:"passages",value:String(y.passages)},{label:"files read",value:String(y.indexed.length)},{label:"conversations",value:y.sessions.length===0?"none indexed — memory.includeHistory is off, or there are no sessions yet":String(y.sessions.length)},{label:"dropped",value:y.dropped.length===0?"":y.dropped.join(", ")}])),process.stdout.write(y.indexed.length===0&&y.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: ${[...y.indexed,...y.sessions].join(", ")}
52
+ `),t}let a=n.query??"";if(a.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'),i;let s=await o.searchMemory({query:a,limit:n.limit??10}),d=s.hits.filter((y)=>y.score>=s.threshold),u=n.all===!0?s.hits:d;if(n.json===!0)return process.stdout.write(`${JSON.stringify({query:a,corpus:s.corpus,threshold:s.threshold,carried:s.carried??null,hits:u.map((y)=>({source:y.passage.source,at:y.passage.at,score:y.score,lexical:y.lexical,coverage:y.coverage,tokens:y.tokens,wouldInject:y.score>=s.threshold,carried:y.passage.source===s.carried,text:y.passage.text}))},null,2)}
54
+ `),t;if(process.stdout.write(g([{label:"corpus",value:`${s.corpus} passage${s.corpus===1?"":"s"}`},{label:"threshold",value:s.threshold.toFixed(2)},{label:"above it",value:String(d.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"),t;if(u.length===0)return process.stdout.write(`
55
+ Nothing ${n.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
+ `),t;let f=Math.max(6,...u.map((y)=>ts(y,s.carried).length));process.stdout.write(`
57
+ ${xe("SCORE",6)} ${xe("LEXICAL",7)} ${xe("COVER",5)} ${xe("SOURCE",f)} ${xe("LEARNED",10)} PASSAGE
58
+ `);for(let y of u){let x=y.score>=s.threshold?" ":"·";process.stdout.write(`${xe(y.score.toFixed(3),6)} ${xe(y.lexical.toFixed(3),7)} ${xe(y.coverage.toFixed(2),5)} ${xe(ts(y,s.carried),f)} ${xe(y.passage.at.slice(0,10),10)} ${x}${Hr(y.passage.text)}
59
+ `)}if(n.all===!0&&d.length<u.length)process.stdout.write(`
60
+ ${u.length-d.length} shown below the threshold; a turn would not inject those.
61
+ `);if(s.carried!==void 0&&u.some((y)=>y.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 t}finally{await r.stop("cli-exit")}}function Hr(n){let r=n.replace(/\s+/g," ").trim();return r.length<=ns?r:`${r.slice(0,ns-1)}…`}function xe(n,r){return n.length>=r?n:n+" ".repeat(r-n.length)}function ts(n,r){return n.passage.source===r?`${n.passage.source} *`:n.passage.source}var Wr=["context_length","context_window","max_context_length","max_model_len"],qr=[["prompt_cache_hit_tokens",(n)=>n.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(n)=>{let r=n.prompt_tokens_details;return kn(r)?r.cached_tokens:void 0}],["cache_read_input_tokens",(n)=>n.cache_read_input_tokens]];function kn(n){return typeof n==="object"&&n!==null&&!Array.isArray(n)}function et(n){if(typeof n!=="number"||!Number.isFinite(n))return;if(!Number.isInteger(n)||n<=0)return;return n}function rs(n,r){let o=kn(n)?n.data:void 0,a=Array.isArray(o)?o:Array.isArray(n)?n:void 0;if(a===void 0)return;let s=r.toLowerCase();for(let d of a){if(!kn(d))continue;let u=typeof d.id==="string"?d.id.toLowerCase():void 0;if(u===void 0)continue;if(!(u===s||u.endsWith(`/${s}`)||s.endsWith(`/${u}`)))continue;for(let y of Wr){let x=et(d[y]);if(x!==void 0)return{technique:"metadata",tokens:x,bound:"ceiling",detail:`GET /models published ${y}: ${x}`}}return}return}function tt(n){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 a of r){let s=a.exec(n);if(s?.[1]===void 0)continue;let d=et(Number(s[1].replaceAll(/[,_]/g,"")));if(d!==void 0)o.push(d)}if(o.length===0)return;return Math.max(...o)}function os(n){if(!kn(n))return;let r=et(n.prompt_tokens)??0;for(let[o,a]of qr){let s=a(n);if(typeof s==="number"&&Number.isFinite(s))return{cached:s,promptTokens:r,field:o}}return{cached:void 0,promptTokens:r,field:void 0}}function is(n,r,o){if(n===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 a=r.cached??0;if(a>0)return{supported:!0,detail:`the second identical call reported ${a} 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 en(n){let r=n.filter((a)=>a.bound==="ceiling");return(r.length>0?r:n).reduce((a,s)=>a===void 0||s.tokens>a.tokens?s:a,void 0)}function as(n,r,o){return[" {",` pattern: "${`${n.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 ds(n,r,o){return`measured ${r} against ${n} — ${o}`}function ls(n,r){let o=Math.max(1,n),a=0,s=0;while(o<r)a+=o,s+=1,o*=2;return a+=r,s+=1,{requests:s,tokens:a}}var Gr=2000000000,cs=1024,fs=8192,ms=2097152;function ps(n){return"context ".repeat(Math.max(1,n))}async function nn(n){let r=await n.text();try{return{text:r,json:JSON.parse(r)}}catch{return{text:r,json:void 0}}}function hs(n,r){if(typeof n==="object"&&n!==null){let o=n,a=o.error;if(typeof a==="string")return a;if(typeof a==="object"&&a!==null){let s=a.message;if(typeof s==="string")return s}if(typeof o.message==="string")return o.message}return r}async function Br(n,r,o){try{let a=await r(n.models,{headers:n.headers});if(!a.ok){o.push(`GET /models answered ${a.status}`);return}let{json:s}=await nn(a),d=rs(s,n.modelId);if(d===void 0)o.push("GET /models published no context length");return d}catch(a){o.push(`GET /models failed: ${a instanceof Error?a.message:String(a)}`);return}}async function Vr(n,r,o){try{let a=await r(n.chat,{method:"POST",headers:{"content-type":"application/json",...n.headers},body:JSON.stringify({model:n.modelId,messages:[{role:"user",content:"hi"}],max_tokens:Gr})}),{text:s,json:d}=await nn(a);if(a.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 u=hs(d,s.slice(0,400)),f=tt(u);if(f===void 0)return o.push(`the refusal named no number: ${u.slice(0,160)}`),{window:void 0,outputCeiling:void 0};let y=/max_?tokens/i.test(u);return{window:y?void 0:{technique:"refusal",tokens:f,bound:"ceiling",detail:`refused an over-range request naming ${f}`},outputCeiling:y?f:void 0}}catch(a){return o.push(`the over-range request failed: ${a instanceof Error?a.message:String(a)}`),{window:void 0,outputCeiling:void 0}}}async function us(n,r,o){let a=await r(n.chat,{method:"POST",headers:{"content-type":"application/json",...n.headers},body:JSON.stringify({model:n.modelId,messages:[{role:"user",content:o}],max_tokens:1})});if(!a.ok)return;let{json:s}=await nn(a),d=typeof s==="object"&&s!==null?s.usage:void 0;return os(d)}async function Jr(n,r,o){let a=`${ps(cs)}
65
+ Reply with the single character x.`;try{let s=await us(n,r,a),d=await us(n,r,a);return is(s,d,cs)}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 Xr(n,r,o){let a=fs,s=0;while(a<=ms){let d;try{d=await r(n.chat,{method:"POST",headers:{"content-type":"application/json",...n.headers},body:JSON.stringify({model:n.modelId,messages:[{role:"user",content:ps(a)}],max_tokens:1})})}catch(x){o.push(`the search stopped at ${a}: ${x instanceof Error?x.message:String(x)}`);break}if(d.ok){let{json:x}=await nn(d),m=typeof x==="object"&&x!==null?x.usage:void 0,w=typeof m==="object"&&m!==null?m.prompt_tokens:void 0;s=typeof w==="number"&&Number.isFinite(w)?w:s,a*=2;continue}let{text:u,json:f}=await nn(d),y=tt(hs(f,u.slice(0,400)));if(y!==void 0)return{technique:"search",tokens:y,bound:"ceiling",detail:`refused a ${a}-token prompt and named ${y}`};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 zr(n,r){let o=en(n.findings),a=o===void 0?"nothing measured — every technique came back empty":`${o.tokens} (${o.bound}) · ${o.detail}`,s=o===void 0?"":o.tokens===n.declared?"matches what is configured":o.bound==="ceiling"&&o.tokens>n.declared?`configured value is ${n.declared}, which is ${(o.tokens-n.declared).toLocaleString("en-US")} tokens short`:`configured value is ${n.declared}`,d=n.cache.supported===void 0?`unknown — ${n.cache.detail}`:n.cache.supported?`yes — ${n.cache.detail}`:`no — ${n.cache.detail}`;return[B(` ${n.role} · ${n.modelId}`),g([{label:"endpoint",value:n.baseUrl},{label:"configured",value:`${n.declared} (${n.declaredSource})`},{label:"measured",value:a},{label:"agreement",value:s},{label:"output cap",value:n.outputCeiling===void 0?"":String(n.outputCeiling)},{label:"prompt cache",value:d},...r===void 0?[]:[{label:"price",value:`$${r}/Mtok input, as given`}]]),...n.failures.length===0?[]:[" what did not answer:",...n.failures.map((u)=>` · ${u}`)],...o===void 0||o.bound!=="ceiling"?[]:[""," registry row, if this model should ship with it:",as(n.modelId,o.tokens,n.outputCeiling).split(`
66
+ `).map((u)=>` ${u}`).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 gs(n){let r=n.fetch??globalThis.fetch;try{let o=b(n.manifestPath,{env:C([n.manifestPath])}),{manifest:a}=o,s=me(a).filter((y)=>y.role===y.configuredAs),d=!1;if(n.window){let y=ls(fs,ms),x=y.tokens*s.length,m=n.price===void 0?"":` ≈ $${(x/1e6*n.price).toFixed(2)}`;process.stdout.write(`--window will send up to ${y.requests} requests per role, about ${x.toLocaleString("en-US")} input tokens in total${m}.
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
+ `),d=n.yes||await CA("spend it?"),process.stdout.write(d?`
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 u=[];for(let y of s){let x=a.model[y.role]??a.model.main,m={chat:Ot(x.baseUrl),models:Ao(x.baseUrl),headers:to(x.apiKeyEnv,o.env,`model.${y.role}`),modelId:x.id},w=[],E=[],j=await Br(m,r,w);if(j!==void 0)E.push(j);let W=await Vr(m,r,w);if(W.window!==void 0)E.push(W.window);let I=await Jr(m,r,w);if(d){let T=await Xr(m,r,w);if(T!==void 0)E.push(T)}u.push({role:y.role,modelId:x.id,baseUrl:x.baseUrl,declared:y.window.contextWindow,declaredSource:y.window.source,findings:E,cache:I,outputCeiling:W.outputCeiling,failures:w})}if(n.json)return process.stdout.write(`${JSON.stringify({agent:a.id,probes:u},null,2)}
76
+ `),t;let f=n.write?await Qr(o.path,u):{written:[],refused:[]};return process.stdout.write([`probed ${a.id} · ${u.length} role${u.length===1?"":"s"}`,...u.map((y)=>zr(y,n.price)),"",...n.write?[...f.written.length===0?[]:[" written to the manifest:",...f.written.map((y)=>` ${y}`)],...f.refused.length===0?[]:[" not written:",...f.refused.map((y)=>` ${y}`)]," A restart picks it up — an agent's settings are fixed for its lifetime."]:[Yr(u)],""].join(`
77
+ `)),t}catch(o){if(o instanceof A)return process.stderr.write(`${o.format()}
78
+ `),i;throw o}}async function Qr(n,r){let o=[],a=[];for(let s of r){let d=en(s.findings);if(d===void 0){a.push(`${s.role}: nothing measured`);continue}if(d.bound!=="ceiling"){a.push(`${s.role}: ${d.tokens} is a floor, not a window — the endpoint accepted it and never said what it would refuse`);continue}if(d.tokens===s.declared){a.push(`${s.role}: already ${d.tokens}, nothing to change`);continue}await ae({file:n,path:["model",s.role,"capabilities","contextWindow"],value:d.tokens}),o.push(`${s.role}: ${s.declared} → ${d.tokens}`)}return{written:o,refused:a}}function Yr(n){let r=n.filter((d)=>en(d.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],a=o===void 0?void 0:en(o.findings);if(o===void 0||a===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: ${a.tokens}`,` # ${ds(s,new Date().toISOString().slice(0,10),a.detail)}`].join(`
79
+ `)}import{existsSync as Ps,rmSync as lo}from"node:fs";import{resolve as uo}from"node:path";var Zr={debug:()=>{},info:()=>{},warn:()=>{},error:()=>{}};function ys(n){if(n===null||typeof n!=="object")return!1;let r=n.kind;return r==="network"||r==="env"||r==="fs"||r==="exec"||r==="store"}async function ws(n,r={}){let o=[],a=[],s=r.hostVersion??je,d=(E,j,W)=>{o.push({level:"error",check:E,message:j,hint:W})},u=(E,j,W)=>{o.push({level:"warning",check:E,message:j,hint:W})};if(typeof n.name!=="string"||n.name==="")d("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(mn(n.version,"*")===void 0)d("version",`\`version\` is ${JSON.stringify(n.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 f=mn(s,n.dispachApi);if(f===void 0)d("dispachApi",`\`dispachApi\` is ${JSON.stringify(n.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(!f)u("dispachApi",`\`dispachApi\` ${n.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(n.dispachApi.trim()==="*")u("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[E,j]of(n.permissions??[]).entries())if(!ys(j))d("permissions",`\`permissions[${E}]\` 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 y=r.config??{};if(n.configSchema!==void 0){let E=n.configSchema.safeParse(y);if(E.success)y=E.data;else u("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 x={defineChannel:(E)=>a.push(`channel:${E}`),defineToolProvider:(E)=>a.push(`toolProvider:${E}`),defineScriptRunner:()=>a.push("scriptRunner"),use:(E)=>a.push(`middleware:${E.name}`),config:y,agentId:"conformance",paths:{workspace:"/nonexistent/conformance",state:"/nonexistent/conformance/.state",manifest:"/nonexistent/conformance/agent.yaml"},env:{},logger:Zr,events:new wn({runtimeId:"conformance"})},m=performance.now();try{await n.setup(x)}catch(E){d("setup",`\`setup\` threw: ${E instanceof Error?E.message:String(E)}`,"`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 w=Math.round((performance.now()-m)*100)/100;if(w>Dn)d("setup budget",`\`setup\` took ${w} ms against a ${Dn} 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(a.length===0)u("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((E)=>E.level!=="error"),findings:o,registered:a,setupMs:w,declared:{name:n.name,version:n.version,apiRange:n.dispachApi,permissions:(n.permissions??[]).filter(ys)}}}import{existsSync as Ue,mkdirSync as eo,readdirSync as ro,readFileSync as dt,renameSync as bs,rmSync as Le,writeFileSync as oo}from"node:fs";import{join as ve}from"node:path";var $s=".origin.json";function io(n){let r=ve(n,$s);if(!Ue(r))return;try{return JSON.parse(dt(r,"utf8"))}catch{return}}function ut(n){let r=O(n),o;try{o=ro(r)}catch{return[]}let a=[];for(let s of o.sort()){if(s.startsWith(".")||s.endsWith(".partial"))continue;let d=ve(r,s);if(!Ue(ve(d,"package.json"))&&!Ue(ve(d,"index.js")))continue;let u=io(d);a.push({name:s,dir:d,...u===void 0?{}:{origin:u}})}return a}function vs(n){let r=ve(n,"package.json");if(!Ue(r))return ve(n,"index.js");try{let o=JSON.parse(dt(r,"utf8"));if(typeof o.main==="string"&&o.main!=="")return ve(n,o.main)}catch{}return ve(n,"index.js")}function ks(n){let r=ve(n,"package.json");if(!Ue(r))return;let o;try{o=JSON.parse(dt(r,"utf8"))}catch(d){return`its package.json is not valid JSON (${d instanceof Error?d.message:String(d)})`}let a=Object.keys(o.dependencies??{});if(a.length===0)return;if(Ue(ve(n,"node_modules")))return;let s=a.slice(0,4).join(", ");return`it declares ${a.length} runtime ${a.length===1?"dependency":"dependencies"} (${s}${a.length>4?", …":""}) and ships no node_modules`}function Ss(n,r){let a=((r??n).split("/").filter((s)=>s.length>0).pop()??"").replace(/\.git$/,"");if(!QA(a))throw new A({code:"plugin_name_invalid",message:`${JSON.stringify(a||n)} 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 a}async function xs(n,r={}){let o=r.git??zn,a=Fn(n.name,r.env),s=`${a}.partial`;eo(O(r.env),{recursive:!0}),Le(s,{recursive:!0,force:!0});let d=await o(["clone","--depth","1","--single-branch",...n.ref===void 0?[]:["--branch",n.ref],n.url,s]);if(d.code!==0)throw Le(s,{recursive:!0,force:!0}),ao(n,d.stderr,d.timedOut===!0);let u=await o(["rev-parse","--short","HEAD"],s),f=u.code===0?u.stdout.trim():"unknown",y=n.path===void 0?s:ve(s,n.path);if(!Ue(y))throw Le(s,{recursive:!0,force:!0}),new A({code:"plugin_path_missing",message:`${n.url} has no ${n.path} at ${f}`,hint:"The path comes from the URL you pasted — .../tree/<branch>/<subdir>. Check it against the repository, or pass the repository URL on its own."});Le(ve(y,".git"),{recursive:!0,force:!0});try{await r.inspect?.(y)}catch(m){throw Le(s,{recursive:!0,force:!0}),m}if(Le(a,{recursive:!0,force:!0}),y===s)bs(s,a);else bs(y,a),Le(s,{recursive:!0,force:!0});let x={url:n.url,...n.ref===void 0?{}:{ref:n.ref},...n.path===void 0?{}:{path:n.path},commit:f,fetchedAt:new Date().toISOString()};return oo(ve(a,$s),`${JSON.stringify(x,null,4)}
80
+ `),{dir:a,commit:f}}function ao(n,r,o){let a=r.trim().split(`
81
+ `).slice(-3).join(" ");if(o)return new A({code:"plugin_fetch_timeout",message:`${n.name}: git did not finish in time`,hint:`Check the network and try again — the partial fetch was discarded, so whatever was installed as ${n.name} is untouched.`});return new A({code:"plugin_fetch_failed",message:`${n.name}: could not clone ${n.url}${a.length===0?"":` — ${a}`}`,hint:"A private repository needs a credential helper git can use without prompting. Check the URL and the --ref; nothing was written."})}async function Es(n){switch(n.action){case"list":return await fo(n);case"add":return await po(n);case"remove":return await ko(n);default:throw new A({code:"cli_plugins_action_unknown",message:`plugins: ${JSON.stringify(n.action)} is not an action`,hint:`Actions are list, add and remove — \`${e.slug} plugins list <agent>\`.`})}}async function fo(n){let r=await U.create({agents:[n.manifestPath],toolProviders:F,builtInPlugins:P,pluginRoot:O(n.env),scriptRunner:v(),channels:N,env:C([n.manifestPath]),store:Q(n.env),lease:!1});h(()=>r.stop("cli-exit"));let o=[...r.plugins.values()].flat(),a=ut(n.env);if(n.json===!0)return process.stdout.write(`${JSON.stringify({plugins:o,installed:a,available:Vn},null,2)}
82
+ `),t;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
+ ${Vn.map((f)=>` - "${f}"`).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 \`${e.slug} plugins add <agent> <repo>\`.
88
+ `),a.length>0)process.stdout.write(`
89
+ Installed in ${O(n.env)} and named by no agent:
90
+ ${a.map((f)=>` - "${f.name}"`).join(`
91
+ `)}
92
+ `);return t}let s=o.map((f)=>({label:f.name,value:`${f.version} ${`${f.setupMs} ms`.padStart(9)}`,note:`${mo(f.spec,f.lookup,a)} — ${f.registered.length===0?"registered nothing":f.registered.join(", ")}`}));process.stdout.write(`${g(s)}
93
+ `);let d=o.filter((f)=>f.permissions.length>0);if(d.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 f of d)for(let y of f.permissions)process.stdout.write(` ${f.name} ${y.kind} ${Rs(y)}
96
+ `)}let u=a.filter((f)=>!o.some((y)=>y.spec===f.name));if(u.length>0)process.stdout.write(`
97
+ Also installed, named by no agent: ${u.map((f)=>f.name).join(", ")}
98
+ `);return t}function mo(n,r,o){if(r!=="installed")return r==="registry"?"built in":"imported";let a=o.find((s)=>s.name===n)?.origin;return a===void 0?"installed":`installed ${a.commit}`}function Rs(n){switch(n.kind){case"network":return n.hosts.join(", ");case"env":return n.vars.join(", ");case"fs":return`${n.paths.join(", ")} (${n.mode})`;case"exec":return n.commands.join(", ");default:return n.tables.join(", ")}}async function po(n){let r=n.rest?.[0];if(r===void 0||r==="")throw new A({code:"cli_plugins_add_needs_repo",message:"plugins add needs a repository",hint:`\`${e.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=Qn(r)?{url:uo(r.replace(/^file:\/\//,""))}:En(r),a=n.ref??o.ref,s=n.name===void 0?Ss(o.url,o.path):ho(n.name),d=ut(n.env).find((w)=>w.name===s);if(d?.origin!==void 0&&d.origin.url!==o.url)throw new A({code:"plugin_name_taken",message:`A different plugin is already installed as "${s}" — from ${d.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 \`${e.slug} plugins remove <agent> ${s}\` first.`});process.stdout.write(`Fetching ${o.url}${a===void 0?"":` at ${a}`} as "${s}"…
99
+ `);let u,f=await xs({name:s,url:o.url,...a===void 0?{}:{ref:a},...o.path===void 0?{}:{path:o.path}},{...n.env===void 0?{}:{env:n.env},...n.git===void 0?{}:{git:n.git},inspect:async(w)=>{let E=ks(w);if(E!==void 0)throw new A({code:"plugin_not_self_contained",message:`${s} cannot be loaded as fetched: ${E}`,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 j=vs(w);if(!Ps(j))throw new A({code:"plugin_entry_missing",message:`${s} has no entry file — ${j.slice(w.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 W=await wo(s,j);if(u=await ws(W),!u.ok)throw new A({code:"plugin_not_conformant",message:`${u.declared.name} does not meet the plugin contract:
100
+ ${u.findings.filter((I)=>I.level==="error").map((I)=>` ${I.check}: ${I.message}`).join(`
101
+ `)}`,hint:`This is the same suite the plugin's own author runs — \`conformance()\` from ${e.packageScope}/core/testing. Nothing was installed. Report it upstream with the checks named above.`});if(vt(M,u.declared.apiRange)!==!0)throw new A({code:"plugin_api_mismatch",message:`${u.declared.name} ${u.declared.version} supports host ${u.declared.apiRange}, and this host is ${M}`,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."})}}),y=u?.declared;if(process.stdout.write(`
102
+ ${y?.name??s} ${y?.version??"?"} (${f.commit})
103
+ from ${o.url}${a===void 0?"":` at ${a}`}
104
+ installed ${f.dir}
105
+ host range ${y?.apiRange??"?"} — this host is ${M}
106
+ registers ${u===void 0||u.registered.length===0?"nothing":u.registered.join(", ")}
107
+ `),y!==void 0&&y.permissions.length>0)process.stdout.write(`
108
+ It declares access to:
109
+ ${y.permissions.map((w)=>` ${w.kind} ${Rs(w)}`).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 x=u?.findings.filter((w)=>w.level==="warning")??[];for(let w of x)process.stdout.write(`
117
+ note: ${w.check} — ${w.message}
118
+ `);if(y!==void 0&&y.name!==s)process.stdout.write(`
119
+ note: it calls itself "${y.name}"; the \`plugins:\` entry is the directory, "${s}".
120
+ `);let m=await $o(n.manifestPath,s);return process.stdout.write(m==="already"?`
121
+ ${n.manifestPath} already names "${s}".
122
+ `:`
123
+ Added "${s}" to the plugins: block in ${n.manifestPath}.
124
+ It loads at the next start — an agent's plugins are fixed for its lifetime, so restart a running one.
125
+ `),t}function ho(n){if(QA(n))return n;throw new A({code:"plugin_name_invalid",message:`--name ${JSON.stringify(n)} 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 wo(n,r){let o;try{o=await import(r)}catch(s){throw new A({code:"plugin_import_failed",message:`${n}: ${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 a=o.default;if(a===null||typeof a!=="object")throw new A({code:"plugin_malformed",message:`${n}: ${r} has no object as its default export`,hint:`A plugin is the module's default export: an object with \`name\`, \`version\`, a \`${e.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 a.setup!=="function")throw new A({code:"plugin_malformed",message:`${n}: 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 a}async function $o(n,r){let a=p(n).plugins??[];if(a.some((d)=>(typeof d==="string"?d:d.spec)===r))return"already";return await ae({file:n,path:["plugins"],value:[...a.map((d)=>typeof d==="string"?d:d.spec),r]}),"written"}async function ko(n){let r=n.rest?.[0];if(r===void 0||r==="")throw new A({code:"cli_plugins_remove_needs_name",message:"plugins remove needs a name",hint:`\`${e.slug} plugins remove <agent> <name>\`, where the name is the \`plugins:\` entry — \`plugins list <agent>\` prints them.`});let a=(p(n.manifestPath).plugins??[]).map((u)=>typeof u==="string"?u:u.spec);if(a.includes(r))await ae({file:n.manifestPath,path:["plugins"],value:a.filter((u)=>u!==r)}),process.stdout.write(`Dropped "${r}" from ${n.manifestPath}.
126
+ Run \`${e.slug} validate ${n.manifestPath}\` — a channel or tool provider it supplied is now unresolved.
127
+ `);else process.stdout.write(`${n.manifestPath} does not name "${r}".
128
+ `);let s=Fn(r,n.env);if(!Ps(s))return process.stdout.write(`Nothing installed at ${s}.
129
+ `),t;let d=So(r,n.manifestPath,n.env);if(d.length>0)return process.stdout.write(`Kept ${s} — still named by ${d.join(", ")}.
130
+ Remove it from those agents first, or delete the directory by hand.
131
+ `),t;return lo(s,{recursive:!0,force:!0}),process.stdout.write(`Deleted ${s}.
132
+ `),t}function So(n,r,o){let a=[];for(let s of R(o)){if(s.manifestPath===r)continue;try{if((p(s.manifestPath).plugins??[]).map((f)=>typeof f==="string"?f:f.spec).includes(n))a.push(s.ref)}catch{}}return a}import{existsSync as Xo,readdirSync as Cs,rmSync as ft,statSync as Ns}from"node:fs";import{homedir as Qo}from"node:os";import{join as js}from"node:path";function Is(n){if(n.filesOnly||n.sharesIdWith.length===0)return[];let r=n.sharesIdWith.join(", ");return[{code:"cli_agent_id_shared",message:`"${n.ref}" has the manifest id "${n.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 ${n.ref} directory and leave the store alone.`}]}function As(n){let r=[];if(n.running!==void 0)r.push({kind:"stop",detail:`stop pid ${n.running.pid} (${n.running.mode}) — gracefully, so anything it left running in the background is reaped`});if(!n.filesOnly&&n.service!==void 0)r.push({kind:"service",detail:`disable and unload ${n.service}`});if(!n.filesOnly){let o=n.footprint;if(r.push({kind:"store",detail:`delete ${ge(o.sessions,"conversation")}, ${ge(o.messages,"message")}, ${ge(o.passages,"memory passage")}`}),n.logs.length>0)r.push({kind:"logs",detail:`delete ${ge(n.logs.length,"log file")}`})}return r.push({kind:"directory",detail:`delete ${n.dir}`}),r}function Ts(n){let r=n.footprint,o=[{label:"directory",value:`${n.dir}`,note:`${ge(n.files.count,"file")}, ${iA(n.files.bytes)}`}];if(n.agentId!==n.ref)o.push({label:"manifest id",value:n.agentId,note:"keys the store, logs and service"});if(n.filesOnly)o.push({label:"keeping",value:`${ge(r.sessions,"conversation")}, ${ge(r.passages,"memory passage")}, and the logs`,note:"--files-only"});else o.push({label:"sessions",value:`${ge(r.sessions,"conversation")}, ${ge(r.messages,"message")}, ${ge(r.turns,"turn")}`},{label:"memory",value:`${ge(r.passages,"passage")} from ${ge(r.memorySources,"source")}`},{label:"outbox",value:r.outbox===0?"nothing queued":`${ge(r.outbox,"delivery")}${r.outboxPending===0?"":`, ${r.outboxPending} not yet sent`}`,...r.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:r.schedules===0?"none":ge(r.schedules,"schedule"),...r.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:n.logs.length===0?"none":`${ge(n.logs.length,"file")}, ${iA(n.logs.reduce((a,s)=>a+s.bytes,0))}`},{label:"service",value:n.service??"not installed"});return o.push({label:"running",value:n.running===void 0?"no":`pid ${n.running.pid} (${n.running.mode})`}),g(o)}function Os(n){if(n.length===0)return"";return n.map((r)=>{let o=r.footprint,a=[];if(o.sessions>0)a.push(`${ge(o.sessions,"conversation")}, ${ge(o.messages,"message")}`);if(o.passages>0)a.push(`${ge(o.passages,"memory passage")}`);if(o.outbox>0)a.push(`${ge(o.outbox,"queued delivery")}`);if(o.schedules>0)a.push(`${ge(o.schedules,"schedule")}`);if(o.lease)a.push("a stale lease");if(r.logs.length>0)a.push(`${ge(r.logs.length,"log file")}, ${iA(r.logs.reduce((s,d)=>s+d.bytes,0))}`);return` ${r.agentId} ${a.length===0?"rows with no detail":a.join(" · ")}`}).join(`
133
+ `)}function ge(n,r){return`${n} ${r}${n===1?"":"s"}`}import{homedir as Eo}from"node:os";var _s=12000,Io=250;async function Rn(n){if(n.manifestPath!==void 0)return await Co(n,n.manifestPath);return await Uo(n)}async function Co(n,r){let o=Bo(r),a=[];if(n.dryRun===!0){let f=await ne(o,n.store);return process.stdout.write(`would stop 1 agent:
134
+ ${l(`${o} — ${f===void 0?"not running; would be switched off for the next start":f.baseUrl===void 0?`pid ${f.pid} (${f.mode}), which serves no HTTP — would be signalled`:`pid ${f.pid} (${f.mode}) at ${f.baseUrl}, which would drop it and keep serving`}`)}
135
+ `),t}await Bn(o,!1,n.reason,n.store),a.push("switched off for the next start");let s=await ne(o,n.store),d=!0;if(s===void 0)a.push("nothing was running");else if(s.baseUrl===void 0){let f=await xn(s.pid,"SIGTERM");d=f||await xn(s.pid,"SIGKILL",!0),a.push(f?`pid ${s.pid} stopped cleanly`:d?`pid ${s.pid} had to be killed`:`pid ${s.pid} would not stop — check it by hand`)}else{let f=await fe(s,`/v1/agents/${encodeURIComponent(o)}/stop`,n.reason===void 0?{}:{reason:n.reason},r);if(f.ok)a.push(`pid ${s.pid} dropped it and kept serving`);else if(f.status===409)d=!1,a.push(f.detail??"a turn is running");else if(f.status===401)d=!1,a.push(`pid ${s.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else d=!1,a.push(`pid ${s.pid} at ${s.baseUrl} could not be reached${f.detail===void 0?"":`: ${f.detail}`}`)}let u={agentId:o,service:!1,...s===void 0?{}:{pid:s.pid,mode:s.mode},stopped:d,note:a.join(" · ")};if(n.json===!0)process.stdout.write(`${JSON.stringify({stopped:[u]},null,2)}
136
+ `);else process.stdout.write(`${g([{label:o,value:d?"stopped":"NOT FULLY STOPPED",note:u.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. \`${e.slug} start ${o}\` switches it back on.
139
+ `);return d?t:i}async function Uo(n){let r=n.platform??process.platform,o=r==="darwin"?PA(r,{home:Eo(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...n.exec===void 0?{}:{exec:n.exec}}):void 0,a=await Mo(o,n.store);if(a.length===0)return process.stdout.write(n.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
+ `),t;if(n.dryRun===!0)return process.stdout.write(`would stop ${a.length} ${a.length===1?"agent":"agents"}:
142
+ ${a.map((d)=>l(qo(d))).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
+ `),t;let s=[];for(let d of a)s.push(await Wo(d,o));if(n.json===!0)process.stdout.write(`${JSON.stringify({stopped:s},null,2)}
145
+ `);else{let d=s.map((u)=>({label:u.agentId,value:u.stopped?"stopped":"STILL RUNNING",note:u.note}));if(process.stdout.write(`${g(d)}
146
+ `),s.some((u)=>u.service&&u.stopped))process.stdout.write(`
228
147
  Services are disabled as well as unloaded, so they stay stopped across a reboot.
229
148
  Start one again with \`${e.slug} daemon start <agent>\`.
230
- `);if(i.some((h)=>h.forced===!0))process.stdout.write(`
149
+ `);if(s.some((u)=>u.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((d)=>d.stopped)?t:i}async function Mo(n,r){let o=`${e.slug}.agent.`,a=new Map;for(let s of n?.labels(o)??[]){let d=s.slice(o.length);a.set(d,{agentId:d,service:!0})}try{let s=await L.open({path:r??Q()});for(let d of await s.leases.all()){if(d.pid===process.pid||!k(d.pid))continue;a.set(d.agentId,{agentId:d.agentId,service:a.get(d.agentId)?.service===!0,pid:d.pid,mode:d.mode})}await s.close()}catch{}return[...a.values()].sort((s,d)=>s.agentId.localeCompare(d.agentId))}async function Wo(n,r){let o=[];if(n.service&&r!==void 0)try{r.stop(In(e.slug,n.agentId)),o.push("service disabled and unloaded")}catch(d){o.push(`service could not be unloaded: ${d instanceof Error?d.message:String(d)}`)}if(n.pid===void 0)return{...n,stopped:!0,note:o.join(" · ")||"no process was running"};if(!k(n.pid))return{...n,stopped:!0,note:o.join(" · ")||`pid ${n.pid} exited`};if(await xn(n.pid,"SIGTERM"))return o.push(`pid ${n.pid} stopped cleanly`),{...n,stopped:!0,note:o.join(" · ")};let s=await xn(n.pid,"SIGKILL",!0);return o.push(s?`pid ${n.pid} did not stop in ${Math.round(_s/1000)}s and was killed`:`pid ${n.pid} would not stop, even killed — check it by hand`),{...n,stopped:s,forced:!0,note:o.join(" · ")}}async function xn(n,r,o=!1){try{process.kill(o?-n:n,r)}catch(s){if(s.code==="ESRCH")return!0;if(o)try{process.kill(n,r)}catch{return!k(n)}}let a=Date.now()+(r==="SIGKILL"?3000:_s);while(Date.now()<a){if(!k(n))return!0;await new Promise((s)=>setTimeout(s,Io))}return!k(n)}function qo(n){let r=[];if(n.service)r.push("background service");if(n.pid!==void 0)r.push(`pid ${n.pid}${n.mode===void 0?"":` (${n.mode})`}`);return`${n.agentId} — ${r.join(", ")}`}function Bo(n){let r=p(n);if(r.id===void 0||r.id==="")throw new A({code:"cli_stop_agent_id_missing",message:`${n} 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 r.id}async function Fs(n){let r=await L.open({path:n.store??Q()});try{if(n.prune===!0)return await ni(n,r);if(n.all===!0)return await ei(n,r);if(n.ref===void 0)throw new A({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 Zo(n.ref,n,r)}finally{await r.close()}}async function Zo(n,r,o){let a=await Ls(n,r,o),s=Is(a);if(s.length>0){let f=s[0];throw new A({code:f.code,message:f.message,hint:f.hint})}let d=As(a),u=`${B(`removing ${n} will:`,!0)}
154
+ ${Ts(a)}
236
155
 
237
- ${f.map((g)=>d(g.detail)).join(`
156
+ ${d.map((f)=>l(f.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:n,agentId:a.agentId,steps:d,footprint:a.footprint},null,2)}
159
+ `:`${u}
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
+ `),t;if(process.stdout.write(u),!await mt(r,n,"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.
163
+ `),t;return await Ks(a,r,o)}async function Ks(n,r,o){let a=[];if(n.running!==void 0||!n.filesOnly&&n.service!==void 0){if(await Rn({manifestPath:n.manifestPath,...r.exec===void 0?{}:{exec:r.exec},...r.platform===void 0?{}:{platform:r.platform}})!==t)return process.stderr.write(`
164
+ Stopping ${n.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
246
165
  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)}
248
- `),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(`
166
+ `),i;a.push({label:"stopped",value:n.ref})}if(!n.filesOnly&&n.service!==void 0){let s=Us(r);try{s?.uninstall(n.service),a.push({label:"service",value:`${n.service} removed`})}catch(d){a.push({label:"service",value:`${n.service} could NOT be removed`,note:d instanceof Error?d.message:String(d)})}}if(!n.filesOnly){let s=await o.purgeAgent(n.agentId);a.push({label:"store",value:`${s.sessions} conversation(s), ${s.messages} message(s), ${s.passages} passage(s)`});for(let d of n.logs)ft(d.path,{force:!0});if(n.logs.length>0)a.push({label:"logs",value:`${n.logs.length} file(s)`})}if(ft(n.dir,{recursive:!0,force:!0}),a.push({label:"directory",value:n.dir}),r.json===!0)return process.stdout.write(`${JSON.stringify({removed:n.ref,agentId:n.agentId,filesOnly:n.filesOnly},null,2)}
167
+ `),t;if(process.stdout.write(`
168
+ ${n.ref} removed.
169
+ ${g(a)}
170
+ `),n.filesOnly)process.stdout.write(`
171
+ Its sessions and memory are still in the store under the id "${n.agentId}", which another agent shares.
172
+ `);return t}async function ei(n,r){let o=R();if(o.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
173
+ `),t;if(process.stdout.write(`${B(`removing every agent in ${_()}:`,!0)}
174
+ ${o.map((s)=>l(`${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
+ `),n.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
+ `),t;if(!await mt(n,"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
+ `),t;let a=t;for(let s of o){let d=await Ls(s.ref,n,r),u=await Ks({...d,sharesIdWith:[]},n,r);if(u!==t)a=u}return a}async function ni(n,r){let o=new Set(R().map((u)=>u.id??u.ref).filter((u)=>u!=="")),a=new Set((await r.agentIds()).filter((u)=>!o.has(u)));for(let u of ri())if(!o.has(u))a.add(u);let s=[];for(let u of[...a].sort())s.push({agentId:u,footprint:await r.agentFootprint(u),logs:Ms(u)});if(s.length===0)return process.stdout.write(n.json===!0?`${JSON.stringify({pruned:[]})}
181
+ `:`Nothing to prune — every agent id in the store and the log directory belongs to an agent in ${_()}.
182
+ `),t;if(process.stdout.write(`${B("no sandbox directory claims these:",!0)}
183
+ ${Os(s)}
184
+ `),n.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
+ `),t;if(!await mt(n,"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
+ `),t;let d=[];for(let u of s){let f=await r.purgeAgent(u.agentId);for(let y of u.logs)ft(y.path,{force:!0});d.push({label:u.agentId,value:`${f.sessions} conversation(s), ${f.passages} passage(s), ${u.logs.length} log file(s)`})}return process.stdout.write(n.json===!0?`${JSON.stringify({pruned:s.map((u)=>u.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
+ ${g(d)}
192
+ `),t}async function Ls(n,r,o){if(n.includes("/")||n.endsWith(".yaml")||n.endsWith(".yml"))throw new A({code:"cli_remove_takes_a_name",message:`remove takes a sandbox agent's name, and "${n}" is a path.`,hint:`An agent outside ${_()} 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 a=R(),s=a.find((E)=>E.ref===n);if(s===void 0){let E=a.map((j)=>j.ref);throw new A({code:"cli_agent_unknown",message:`No agent named "${n}" in the sandbox${E.length===0?", which is empty":""}.`,hint:E.length===0?`Nothing to remove. \`${e.slug} init\` creates one.`:`Known agents: ${E.join(", ")}. \`--prune\` clears data left by an agent whose directory is already gone.`})}let d=s.id;if(d===void 0)try{d=p(s.manifestPath).id}catch{}let u=r.filesOnly===!0||d===void 0,f=d??n,y=await o.agentFootprint(f),x=y.lease?await o.leases.get(f):void 0,m=Us(r),w=In(e.slug,f);return{ref:n,agentId:f,manifestPath:s.manifestPath,dir:s.dir,files:ti(s.dir),footprint:y,logs:Ms(f),sharesIdWith:a.filter((E)=>E.ref!==n&&(E.id??"")===f).map((E)=>E.ref),...x!==void 0&&k(x.pid)?{running:{pid:x.pid,mode:x.mode}}:{},...m?.state(w).installed===!0?{service:w}:{},filesOnly:u}}function Us(n){let r=n.platform??process.platform;if(r!=="darwin")return;return PA(r,{home:Qo(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...n.exec===void 0?{}:{exec:n.exec}})}function ti(n){let r=0,o=0,a=(s)=>{let d;try{d=Cs(s)}catch{return}for(let u of d){let f=js(s,u);try{let y=Ns(f);if(y.isDirectory()){a(f);continue}r+=1,o+=y.size}catch{}}};return a(n),{count:r,bytes:o}}function Ms(n){let r=_A(n),o=[];for(let a of[r.out,r.err])try{if(!Xo(a))continue;o.push({path:a,bytes:Ns(a).size})}catch{}return o}function ri(){let n;try{n=Cs(js(z(),"logs"))}catch{return[]}let r=new Set;for(let o of n)for(let a of[".out.log",".err.log"])if(o.endsWith(a))r.add(o.slice(0,-a.length));return[...r]}async function mt(n,r,o){if(n.yes===!0)return!0;let a=n.confirm;if(a===void 0)return!1;return await a(o,r)}async function Ds(n){if(n.manifestPath===void 0)return await ke({action:"restart",...n.store===void 0?{}:{store:n.store},...n.json===void 0?{}:{json:n.json}});let r=H(n.manifestPath),o=await st(n.manifestPath,n.store),a,s,d=t;switch(o.kind){case"reloaded":a="reloaded",s=`pid ${o.pid} rebuilt it from disk${o.adopted.length>0?` · adopted ${o.adopted.join(", ")}`:""}`;break;case"busy":a="not reloaded",s=`pid ${o.pid} has a turn in flight — try again when it finishes`,d=i;break;case"failed":a="not reloaded",s=`pid ${o.pid} answered ${o.status}${o.detail===void 0?"":`: ${o.detail}`}${o.hint===void 0?"":` — ${o.hint}`}`,d=i;break;case"no-host":{let u=await oe(n.store);if(u===void 0)throw new A({code:"cli_restart_nothing_running",message:`Nothing is hosting ${r}, and no server is running to adopt it.`,hint:`\`${e.slug} serve ${r}\` runs it in this terminal; \`${e.slug} daemon install\` keeps a server running that hosts every agent. Then \`${e.slug} restart ${r}\` reloads it in place.`});let f=await dA(u,n.manifestPath,n.store);if(f.ok)a="started",s=`nothing was hosting it — adopted by pid ${u.pid}`;else a="not started",s=`pid ${u.pid} did not adopt it${f.detail===void 0?"":`: ${f.detail}`}`,d=i;break}}if(n.json===!0)process.stdout.write(`${JSON.stringify({agentId:r,result:o,ok:d===t},null,2)}
193
+ `);else process.stdout.write(`${g([{label:r,value:a,note:s}])}
194
+ `);return d}import{randomBytes as yt}from"node:crypto";import{existsSync as mi}from"node:fs";import{createInterface as Xs}from"node:readline";class He extends Error{code;hint;field;status;request;constructor(n,r={}){super(n.hint===void 0?n.message:`${n.message}
195
+ hint: ${n.hint}`);if(this.name="DispachError",this.code=n.code,this.hint=n.hint??"",this.field=n.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 oi(n,r){let o=n instanceof Error?n.message:String(n);return new He({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:n})}async function ii(n,r){let o;try{let a=await n.json();if(typeof a.error?.code==="string"&&typeof a.error.message==="string")o={code:a.error.code,message:a.error.message,...a.error.hint===void 0?{}:{hint:a.error.hint},...a.error.field===void 0?{}:{field:a.error.field}}}catch{}return new He(o??{code:`http_${n.status}`,message:`${r.method} ${r.path} returned ${n.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:n.status,...r})}var Hs=new Set(_e);async function*Ws(n){for await(let r of bn(ai(n))){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*ai(n){let r=n.getReader();try{while(!0){let{done:o,value:a}=await r.read();if(o)return;if(a!==void 0)yield a}}finally{r.releaseLock()}}async function*di(n){for await(let{name:r,data:o}of Ws(n)){if(Hs.has(r)){yield{kind:"event",event:o};continue}let a=o??{};switch(r){case"turn.accepted":yield{kind:"accepted",turnId:String(a.turnId??""),sessionKey:String(a.sessionKey??"")};break;case"stream.replay":yield{kind:"replay",report:{state:a.state==="ended"?"ended":"running",events:Number(a.events??0),truncated:a.truncated===!0,dropped:Number(a.dropped??0),chunks:a.chunks==="start"||a.chunks==="partial"?a.chunks:"none"}};break;case"stream.ended":yield{kind:"ended",turnId:String(a.turnId??""),status:String(a.status??"unknown"),steps:typeof a.steps==="number"?a.steps:void 0,errorCode:typeof a.errorCode==="string"?a.errorCode:void 0};break;case"stream.unavailable":yield{kind:"unavailable",turnId:String(a.turnId??""),reason:String(a.reason??"not observable from this process")};break;default:break}}}async function*ci(n){for await(let{name:r,data:o}of Ws(n)){if(Hs.has(r)){yield{kind:"event",event:o};continue}if(r==="stream.subscribed"){let a=o??{};yield{kind:"subscribed",report:{agentId:typeof a.agentId==="string"?a.agentId:null,types:Array.isArray(a.types)?a.types:null,chunks:a.chunks===!0,implied:typeof a.implied==="string"?a.implied:void 0}}}}}async function*ui(n,r={}){for await(let o of n){if(o.kind==="replay"&&o.report.truncated&&r.allowTruncated!==!0)throw new He({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 He({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 a=o.event.data;if(a.kind==="reasoning")continue;if(typeof a.delta==="string")yield a.delta}}function qs(n){let r=n.baseUrl.replace(/\/+$/,""),o=n.fetch??fetch,a=(x={})=>({...n.token===void 0?{}:{authorization:`Bearer ${n.token}`},...x});async function s(x,m,w={}){let E;try{E=await o(`${r}${m}`,{method:x,headers:a({...w.body===void 0?{}:{"content-type":"application/json"},...w.accept===void 0?{}:{accept:w.accept},...w.headers}),...w.body===void 0?{}:{body:JSON.stringify(w.body)},...w.signal===void 0?{}:{signal:w.signal}})}catch(j){throw oi(j,{method:x,path:m,baseUrl:r})}if(!E.ok)throw await ii(E,{method:x,path:m});return E}async function d(x,m,w){return await(await s(x,m,w??{})).json()}async function u(x,m){let w=await s("GET",x,{accept:"text/event-stream",...m===void 0?{}:{signal:m}});if(w.body===null)throw new He({code:"no_response_body",message:`GET ${x} returned ${w.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:w.status,method:"GET",path:x});return w.body}function f(x,m,w,E={}){let j=(I)=>I?.chunks===!0?"?chunks=true":"",W={turnId:m,sessionKey:w,replayed:E.replayed===!0,async*stream(I){let T=await u(`/v1/agents/${encodeURIComponent(x)}/turns/${encodeURIComponent(m)}/stream${j(I)}`,I?.signal);yield*di(T)},async*tokens(I){yield*ui(W.stream({chunks:!0,...I}),{...I?.allowTruncated===void 0?{}:{allowTruncated:I.allowTruncated}})},async text(){for await(let I of W.stream()){if(I.kind==="ended")break;if(I.kind==="unavailable")break;if(I.kind==="event"&&I.event.type==="turn.end")break}return(await W.get()).text},get:()=>d("GET",`/v1/agents/${encodeURIComponent(x)}/turns/${encodeURIComponent(m)}`),async stop(){await s("POST",`/v1/agents/${encodeURIComponent(x)}/turns/${encodeURIComponent(m)}/stop`)}};return W}function y(x){let m=(w)=>`/v1/agents/${encodeURIComponent(x)}${w}`;return{id:x,async send(w,E){let j=await d("POST",m("/messages"),{body:{text:w,...E?.sessionKey===void 0?{}:{sessionKey:E.sessionKey},...E?.deliver===void 0?{}:{deliver:E.deliver},...E?.from===void 0?{}:{from:E.from}},...E?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":E.idempotencyKey}},...E?.signal===void 0?{}:{signal:E.signal}});return f(x,j.turnId,j.sessionKey,{replayed:j.replayed===!0})},turn:(w)=>f(x,w,""),describe:()=>d("GET",m("")),tools:()=>d("GET",m("/tools")),skills:()=>d("GET",m("/skills")),sessions:()=>d("GET",m("/sessions")),messages:(w,E)=>{let j=new URLSearchParams;if(E?.before!==void 0)j.set("before",String(E.before));if(E?.limit!==void 0)j.set("limit",String(E.limit));let W=j.size===0?"":`?${j.toString()}`;return d("GET",m(`/sessions/${encodeURIComponent(w)}/messages${W}`))},clearSession:(w)=>d("DELETE",m(`/sessions/${encodeURIComponent(w)}`)),reload:()=>d("POST",m("/reload"),{body:{}}),schedules:async()=>(await d("GET",m("/schedules"))).schedules,approvals:async()=>(await d("GET",m("/approvals"))).approvals,createSchedule:(w)=>d("POST",m("/schedules"),{body:w}),updateSchedule:(w,E)=>d("PATCH",m(`/schedules/${encodeURIComponent(w)}`),{body:E}),deleteSchedule:async(w)=>{await d("DELETE",m(`/schedules/${encodeURIComponent(w)}`))},runSchedule:(w)=>d("POST",m(`/schedules/${encodeURIComponent(w)}/run`),{body:{}}),config:()=>d("GET",m("/config")),setConfig:(w,E,j)=>d("PATCH",m("/config"),{body:{path:w,value:E,...j?.confirm===void 0?{}:{confirm:j.confirm}}}),setChannel:(w,E)=>d("PATCH",m(`/channels/${encodeURIComponent(w)}`),{body:{...E}}),unpairChannel:(w)=>d("POST",m(`/channels/${encodeURIComponent(w)}/unpair`)),session:(w)=>d("GET",m(`/sessions/${encodeURIComponent(w)}`)),setPhase:(w,E)=>d("POST",m(`/sessions/${encodeURIComponent(w)}/phase`),{body:{phase:E}}),approve:async(w,E)=>{await d("POST",m(`/approvals/${encodeURIComponent(w)}`),{body:{granted:E}})},stop:(w)=>d("POST",m("/stop"),{body:w===void 0?{}:{reason:w}}),start:()=>d("POST",m("/start"),{body:{}}),context:(w)=>{let E=new URLSearchParams;if(w?.sessionKey!==void 0)E.set("sessionKey",w.sessionKey);if(w?.input!==void 0)E.set("input",w.input);let j=E.size===0?"":`?${E.toString()}`;return d("GET",m(`/context${j}`))}}}return{agent:y,agents:()=>d("GET","/v1/agents"),health:()=>d("GET","/v1/health"),async ready(){try{return await s("GET","/v1/ready"),!0}catch(x){if(x instanceof He&&x.status===503)return!1;throw x}},provision:()=>d("GET","/v1/provision"),keys:()=>d("GET","/v1/keys"),createKey:(x)=>d("POST","/v1/keys",{body:x}),revokeKey:(x)=>d("DELETE",`/v1/keys/${encodeURIComponent(x)}`),createAgent:(x)=>d("POST","/v1/agents",{body:{answers:x}}),async*events(x){let m=new URLSearchParams;if(x?.agentId!==void 0)m.set("agentId",x.agentId);if(x?.types!==void 0&&x.types.length>0)m.set("types",x.types.join(","));if(x?.chunks===!0)m.set("chunks","true");let w=m.size===0?"":`?${m.toString()}`,E=await u(`/v1/events${w}`,x?.signal);yield*ci(E)}}}function tn(n,r){let o=[];for(let a of n){if(a.origin!==void 0&&a.origin!=="call")continue;if(a.role!=="user"&&a.role!=="assistant")continue;let s=go(a,r);if(s==="")continue;o.push({role:a.role,text:s})}return o}function Gs(n){let r=n.ref??"<your agent>",o=`${e.slug} run ${r} --session ${n.sessionKey}`;return`
196
+ ${vi}Resume this session with:
197
+ ${o}${Xt}
198
+ `}function ht(n,r){switch(n){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 fi(n){return n==="nlt"?Mn():Sn()}function Bs(n){return{kind:"embedded",agentId:n.agent.id,describe:()=>n.description,subscribe:(r)=>n.bus.on("*",r,{chunks:!0}),send:(r,o)=>n.send(r,{...o,source:"repl"}),streamFilter:n.streamFilter,history:n.history,sessions:n.sessions,clearSession:n.clearSession,tools:async()=>cn(n.agent),context:n.context,close:async()=>{}}}function Vs(n){let r=n.client.agent(n.agentId),o=new Set,a=new AbortController,s,d=()=>{if(s!==void 0)return;s=(async()=>{for await(let u of n.client.events({agentId:n.agentId,chunks:!0,signal:a.signal})){if(u.kind!=="event"||u.event===void 0)continue;for(let f of o)f(u.event)}})().catch(()=>{})};return{kind:"attached",agentId:n.agentId,host:n.host,describe:()=>n.description,subscribe:(u)=>(o.add(u),d(),()=>o.delete(u)),send:async(u,f)=>{let y=!1,x,m=()=>{if(y=!0,x!==void 0)r.turn(x).stop().catch(()=>{})};f.signal.addEventListener("abort",m,{once:!0});let w,E=new Promise((j)=>{let W=(I)=>{if(x!==void 0&&I.turnId!==void 0&&I.turnId!==x)return;if(I.type==="error"){w=I.data;return}if(I.type!=="turn.end")return;o.delete(W),j({text:"",reason:I.data.reason,steps:I.data.steps,durationMs:I.data.durationMs,tokens:I.data.tokens,...w===void 0?{}:{error:w}})};o.add(W),d()});try{if(x=(await r.send(u,{sessionKey:f.sessionKey})).turnId,y)r.turn(x).stop().catch(()=>{});return await E}finally{f.signal.removeEventListener("abort",m)}},streamFilter:()=>fi(n.description.dialect),history:async(u)=>{let f=await r.messages(u);return tn([...f.messages].reverse().map((y)=>({role:y.role,content:y.content,...y.origin===void 0?{}:{origin:y.origin}})),n.description.dialect)},sessions:()=>r.sessions(),clearSession:async(u)=>{await r.clearSession(u)},tools:async()=>{let u=await r.tools();return{dialect:n.description.dialect,catalogueTokens:n.description.catalogueTokens,tools:u.map((f)=>({slug:f.slug,mutating:f.mutating,trust:f.trust,...f.trustReason===void 0?{}:{trustReason:f.trustReason},summary:f.summary}))}},context:async(u)=>{let f=await r.context({sessionKey:u});return{...f,windowSource:"as the host resolved it",...f.lastCompaction===void 0&&f.compactions!==void 0?{lastCompaction:f.compactions===0?void 0:`${f.compactions} stage${f.compactions===1?"":"s"} run this session`}:{}}},reload:async()=>(await r.reload()).adopted,close:async()=>{a.abort(),o.clear()}}}function Js(n){if(n?.baseUrl===void 0||n.baseUrl==="")return;return{baseUrl:n.baseUrl,pid:n.pid}}async function pi(n,r,o,a,s,d=[],u){let f=n.describe(),[y,x]=await Promise.all([n.turns(r,1),n.store.messages.count(n.id,r)]),m=[`${e.name} ${M} · ${f.id} · ${f.model}`,`session ${r} · ${x} message(s) · window ${f.window} · store ${o}`,`ready in ${a.toFixed(0)} ms · /help for commands and keys · /exit to leave`],w=ht(s,u);if(w!==void 0)m.push(w);if(y[0]?.errorCode==="turn_abandoned")m.push("note: the previous turn in this session did not finish — the process exited while it was generating.");for(let E of[...n.warnings,...n.tools.warnings])m.push(`note: ${E.message}
199
+ ${E.hint}`);if(d.length>0)m.push(`note: ${d.join(", ")} in the .env here ${d.length===1?"was":"were"} ignored — this agent's own .env sets ${d.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 m}async function wt(n){let r=n.once!==void 0,o=ue({json:!1,plain:n.plain===!0,oneShot:r}),{mode:a}=o;if(n.manifestPath===void 0){let I=await yi(a,o.because,n);if(typeof I==="number")return I;return wt({...n,manifestPath:I})}let s=so();if(n.store===void 0&&n.ephemeral!==!0&&mi(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 ${Q()}
201
+ `);let d;h(()=>d?.stop("cli-exit"));let u={current:void 0},f={current:""},y={current:n.sessionKey},x={current:!1},m={current:void 0},w=n.quiet===!0,E="first",j={current:void 0},W=n.ephemeral===!0?void 0:Js(await ne(H(n.manifestPath),n.store));if(W!==void 0)return await Si({...n,host:W,mode:a==="rich"?"rich":"plain",quiet:w,oneShot:r,reader:u,draft:f,session:y,random:yt});for(;;){let I=await U.create({agents:[n.manifestPath],toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C([n.manifestPath]),store:n.ephemeral===!0?":memory:":n.store??Q()});d=I;let T=I.list()[0];if(T===void 0)throw Error("The manifest produced no agent.");if(y.current===void 0||y.current===""){let ce=await zs({list:()=>te.sessions(),mode:a,asked:y.current,wantsContinue:n.continueSession===!0,random:yt});if(typeof ce==="number")return await I.stop("cli-exit"),ce;y.current=ce.sessionKey,x.current=ce.fresh}let de=y.current,K=T.roles.main.capabilities.thinking!=="none",re=n.noReasoning===!0?!1:K,G=w||r?[]:await pi(T,de,I.store.location,E==="first"?I.boot.processMs:I.boot.bootMs,E,li([n.manifestPath]),m.current),ee=a==="rich"&&!w&&!r?tn(await T.history(de),T.describe().dialect):[],te=Bs({agent:T,bus:I.bus,send:(ce,Ce)=>T.send(ce,Ce),history:async(ce)=>tn(await T.history(ce),T.describe().dialect),sessions:async()=>await T.store.sessions.list(T.id),clearSession:async(ce)=>{await T.clearSession(ce)},context:async(ce)=>xi(T,ce),streamFilter:()=>T.streamFilter(),description:{agentId:T.id,name:T.describe().name,model:T.describe().model,dialect:T.describe().dialect,window:T.describe().window,catalogueTokens:T.describe().catalogueTokens,thinking:T.roles.main.capabilities.thinking,warnings:[...T.warnings,...T.tools.warnings]}}),se={...n,source:te,embedded:{agent:T,runtime:I},sessionKey:de,banner:G,prior:ee,quiet:w,reader:u,draft:f,showReasoning:re,freshSession:x.current,switchTo:j,random:yt},be=a==="rich"?await Qs(se):await Ys(se);if(await I.stop(be===qe?"restart":"cli-exit"),be!==qe)return be;if(j.current===void 0)E="restart";else E=j.current.reason,m.current=de,y.current=j.current.key,j.current=void 0;x.current=!1}}function gi(n,r){let o=[];for(let a of n)Re({action:"install",manifestPath:r,name:`${a.source}/${a.skill}`,quiet:!0,collect:o});return o}var qe=Symbol("restart");async function yi(n,r,o){let a=R();if(a.length===0){if(n==="rich"){let m=await Wn({plain:o.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
202
+ `),t;if(m.kind==="failed")return m.code;return m.manifestPath}throw new A({code:"cli_sandbox_empty",message:"No agent named, and the sandbox is empty.",hint:`Create one with \`${e.slug} init\`, or pass a path to an agent.yaml.`})}if(a.length===1&&a[0]!==void 0)return process.stdout.write(`running ${a[0].ref} — the only agent in the sandbox
203
+ `),a[0].manifestPath;if(n!=="rich"){for(let m of a)process.stdout.write(`${m.ref} ${m.problem??m.modelId??"?"} ${m.dir}
204
+ `);return process.stderr.write(`pass an agent name or a manifest path — the picker needs a terminal (${r})
205
+ `),i}let[{render:s},{createElement:d},{Picker:u}]=await Promise.all([import("ink"),import("react"),import("./Picker-b7mn0mjg.js")]),f={kind:"quit"};Qt();let y=s(d(u,{title:`${e.name} ${M}`,agents:a,onDone:(m)=>{f=m}}),{exitOnCtrlC:!1,...X(o.noEnhancedKeys)});h(()=>y.unmount()),await y.waitUntilExit(),y.unmount();let x=f;if(x.kind==="quit")return process.stdout.write(`nothing run
206
+ `),t;if(x.kind==="create"){let m=await Wn({plain:o.plain===!0});if(m.kind==="aborted")return process.stdout.write(`nothing to run
207
+ `),t;if(m.kind==="failed")return m.code;return m.manifestPath}return x.manifestPath}async function zs(n){let r=()=>({sessionKey:Pn(n.random),fresh:!0});if(n.wantsContinue&&n.asked==="")throw new A({code:"cli_session_ambiguous",message:"--continue and a bare --session ask for different things.",hint:"--continue takes the most recent conversation without asking; --session on its own opens the list. Pass one."});if(n.wantsContinue){let o=await n.list(),a=bi(o);if(a===void 0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
208
+ `),r();return{sessionKey:a.sessionKey,fresh:!1}}if(n.asked===""){let o=await n.list();if(o.length===0)return process.stdout.write(`no stored conversation with this agent yet — starting a new one
209
+ `),r();if(n.mode!=="rich"){for(let s of[...o].sort(Tn))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
+ `),i}let a=await $i([...o].sort(Tn));return a===void 0?r():{sessionKey:a,fresh:!1}}return n.asked===void 0?r():{sessionKey:n.asked,fresh:!1}}function Tn(n,r){return Date.parse(r.lastActivityAt)-Date.parse(n.lastActivityAt)}function bi(n){return[...n].sort(Tn)[0]}async function $i(n){let[{render:r},{createElement:o},{SessionPicker:a}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-vacfwczg.js")]),s;Qt();let d=r(o(a,{sessions:n.map((u)=>({sessionKey:u.sessionKey,messages:u.messages,turns:u.turns,lastActivityAt:u.lastActivityAt,phase:u.phase})),now:Date.now(),columns:V(process.stdout.columns,J),maxRows:At,onDone:(u)=>{s=u,d.unmount()}}),{exitOnCtrlC:!1,...X()});return h(()=>d.unmount()),await d.waitUntilExit(),s}function ki(n,r,o,a,s){let d=n.describe(),u=[`${e.name} ${M} · ${d.agentId} · ${d.model}`,`session ${r} · window ${d.window} · attached to ${o.baseUrl} (pid ${o.pid})`,"a view — the agent keeps running when you leave · /help for commands · /exit to detach"],f=ht(a,s);if(f!==void 0)u.push(f);for(let y of d.warnings)u.push(`warning: ${y.message}`);return u}async function Si(n){let r=n.manifestPath??"",o=H(r),a=fA(r),s=qs({baseUrl:n.host.baseUrl,...a===void 0?{}:{token:a}}),d=await s.agent(o).describe(),u=Vs({client:s,agentId:o,host:n.host,description:{agentId:o,name:d.name,model:d.model??"unknown",dialect:d.dialect??"nlt",window:d.window??0,catalogueTokens:d.catalogueTokens??0,thinking:"unknown",warnings:d.warnings??[]}}),f={current:void 0},y="first",x={current:void 0},m={current:!1};for(;;){if(n.session.current===void 0||n.session.current===""){let T=await zs({list:()=>u.sessions(),mode:n.mode,asked:n.session.current,wantsContinue:n.continueSession===!0,random:n.random});if(typeof T==="number")return T;n.session.current=T.sessionKey,m.current=T.fresh}let w=n.session.current??"",E=n.quiet||n.oneShot?[]:ki(u,w,n.host,y,x.current),j=n.mode==="rich"&&!n.quiet&&!n.oneShot?await u.history(w):[],W={...n,source:u,sessionKey:w,banner:E,prior:j,quiet:n.quiet,reader:n.reader,draft:n.draft,showReasoning:n.noReasoning!==!0,freshSession:m.current,switchTo:f,random:n.random},I=n.mode==="rich"?await Qs(W):await Ys(W);if(I!==qe)return await u.close(),I;if(f.current===void 0)y="restart";else y=f.current.reason,x.current=w,n.session.current=f.current.key,f.current=void 0;m.current=!1}}async function Qs(n){let[{render:r},{createElement:o},{App:a}]=await Promise.all([import("ink"),import("react"),import("./App-qfqvx9c7.js")]),s=ln();h(()=>{s.close()}),he(),_o(),process.stdout.write(`${Me}${Di}`);let d=!1,u=r(o(a,{source:n.source,onSwitch:(f,y)=>{d=!0,n.switchTo.current={key:f,reason:"switch"},n.draft.current=y},onNew:(f)=>{d=!0,n.switchTo.current={key:Pn(n.random),reason:"new"},n.draft.current=f},sessions:async()=>[...await n.source.sessions()].sort(Tn).map((y)=>({sessionKey:y.sessionKey,messages:y.messages,turns:y.turns,lastActivityAt:y.lastActivityAt,phase:y.phase})),onRestart:(f)=>{d=!0,n.draft.current=f},sessionKey:n.sessionKey,model:n.source.describe().model,agentName:n.source.describe().agentId,freshSession:n.freshSession,warnings:n.source.describe().warnings.map((f)=>f.message),initial:bo(Do(n.banner.slice(1)),n.prior),correctKeys:s.correct,showReasoning:n.showReasoning,quiet:n.quiet,...n.manifestPath===void 0?{}:{manifestPath:n.manifestPath},catalogue:{load:(f)=>yA({onStatus:f}),install:async(f,y)=>WA(gi(f,y))},status:()=>n.embedded===void 0?er(n.source):Zs(n.embedded),contextView:()=>nr(n,n.sessionKey),...n.draft.current===""?{}:{initialDraft:n.draft.current}}),{exitOnCtrlC:!1,...X(n.noEnhancedKeys)});if(h(()=>u.unmount()),await u.waitUntilExit(),ie(),!d)process.stdout.write(Gs({ref:n.source.describe().agentId,sessionKey:n.sessionKey}));return d?qe:t}async function Ys(n){let{source:r,sessionKey:o,quiet:a}=n,s=!0,d=(G)=>{if(G==="")return;process.stdout.write(G),s=G.endsWith(`
212
+ `)},u=(G)=>{if(!s)d(`
213
+ `);d(`${G}
214
+ `)};if(n.banner.length>0)d(`${n.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 f=!a&&n.once===void 0,y=!1,x,m=r.streamFilter(),w=(G)=>{if(G==="")return;d(G),y=!0},E=n.source.subscribe((G)=>{switch(G.type){case"model.result":w(m.endStep());return;case"model.chunk":{let{delta:ee,kind:te}=G.data;if(te==="reasoning"&&n.showReasoning!==!0)return;if(te!==x){if(x!==void 0)d(`
297
218
 
298
- `);if(r.showReasoning===!0)f(Q==="reasoning"?`· reasoning ·
219
+ `);if(n.showReasoning===!0)d(te==="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
+ `);x=te}if(te==="reasoning"){d(ee),y=!0;return}w(m.push(ee));return}case"tool.result":{if(!f)return;let{slug:ee,ok:te,latencyMs:se,truncated:be}=G.data;u(` · ${ee} — ${te?"ok":"failed"} · ${se} ms${be?" · observation trimmed":""}`);return}case"agent.warning":u(` · ${G.data.message}
222
+ ${G.data.hint}`);return;case"tool.repair":if(f)u(` · ${G.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":u(` · ${G.data.slug} — blocked: ${G.data.reason}`);return;case"context.dropped":u(` · context: ${G.data.messages} older message(s) did not fit the ${G.data.budget}-token budget and were left out`);return;default:return}}),j=async(G)=>{let ee=nt(G,it());if(ee===void 0)return"prompt";switch(ee.kind){case"exit":return"exit";case"restart":{let te=r.reload;if(te===void 0)return"restart";try{let se=await te();u(`reloaded ${se.join(", ")} — this conversation continues`)}catch(se){u(`could not reload: ${se instanceof Error?se.message:String(se)}`)}return"handled"}case"new":return n.switchTo.current={key:Pn(n.random),reason:"new"},"restart";case"help":return u(ot()),"handled";case"tools":return u(IA(await r.tools())),"handled";case"status":return u(n.embedded===void 0?await er(r):await Zs(n.embedded)),"handled";case"context":return u(await nr(n,o)),"handled";case"reset":return await r.clearSession(o),u("session cleared — memory files on disk are untouched"),"handled";case"unknown":return u(TA(ee)),"handled";case"command":return u(`${ee.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${e.slug} ${ee.name}${ee.rest===""?"":` ${ee.rest}`}\``),"handled"}},W,I=0,T=t,de=(G=n.reader.current)=>{if(W!==void 0&&!W.signal.aborted){I=performance.now(),W.abort();return}G?.close(),d(`
223
+ `)},K=async(G)=>{W=new AbortController,y=!1,x=void 0,m=r.streamFilter();let ee=await r.send(G,{sessionKey:o,signal:W.signal});if(W=void 0,w(m.end()),y&&!s)d(`
224
+ `);else if(!y&&ee.text!=="")d(`${ee.text}
225
+ `);let te=$e(ee.reason,{steps:ee.steps,durationMs:ee.durationMs,...I===0?{}:{cancelledAfterMs:performance.now()-I}});if(te!==void 0)d(`
226
+ (${te})
227
+ `);if(ee.reason==="error"&&ee.error!==void 0)process.stderr.write(`
228
+ ${ee.error.code}: ${ee.error.message}
229
+ hint: ${ee.error.hint}
230
+ `);if(no(ee.reason))T=i;if(!a&&ee.reason==="final")d(` ${ee.tokens.prompt} prompt · ${ee.tokens.output} output · ${ee.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 pe()},re=()=>de();process.on("SIGINT",re);try{if(n.once!==void 0)return await K(n.once),T;if(process.stdin.isTTY!==!0){let ee=n.reader.current??Xs({input:process.stdin});n.reader.current=ee;for await(let te of ee){let se=te.trim();if(se==="")continue;let be=await j(se);if(be==="exit")break;if(be==="restart"){T=qe;break}if(be==="handled")continue;await K(se)}return T}let G=n.reader.current??Xs({input:process.stdin,output:process.stdout,prompt:An,terminal:!1});n.reader.current=G,G.prompt();for await(let ee of G){let te=ee.trim();if(te===""){G.prompt();continue}let se=await j(te);if(se==="exit")break;if(se==="restart"){T=qe;break}if(se==="handled"){G.prompt();continue}await K(te),G.prompt()}if(T!==qe)G.close(),n.reader.current=void 0;return T}finally{process.off("SIGINT",re),E()}}async function Zs(n){let{agent:r,runtime:o}=n,a=r.describe(),s=r.manifest,d=s.channels.filter((m)=>m.enabled).map((m)=>`${m.id} (${m.type})`).join(", "),u=d===""?"none — reached through this session and the HTTP API only":o.channels.started?`${d} — connected in this session`:`${d} — configured, NOT running here; \`serve\` starts channels, \`run\` does not`,f=!s.server.enabled?"off":`enabled on ${s.server.host}:${s.server.port}, NOT bound here — \`serve\` binds it`,y=me(s),x=y.filter((m)=>m.role!=="main"&&m.role===m.configuredAs);return g([{label:"agent",value:`${a.id} (${a.name})`},{label:"model",value:`${a.model} · ${s.tools.dialect} · ${a.window} token window (${Xe(y[0]?.window)})`},...x.map((m)=>({label:m.role,value:`${m.modelId} · ${m.window.contextWindow} token window (${Xe(m.window)})`})),{label:"channels",value:u},{label:"http api",value:f},{label:"store",value:o.store.location},{label:"background",value:await Pi(o,a.id)}])}async function er(n){let r=n.describe(),o=n.host,[a,s]=await Promise.all([n.tools(),n.sessions()]);return g([{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:`${a.tools.length} pinned · ${a.catalogueTokens} catalogue tokens per turn`},{label:"conversations",value:`${s.length} on this agent`},{label:"warnings",value:r.warnings.length===0?"none":r.warnings.map((d)=>d.message).join("; ")}])}async function xi(n,r){let o=await n.previewContext({sessionKey:r}),[a]=me(n.manifest);return{slots:o.slots,history:o.history,cache:o.cache,total:o.total,window:o.window,windowSource:Xe(a?.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 nr(n,r){return yo(await n.source.context(r))}async function Pi(n,r){if(n.owned.includes(r))return"this session is serving this agent";let o=await n.store.leases.get(r);if(o!==void 0&&k(o.pid))return o.mode==="daemon"?`running as a background service · pid ${o.pid} · \`${e.slug} daemon status ${r}\``:`served by another session · pid ${o.pid} (${o.mode})`;return`not supervised — \`${e.slug} daemon install ${r}\` keeps it running without a terminal`}function Se(n,r){return n.length>=r?n:n+" ".repeat(r-n.length)}function Ei(n,r){if(!n.enabled)return"off";if(n.nextRunAt===void 0)return"done";let o=Date.parse(n.nextRunAt)-r;if(o<=0)return"due";let a=Math.round(o/60000);if(a<60)return`in ${a}m`;let s=Math.round(o/3600000);return s<48?`in ${s}h`:`in ${Math.round(s/24)}d`}function Ri(n,r){if(n.lastFiredAt===void 0)return"never run";let o=sA(n.lastFiredAt,r);if(n.lastStatus==="error")return`FAILED ${o}`;return`ok ${o}`}function Ii(n,r){if(n.length===0){process.stdout.write("no schedules — add a `schedules:` block to the manifest\n");return}let o=Math.max(8,...n.map((d)=>d.id.length)),a=Math.max(4,...n.map((d)=>`${d.kind} ${d.expr}`.length));process.stdout.write(`${Se("SCHEDULE",o)} ${Se("WHEN",a)} ${Se("NEXT",7)} LAST
233
+ `);for(let d of n)process.stdout.write(`${Se(d.id,o)} ${Se(`${d.kind} ${d.expr}`,a)} ${Se(Ei(d,r),7)} ${Ri(d,r)}
234
+ `);let s=n.filter((d)=>d.lastStatus==="error");if(s.length>0)process.stdout.write(`
235
+ ${s.length} failing — \`schedules --id ${s[0]?.id}\` for the error
236
+ `)}function Ai(n){let r=[["kind",`${n.kind} ${n.expr}`],["timezone",n.timezone??"(host)"],["task",n.task],["deliver",n.deliverChannel===void 0?"none — the reply reaches the event stream only":`${n.deliverChannel} → ${n.deliverTo}`],["session",n.sessionMode],["model role",n.role??"main"],["enabled",n.enabled?"yes":"no"],["declared in",n.origin==="manifest"?"agent.yaml":"the API"],["next run",n.nextRunAt??"(never again)"],["runs",String(n.runs)],["last run",n.lastFiredAt??"never"],["last status",n.lastStatus??"-"]];if(n.lastError!==void 0)r.push(["last error",n.lastError]);let o=Math.max(...r.map(([a])=>a.length));process.stdout.write(`${n.id}
237
+ `);for(let[a,s]of r)process.stdout.write(` ${Se(a,o)} ${s}
238
+ `)}function Ti(n,r){let o=new Set(r),a=new Map;for(let s of n){if(!o.has(s.channel))continue;let d=`${s.channel}\x00${s.peerId}`,u=a.get(d);if(u!==void 0&&u.lastSeen>=s.lastActivityAt)continue;a.set(d,{channelId:s.channel,address:s.peerId,lastSeen:s.lastActivityAt})}return[...a.values()].sort((s,d)=>s.channelId===d.channelId?d.lastSeen.localeCompare(s.lastSeen):s.channelId.localeCompare(d.channelId))}function Oi(n,r){if(n.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,...n.map((s)=>s.channelId.length)),a=Math.max(7,...n.map((s)=>s.address.length));process.stdout.write(`${Se("CHANNEL",o)} ${Se("ADDRESS",a)} LAST SEEN
241
+ `);for(let s of n)process.stdout.write(`${Se(s.channelId,o)} ${Se(s.address,a)} ${sA(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 tr(n){let r=await U.create({agents:[n.manifestPath],store:n.store??Q(),toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C([n.manifestPath]),lease:!1});h(()=>r.stop("cli-exit"));let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let a=Date.now();for(let[d,u]of[[n.enable,!0],[n.disable,!1]]){if(d===void 0)continue;let f=await o.store.schedules.get(o.id,d);if(f===void 0)return process.stderr.write(`no schedule "${d}" 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
+ `),i;if(f.origin==="manifest")return process.stderr.write(`${d} 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: ${u}\` on the "${d}" entry under schedules: in
252
+ ${n.manifestPath}
253
+ `),i;await o.store.schedules.setEnabled(o.id,d,u,new Date(a).toISOString()),process.stdout.write(u?`${d} enabled — it fires at its next occurrence, not now
254
+ `:`${d} disabled — still listed, and it keeps its place in the sequence
255
+ `)}if(n.recipients===!0){let d=Ti(await o.store.sessions.list(o.id),o.manifest.channels.map((u)=>u.id));if(n.json===!0)return process.stdout.write(`${JSON.stringify({recipients:d},null,2)}
256
+ `),t;return Oi(d,a),t}let s=await o.store.schedules.list(o.id);if(n.json)return process.stdout.write(`${JSON.stringify({schedules:s},null,2)}
257
+ `),t;if(n.id!==void 0){let d=s.find((u)=>u.id===n.id);if(d===void 0)return process.stderr.write(`no schedule "${n.id}" on ${o.id}
258
+ `),i;return Ai(d),t}if(n.enable===void 0&&n.disable===void 0)Ii(s,a);return t}function _i(){return MA.shape.server.parse({})}async function sr(n){let r=C(n.manifestPaths),o=n.store??Q(),a=await Ho(n.manifestPaths,r,o),s=a.filter((D)=>!D.enabled),d=a.filter((D)=>D.enabled),u=n.manifestPaths.length===0,f=[],y=[];for(let D of d)try{f.push({path:D.manifestPath,loaded:b(D.manifestPath,{env:r})})}catch(Y){if(!u)throw Y;y.push({path:D.manifestPath,detail:Te(Y)?Y.message:String(Y),...Te(Y)&&Y.hint!==void 0?{hint:Y.hint}:{}})}let x=f[0],m=x?.loaded,w=m?.manifest.server??_i();for(let D of f.slice(1)){let Y=D.loaded.manifest.server;for(let[le,Ye,rn,Be]of[["server.port",w.port,Y.port,n.port!==void 0],["server.host",w.host,Y.host,n.host!==void 0],["server.tokenEnv",w.tokenEnv,Y.tokenEnv,!1]]){if(Be||Ye===rn)continue;throw new A({code:"serve_bind_conflict",message:`${x?.path??"the first manifest"} sets ${le} to ${String(Ye)} 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:le})}}let E=n.port??w.port,j=n.port===void 0,W=n.host??w.host,I=m===void 0?r[w.tokenEnv]:m.env[w.tokenEnv],T=r[`${e.envPrefix}SERVICE`]!==void 0,de=new We({runtimeId:`rt_${Date.now().toString(36)}`});if(n.json!==!0)de.on("agent.channel.status",(D)=>{let Y=D.data,le=Y.input===void 0?"":Y.input.kind==="pairing_code"?`
259
+
260
+ ${Y.input.payload}
261
+ ${Y.input.expiresAt===void 0?"":`
262
+ expires ${Y.input.expiresAt}`}`:` (${Y.input.kind}${Y.input.expiresAt===void 0?"":`, expires ${Y.input.expiresAt}`} — GET /v1/agents/${D.agentId??""} carries it)`;process.stdout.write(` ${Y.channelId}: ${Y.status}${Y.detail===void 0?"":` — ${Y.detail}`}${le}
263
+ `)}),de.on("agent.channel.error",(D)=>{let Y=D.data;process.stderr.write(` ${Y.channelId}: ${Y.message}
264
+ hint: ${Y.hint}
265
+ `)}),de.on("error",(D)=>{let Y=D.data,le=D.sessionKey===void 0?"":` [${D.sessionKey}]`;process.stderr.write(` turn failed${le}: ${Y.code}: ${Y.message}
266
+ hint: ${Y.hint}
267
+ `)}),de.on("agent.channel.rejected",(D)=>{let Y=D.data;process.stdout.write(` ${Y.channelId}: ${Y.reason} — ${Y.detail}
268
+ `)});let K=qn(),re=await U.create({agents:f.map((D)=>D.path),approve:K.approver,env:r,bus:de,toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,startChannels:!0,startSchedules:!0,store:o,mode:T?"daemon":"terminal"});zo();let G=Ci(),ee=await re.store.operatorKeys.liveCount(),te=ee===0||n.claim===!0?Go():void 0,se,be=[];try{se=await ji(E,j,(D)=>(be.push(D),Lo({runtime:re,host:W,port:D,approvals:K,allowedOrigins:w.allowedOrigins,allowedHosts:w.allowedHosts,resolveAgent:(Y)=>Bt(Y,r),provision:{steps:()=>Kt({agentDirBase:_(r)}),create:(Y)=>Ut({answers:Y,defaults:{agentDirBase:_(r)}})},channels:{setEnabled:ct,setCredential:lt,unpair:It},...te===void 0?{}:{claim:te},...I===void 0||I===""?{}:{token:I}})))}catch(D){if(await re.stop("server failed to bind"),D instanceof A)throw D;let Y=be.length>1?` — also tried ${be.slice(1).join(", ")}`:"";throw new A({code:"server_bind_failed",message:`Could not bind ${W}:${E}${Y}: ${D instanceof Error?D.message:String(D)}`,hint:j?`Every port in the range is taken. Pass --port to name a free one, or stop whatever is holding them — \`${e.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:D})}await re.publishAddress(se.url);let ce=re.list(),Ce=ce[0];if(Ce!==void 0)process.title=ce.length===1?`${e.slug} ${Ce.id}`:`${e.slug} ${ce.length} agents`;for(let D of ce)D.reportRuntimeState({serverListening:!0});if(n.json===!0)process.stdout.write(`${JSON.stringify({url:se.url,websocket:se.websocket,authenticated:I!==void 0&&I!=="",keys:ee,...te===void 0?{}:{claim:te.token},agents:ce.map((D)=>({id:D.id,channels:re.channels.statusOf(D.id)})),declined:re.declined.map((D)=>({agentId:D.agentId,pid:D.pid,mode:D.mode,since:D.startedAt})),disabled:s.map((D)=>({agentId:D.agentId,...D.reason===void 0?{}:{reason:D.reason}})),broken:y.map((D)=>({path:D.path,detail:D.detail,...D.hint===void 0?{}:{hint:D.hint}}))})}
269
+ `);else{let D=`http://${KA(W)}:${se.port}`,Y=D===se.url?"":` (bound ${W} — every interface)`;if(process.stdout.write(`${e.name} serving on ${D}${Y}
270
+ `),se.port!==E)process.stdout.write(` moved from ${E} — something else is on it. \`--port ${E}\` would refuse instead of moving.
271
+ `);process.stdout.write(` web UI ${D}/ · API reference ${D}/docs
272
+ `);for(let le of ce){let Ye=re.channels.statusOf(le.id),rn=Ye.length===0?"no channels":Ye.map((Ze)=>`${Ze.id} (${Ze.type}${Ze.status==="error"?", BROKEN":""})`).join(", "),Be=le.manifest.schedules.filter((Ze)=>Ze.enabled),hr=le.manifest.schedules.length===0?"":`, ${Be.length} schedule${Be.length===1?"":"s"}${le.manifest.schedules.length>Be.length?` (+${le.manifest.schedules.length-Be.length} disabled)`:""}`;process.stdout.write(` ${le.id} — ${rn}${hr}
273
+ `)}for(let le of s)process.stdout.write(` ${le.agentId} — stopped${le.reason===void 0?"":` (${le.reason})`}, \`${e.slug} start ${le.agentId}\`
274
+ `);for(let le of y)if(process.stdout.write(` ${le.path} — NOT served: ${le.detail}
275
+ `),le.hint!==void 0)process.stdout.write(` hint: ${le.hint}
276
+ `);for(let le of re.declined)process.stdout.write(` ${le.agentId} — NOT served here: pid ${le.pid} (${le.mode}) already has it
277
+ `);if(re.declined.length>0)process.stdout.write(` \`${e.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
278
+ `);if(te!==void 0){if(process.stdout.write(` open once to claim this server:
279
+ ${Fo(W,se.port,te.token)}
280
+ without a browser: ${To(W,se.port,te.token)}
281
+ `),I===void 0||I==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
282
+ `)}if(I===void 0||I==="")process.stdout.write(` unauthenticated — loopback only. Set ${w.tokenEnv} to bind a public host.
283
+ `);if(T)process.stdout.write(` running as a background service · ${e.slug} daemon status ${ce[0]?.id??""}
284
+ `);else if(Jn())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. \`${e.slug} daemon install${ce[0]?.id===void 0?"":` ${ce[0].id}`}\` keeps it running.
286
+ `)}let ze=!1,Qe=async()=>{if(ze)return;ze=!0,await se.stop(),await re.stop("interrupted")};return h(Qe),await G,process.stdout.write(`stopping
287
+ `),await Qe(),t}function Ci(){return new Promise((n)=>{let r=()=>{process.off("SIGINT",r),process.off("SIGTERM",r),n()};process.once("SIGINT",r),process.once("SIGTERM",r)})}var Ni=16;async function ji(n,r,o){let a=r&&n!==0?n+Ni:n;for(let s=n;;s+=1)try{return await o(s)}catch(d){if(s>=a||!Fi(d))throw d}}function Fi(n){if(typeof n==="object"&&n!==null&&"code"in n){if(n.code==="EADDRINUSE")return!0}let r=n instanceof Error?n.message:String(n);return r.includes("EADDRINUSE")||r.includes("in use")}function ye(n,r){return n.length>=r?n:n+" ".repeat(r-n.length)}function Ki(n){let r=new Map,o=[];for(let a of n){let s=a.sessionKey.split(":"),d={sessionKey:a.sessionKey,phase:a.phase,messages:a.messages,turns:a.turns,lastActivityAt:a.lastActivityAt};if(s.length!==3||s[0]!=="schedule"){o.push(d);continue}let u=`schedule:${s[1]}`,f=r.get(u);if(f===void 0){let y={...d,sessionKey:`${u}:*`,runs:1};r.set(u,y),o.push(y);continue}if(f.runs=(f.runs??1)+1,f.messages+=a.messages,f.turns+=a.turns,a.lastActivityAt>f.lastActivityAt)f.lastActivityAt=a.lastActivityAt}return o}function Li(n){if(n.length===0){process.stdout.write(`no sessions yet
288
+ `);return}let r=Ki(n),o=Math.max(7,...r.map((a)=>a.sessionKey.length));process.stdout.write(`${ye("SESSION",o)} ${ye("MSGS",5)} ${ye("TURNS",5)} ${ye("PHASE",8)} LAST
289
+ `);for(let a of r){let s=a.runs===void 0?"":` (${a.runs} run${a.runs===1?"":"s"})`;process.stdout.write(`${ye(a.sessionKey,o)} ${ye(String(a.messages),5)} ${ye(String(a.turns),5)} ${ye(a.phase??"-",8)} ${sA(a.lastActivityAt,Date.now())}${s}
290
+ `)}}async function Ui(n,r,o){let a=await n.store.messages.page(n.id,r,{limit:o});if(a.messages.length===0){process.stdout.write(`no messages in ${r}
291
+ `);return}for(let s of[...a.messages].reverse())process.stdout.write(`${s.role}: ${s.content}
292
+ `);if(a.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 Mi(n,r,o){let a=await n.turns(r,o);if(a.length===0){process.stdout.write(`no turns in ${r}
295
+ `);return}process.stdout.write(`${ye("TURN",22)} ${ye("STATUS",9)} ${ye("STEPS",5)} ${ye("TOKENS",13)} ${ye("MS",6)} SOURCE
296
+ `);for(let s of a)if(process.stdout.write(`${ye(s.turnId,22)} ${ye(s.status,9)} ${ye(String(s.steps),5)} ${ye(`${s.promptTokens}/${s.outputTokens}`,13)} ${ye(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 rr(n){let r=await U.create({agents:[n.manifestPath],store:n.store??Q(),toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C([n.manifestPath])});h(()=>r.stop("cli-exit"));let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let a=n.limit??sn;if(n.clear===!0){if(n.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 d=await o.store.messages.count(o.id,n.sessionKey);return await o.clearSession(n.sessionKey),process.stdout.write(`cleared ${n.sessionKey}: ${d} message(s) removed, memory files untouched
300
+ `),t}if(n.json===!0){let d=n.sessionKey===void 0?{store:r.store.location,sessions:await o.sessions()}:{store:r.store.location,session:await o.store.sessions.get(o.id,n.sessionKey),messages:(await o.store.messages.page(o.id,n.sessionKey,{limit:a})).messages,turns:await o.turns(n.sessionKey,a)};return process.stdout.write(`${JSON.stringify(d,null,2)}
301
+ `),t}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
+ `),n.sessionKey===void 0)return Li(await o.sessions()),t;if(await o.store.sessions.get(o.id,n.sessionKey)===void 0)return process.stderr.write(`no session "${n.sessionKey}" for agent ${o.id}
304
+ hint: run \`sessions ${n.manifestPath}\` to list the keys that exist
305
+ `),i;if(n.turns===!0)await Mi(o,n.sessionKey,a);else await Ui(o,n.sessionKey,a);return t}import{existsSync as Hi,readFileSync as Wi,writeFileSync as qi}from"node:fs";import{basename as Gi,dirname as Bi,join as Vi}from"node:path";var Ji=/^(#{1,6})\s+(.*)$/,Xi=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,zi=/^[ \t]*<\/rules>[ \t]*$/,Qi=/^\s*(?:```|~~~)/;function or(n){if(n.action!=="distill")throw new A({code:"cli_soul_unknown_action",message:`soul takes the action "distill", not "${n.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=Wi(n.file,"utf8")}catch{throw new A({code:"cli_soul_file_missing",message:`${n.file} is not readable.`,hint:"Point soul distill at the long-form identity document named by context.soul.file."})}let o=Gi(n.file),a=n.out??Vi(Bi(n.file),`${o.replace(/\.md$/i,"")}.compact.md`);if(Hi(a))throw new A({code:"cli_soul_out_exists",message:`${a} 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}=kt(o,r),d=Yi(o,s);return qi(a,d,"utf8"),process.stdout.write(`wrote ${a}
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
+ `),t}function Yi(n,r){let o=["---","tier: static","---","","<!--",`Compact identity scaffolded from ${n}. 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.","-->",""],a=!1,s=!1,d=0,u=!1;for(let f of r.split(`
313
+ `)){if(Qi.test(f)){if(a=!a,s)o.push(f);continue}if(a){if(s)o.push(f);continue}if(Xi.test(f)){s=!0,o.push(f);continue}if(s){if(o.push(f),zi.test(f))s=!1,o.push("");continue}if(Ji.exec(f)!==null)u=!0,d+=1,o.push(f),o.push(""),o.push(`{{SECTION_${d}}}`),o.push("")}if(!u)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 Zi=["list","add","remove","update","search"],ea=12;async function ir(n){try{switch(n.action){case"list":return na(n);case"add":return ta(n);case"remove":return ra(n);case"update":return await oa(n);case"search":return await ia(n);default:throw new A({code:"sources_action_unknown",message:`${n.action} is not a sources action`,hint:`One of: ${Zi.join(", ")}.`})}}catch(r){if(r instanceof A)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
+ `),i;throw r}}function na(n){let o=Z(n.env).map((a)=>{let s=pn(a.name,n.env);return{...a,cached:Ee(a.name,n.env),commit:s.commit,fetchedAt:s.fetchedAt,skills:s.skills}});if(n.json===!0)return process.stdout.write(`${JSON.stringify({registry:pt(n.env),sources:o},null,2)}
321
+ `),t;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 ${pA[0]?.name??"anthropic"} ${pA[0]?.url??""}\` to put a built-in back.
324
+ `),t;process.stdout.write(B("sources",!0));for(let a of o)process.stdout.write(`
325
+ ${l(`${a.name}${a.builtin===!0?" (built-in)":""}`)}
326
+ `),process.stdout.write(c(g([{label:"url",value:a.url},...a.path===void 0?[]:[{label:"path",value:a.path}],...a.ref===void 0?[]:[{label:"branch",value:a.ref}],{label:"cached",value:a.cached?`${a.skills??"?"} skills at ${a.commit??"?"}, fetched ${a.fetchedAt??"at an unknown time"}`:"never fetched — `sources update` or just search, which fetches on demand"}]),4));return process.stdout.write(`
327
+ ${B("registry")}
328
+ ${c(pt(n.env))}
329
+ `),t}function ta(n){let[r,o]=n.rest;if(r===void 0)throw new A({code:"sources_add_incomplete",message:"sources add needs a repository",hint:"`sources add <url>` names it after the owner, or `sources add <name> <url>` to choose. A .../tree/<branch>/<subdir> page URL is understood."});let a=o!==void 0,s=a?o:r,d=En(s),u=a?r:sa(d.url);if(!QA(u))throw new A({code:"sources_name_invalid",message:`${JSON.stringify(u)} 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 f=Z(n.env).find((w)=>w.name===u);if(f!==void 0&&!a)throw new A({code:"sources_name_taken",message:`${u} is already a source, pointing at ${f.url}`,hint:`Give this one its own name: \`sources add <name> ${s}\`.`});let y=n.path??d.path,x=n.ref??d.ref,m={name:u,url:d.url,...y===void 0?{}:{path:y},...x===void 0?{}:{ref:x}};if(xo(m,n.env),n.json===!0)return process.stdout.write(`${JSON.stringify({added:m},null,2)}
330
+ `),t;return process.stdout.write(`${g([{label:f===void 0?"added":"replaced",value:u},{label:"url",value:m.url},...m.path===void 0?[{label:"path",value:"the whole repository — `--path skills` if the skills live in a subdirectory"}]:[{label:"path",value:m.path}],...m.ref===void 0?[]:[{label:"branch",value:m.ref}]])}
331
+ `),process.stdout.write(`${B("next")}
332
+ ${l(`sources update ${u}`)}
333
+ ${l("sources search <what you need>")}
334
+ `),t}function sa(n){let r=n.replace(/\.git$/,"").split(/[:/]/).filter((a)=>a.length>0);return(r[r.length-2]??"").toLowerCase().replace(/[^a-z0-9]+/g,"-").replace(/^-|-$/g,"")}function ra(n){let r=n.rest[0];if(r===void 0)throw new A({code:"sources_remove_incomplete",message:"sources remove needs a name",hint:"`sources list` shows them."});let o=Z(n.env).map((s)=>s.name);if(!Yo(r,n.env)){let s=S(r,o);throw new A({code:"sources_unknown",message:`no source called ${r}`,hint:s===void 0?`Configured: ${o.join(", ")||"none"}.`:`Did you mean ${s}?`})}let a=pA.some((s)=>s.name===r);return process.stdout.write(`removed ${r}${a?" — 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
+ `),t}async function oa(n){let r=Z(n.env),o=n.rest.length===0?r:n.rest.map((d)=>{let u=r.find((f)=>f.name===d);if(u===void 0){let f=S(d,r.map((y)=>y.name));throw new A({code:"sources_unknown",message:`no source called ${d}`,hint:f===void 0?`Configured: ${r.map((y)=>y.name).join(", ")||"none"}.`:`Did you mean ${f}?`})}return u});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
+ `),t;let a=[],s=[];for(let d of o){if(n.json!==!0)process.stdout.write(`fetching ${d.name} … `);try{let u=await hA(d,{...n.env===void 0?{}:{env:n.env},...n.git===void 0?{}:{git:n.git}});if(a.push({name:d.name,commit:u.commit,skills:u.skills}),n.json!==!0)process.stdout.write(`${u.skills} skills at ${u.commit}${u.unfiltered&&d.path!==void 0?" (full clone — the server refused a partial one)":""}
341
+ `)}catch(u){let f=u instanceof Error?u.message:String(u);if(s.push({name:d.name,reason:f}),n.json!==!0)process.stdout.write(`failed
342
+ `);if(n.json!==!0&&u instanceof A)process.stdout.write(`${c(u.message)}
343
+ ${c(u.hint,4)}
344
+ `)}}if(n.json===!0)process.stdout.write(`${JSON.stringify({updated:a,failed:s},null,2)}
345
+ `);return a.length===0?i:t}async function ia(n){let r=n.rest.join(" ").trim(),o=Z(n.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
+ `),i;let a=o.filter((f)=>!Ee(f.name,n.env));for(let f of a){if(n.json!==!0)process.stdout.write(`fetching ${f.name} for the first time … `);try{let y=await hA(f,{...n.env===void 0?{}:{env:n.env},...n.git===void 0?{}:{git:n.git}});if(n.json!==!0)process.stdout.write(`${y.skills} skills
349
+ `)}catch(y){if(n.json!==!0){if(process.stdout.write(`failed
350
+ `),y instanceof A)process.stdout.write(`${c(y.message)}
351
+ `)}}}let s=o.flatMap((f)=>Ne(f,n.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
+ `),i;let d=r.length===0?s:aa(r,s);if(d.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
+ `),t;if(n.json===!0)return process.stdout.write(`${JSON.stringify({query:r,searched:s.length,results:d.map((f)=>({source:f.source,skill:f.skill,description:f.description,tokens:f.tokens,scripts:f.scripts.length,repoPath:f.repoPath,...f.problem===void 0?{}:{problem:f.problem}}))},null,2)}
360
+ `),t;let u=d.slice(0,ea);process.stdout.write(`
361
+ ${B(r.length===0?`${s.length} skills`:`${d.length} of ${s.length} skills match ${JSON.stringify(r)}`,!0)}
362
+ `);for(let f of u){process.stdout.write(`${l(`${f.source}/${f.skill}`)} ${f.tokens} tokens${f.scripts.length===0?"":`, ${f.scripts.length} runnable file${f.scripts.length===1?"":"s"}`}${f.problem===void 0?"":" — will not load"}
363
+ `);let y=f.problem??f.description;process.stdout.write(`${c(y.length>160?`${y.slice(0,157)}…`:y,4)}
364
+ `)}if(d.length>u.length)process.stdout.write(`
365
+ ${c(`… and ${d.length-u.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(`
367
+ ${B("install")}
368
+ ${c(`skills install <agent> ${u[0]?.source}/${u[0]?.skill}`)}
369
+ `),t}function aa(n,r){let o=new Map,a=r.map((s)=>{let d=`${s.source}/${s.skill}`;return o.set(d,s),{name:d,dir:s.dir,tokens:s.tokens,scripts:[],ignoredScripts:[],frontmatter:{name:d,description:s.description,metadata:{}}}});return kA(n,a).filter((s)=>s.score>0).map((s)=>o.get(s.skill.name)).filter((s)=>s!==void 0)}async function ar(n){let r=da(n.manifestPath),o=await fn(r,n.store),a=[];if(o?.enabled===!0)a.push("was already switched on");await Bn(r,!0,void 0,n.store);let s=await oe(n.store),d=!1;if(s===void 0)a.push("nothing is serving yet — it will be hosted at the next start");else if(s.baseUrl===void 0)a.push(`pid ${s.pid} is a ${s.mode} session, which serves no HTTP to adopt into`);else{let u=await fe(s,`/v1/agents/${encodeURIComponent(r)}/start`,{},n.manifestPath);if(u.ok)d=!0,a.push(`adopted by pid ${s.pid}, live now`);else if(u.status===501)a.push(`pid ${s.pid} cannot look up manifests — restart it to pick this up`);else if(u.status===401)a.push(`pid ${s.pid} refused the request — set ${e.envPrefix}API_TOKEN to the server's token`);else a.push(`pid ${s.pid} could not adopt it${u.detail===void 0?"":`: ${u.detail}`}`)}if(n.json===!0)process.stdout.write(`${JSON.stringify({started:[{agentId:r,enabled:!0,running:d,...s===void 0?{}:{pid:s.pid,mode:s.mode},note:a.join(" · ")}]},null,2)}
370
+ `);else if(process.stdout.write(`${g([{label:r,value:d?"running":"switched on",note:a.join(" · ")}])}
371
+ `),!d&&s!==void 0&&s.baseUrl!==void 0)process.stdout.write(`
445
372
  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)}
373
+ `);return s!==void 0&&s.baseUrl!==void 0&&!d?i:t}function da(n){let r=p(n);if(r.id===void 0||r.id==="")throw new A({code:"cli_start_agent_id_missing",message:`${n} 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 dr(n){let r=await _n(n.store),o=new Map;for(let d of r){if(d.serving===void 0)continue;let u=await UA(d.manifestPath,n.store);if(u!==void 0)o.set(d.ref,u)}if(n.json===!0)return process.stdout.write(`${JSON.stringify({agents:r.map((d)=>({...d,channels:[...o.get(d.ref)?.values()??[]]}))},null,2)}
374
+ `),t;let a=await ke({action:"status",...n.store===void 0?{}:{store:n.store}});process.stdout.write(`${g(Cn(r))}
375
+ `);let s=[];for(let[d,u]of o)for(let f of u.values())s.push({label:`${d} / ${f.id}`,value:f.status,note:f.input!==void 0?`${f.detail??"enter this code"}: ${f.input.payload}`:f.detail??""});if(s.length>0)process.stdout.write(`
376
+ ${g(s)}
377
+ `);return a}import{copyFileSync as la,existsSync as ca,mkdirSync as ua,readFileSync as fa,writeFileSync as ma}from"node:fs";import{dirname as pa,join as lr}from"node:path";async function cr(n){let r=n.env??C([]),o=n.home??r.HOME??"",a=gn(r),s=$n(a);if(n.json===!0)return process.stdout.write(`${JSON.stringify({terminal:a,how:s?.how??"unknown",configPath:s?.configPath===void 0?void 0:lr(o,s.configPath),line:s?.line,steps:s?.steps},null,2)}
378
+ `),s===void 0?i:t;if(process.stdout.write(`${B("shift+enter",!0)}
448
379
  ${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"}`)}
380
+ `),s===void 0)return process.stdout.write(`
381
+ ${B("this terminal was not recognised")}
382
+ ${c(`TERM_PROGRAM=${r.TERM_PROGRAM??"(unset)"} TERM=${r.TERM??"(unset)"}`)}
383
+ ${c(`known: ${Wt().map((d)=>d.name).join(", ")}`)}
384
+ ${l("⌥⏎ works here regardless — nothing needs configuring for it")}
385
+ `),i;if(process.stdout.write(`
386
+ ${B(s.name)}
387
+ `),s.how!=="write"){process.stdout.write(`${c(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[d,u]of(s.steps??[]).entries())process.stdout.write(`${c(`${d+1}. ${u}`)}
390
+ `);return process.stdout.write(s.how==="unverified"?`
391
+ ${l("⌥⏎ 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}
499
- `+(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
393
+ ${l("then restart the terminal and press shift+⏎ in a session to check it")}
394
+ `),t}return await ha(s,{...n,env:r,home:o})}async function ha(n,r){let o=lr(r.home,n.configPath??""),a=ca(o)?fa(o,"utf8"):"";if(qt(a,n))return process.stdout.write(`${c("already configured — a binding for shift+enter is present")}
395
+ ${c(rA(o,r.home),4)}
396
+ `),t;let s=Vt(a,n);if(s===void 0)return process.stdout.write(`${c("this file is not in a shape this command can edit safely:")}
397
+ ${c(rA(o,r.home),4)}
398
+ ${l("add the line below by hand:")}
399
+ ${c(n.line??"",4)}
400
+ `),i;if(process.stdout.write(`${g([{label:"file",value:rA(o,r.home)},{label:"exists",value:a===""?"no — it will be created":"yes"},{label:"add",value:n.line??""}])}
401
+ `),r.dryRun===!0)return process.stdout.write(`
402
+ ${l("--dry-run: nothing was written")}
403
+ `),t;if(r.yes!==!0){if(!(r.confirm===void 0?!1:await r.confirm("write this change?")))return process.stdout.write(`
404
+ ${l("nothing was written")}
405
+ `),t}try{if(ua(pa(o),{recursive:!0}),a!=="")la(o,`${o}.${e.slug}-backup`);ma(o,s,"utf8")}catch(d){return process.stderr.write(`could not write ${o}: ${d instanceof Error?d.message:String(d)}
406
+ `),i}return process.stdout.write(`
407
+ ${B("done")}
408
+ ${a===""?"":`${c(`a copy of the old file is at ${rA(`${o}.${e.slug}-backup`,r.home)}`)}
409
+ `}${l("restart the terminal, then press shift+⏎ in a session to check it")}
410
+ `),t}async function ur(n){return n.warm===!0?await ga(n):await ya(n)}async function ga(n){let r=b(n.manifestPath,{env:C([n.manifestPath])}),o=De(r.manifest.tools).selections,a=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
+ `),t;if(a.length===0)return process.stdout.write(`nothing to warm — ${o.map((f)=>f.id).join(", ")} configured but tools.pinned is empty, so there are no schemas to fetch.
412
+ `),t;let s=[],d=new Set;for(let f of o){let y=F[f.id];if(y===void 0)return i;let x=y({dir:r.dir,env:r.env,config:f.config,agentId:r.manifest.id});if(x.refresh===void 0){for(let w of await x.resolve(a))d.add(w.spec.slug);if(n.json!==!0)process.stdout.write(`${f.id}: nothing to warm — it resolves without a cache.
413
+ `);continue}let m=await x.refresh(a);for(let w of a)if(!m.missing.includes(w))d.add(w);s.push({provider:f.id,fetched:m.fetched,changed:[...m.changed],missing:[...m.missing],cachePath:"cachePath"in m&&typeof m.cachePath==="string"?m.cachePath:""})}if(n.json===!0)process.stdout.write(`${JSON.stringify(s,null,2)}
414
+ `);else for(let f of s){if(process.stdout.write(`${f.fetched} of ${a.length} pinned tools fetched from ${f.provider}
415
+ `),f.changed.length>0)process.stdout.write(` changed: ${f.changed.join(", ")}
416
+ `);if(f.cachePath!=="")process.stdout.write(` cache: ${f.cachePath}
417
+ `)}let u=a.filter((f)=>!d.has(f));for(let f of u)process.stdout.write(` missing: ${f} — no configured provider has a tool with that slug
418
+ `);return u.length>0?i:t}async function ya(n){let r=await U.create({agents:[n.manifestPath],toolProviders:F,builtInPlugins:P,pluginRoot:O(),scriptRunner:v(),channels:N,env:C([n.manifestPath])});try{let o=r.list()[0];if(o===void 0)throw Error("The manifest produced no agent.");let a=cn(o);return process.stdout.write(n.json===!0?`${JSON.stringify(a,null,2)}
419
+ `:`${IA(a)}
420
+ `),t}finally{await r.stop("cli-exit")}}import{dirname as fr,isAbsolute as wa,resolve as On}from"node:path";async function mr(n){try{let r=p(n.manifestPath),o=await Gt({refs:r.plugins??[],agentId:r.id??n.manifestPath,paths:{workspace:fr(On(n.manifestPath)),state:fr(On(n.manifestPath)),manifest:On(n.manifestPath)},env:C([n.manifestPath]),bus:new We({runtimeId:"validate"}),builtIn:P,pluginRoot:O(),base:{toolProviders:F,channels:N}}),a=b(n.manifestPath,{env:C([n.manifestPath])}),{manifest:s}=a,d=q(s.model.main.id,s.model.main.capabilities),{workspace:u,warnings:f}=nA(a,d.promptStyle),y=Pt(Lt(a,{channels:o.channels})),x=await Tt(a,{toolProviders:o.toolProviders,channels:o.channels,scriptRunner:o.scriptRunner,middleware:o.middleware});for(let K of x.providers)await K.stop?.();let m=Ke(u,s.context.rules);if(m!==void 0&&s.context.rules.onExceed==="fail")throw m;let w=[...f,...o.failed,...x.warnings,...x.registry.warnings,...y,...Nt(s),...m===void 0?[]:[m.toDetail()]],E=s.knowledge===void 0?void 0:Ft({dir:wa(s.knowledge.dir)?s.knowledge.dir:On(a.dir,s.knowledge.dir),maxActive:s.knowledge.maxActive,budget:s.knowledge.budget,style:d.promptStyle}),j=["static","volatile","reminder"].map((K)=>{let re=u.files.filter((G)=>G.tier===K).map((G)=>G.name);if(re.length===0)return;return`${K}=${re.join(",")} (${u.tokens[K]}/${s.context.budgets[K]})`}).filter((K)=>K!==void 0).join(" ");if(n.json===!0)return process.stdout.write(`${JSON.stringify({ok:!0,path:a.path,id:s.id,model:s.model.main.id,window:a.window,capabilities:d,workspace:{files:u.files.map((K)=>({name:K.name,tier:K.tier,editable:K.editable,tokens:K.tokens,budget:K.budget})),tokens:u.tokens},knowledge:E===void 0?[]:E.entries.map((K)=>({name:K.name,keywords:K.keywords,tokens:K.tokens})),warnings:w},null,2)}
421
+ `),t;let W=me(s),I=W.map((K)=>K.role===K.configuredAs?`${K.role}=${K.modelId}`:`${K.role}=→main`).join(" "),T=W.filter((K)=>K.role===K.configuredAs),de=No({manifestPath:n.manifestPath,rawModelId:r.modelId,apiKeyEnv:s.model.main.apiKeyEnv}).flatMap((K)=>{let re=Oo(K.origin);return re===void 0?[]:[` env ${K.variable} — ${re}
422
+ `]}).join("");return process.stdout.write(`ok ${a.path}
423
+ id ${s.id}${s.name===void 0?"":` (${s.name})`}
424
+ models ${I}
425
+ `+de+` window ${a.window} ${Xe(W[0]?.window)} (reserveOutput ${s.context.reserveOutput}, maxOutput ${d.maxOutput})
426
+ `+(T.length<2?"":`${T.slice(1).map((K)=>` ${K.role.padEnd(12)} ${K.modelId} · window ${K.window.contextWindow} ${Xe(K.window)}
427
+ `).join("")}`)+` capabilities thinking=${d.thinking} promptCache=${d.promptCache} nativeTools=${d.nativeTools} strictSchema=${d.strictSchema}
428
+ `+ba(d.promptCache,s.model.main.id)+` dialect ${s.tools.dialect}
429
+ workspace ${j===""?"(none)":j}
430
+ `+(E===void 0?"":` knowledge ${E.entries.length} entries, maxActive=${E.maxActive}, budget=${E.budget}
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
+ `+w.map((K)=>` warning ${K.message}
436
+ `).join("")),t}catch(r){if(n.json===!0&&r instanceof A)return process.stdout.write(`${JSON.stringify({ok:!1,error:r.toDetail(),details:r.details},null,2)}
437
+ `),i;throw r}}function ba(n,r){if(n!=="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 pr(n){try{let r=b(n.manifestPath,{env:C([n.manifestPath])}),{manifest:o}=r,a=q(o.model.main.id,o.model.main.capabilities),{workspace:s,warnings:d}=nA(r,a.promptStyle),u=[...d,...co(s.files.map((x)=>({name:x.name,authored:x.authored,tier:x.tier,field:x.field})))],f=Ke(s,o.context.rules);if(f!==void 0)u.push(f.toDetail());if(n.json===!0)return process.stdout.write(`${JSON.stringify({ok:u.length===0,path:r.path,promptStyle:a.promptStyle,files:s.files.map((x)=>({name:x.name,tier:x.tier,editable:x.editable,tokens:x.tokens,budget:x.budget})),tokens:s.tokens,findings:u},null,2)}
442
+ `),n.strict===!0&&u.length>0?i:t;let y=a.promptStyle;process.stdout.write(`${r.path}
443
+ rendering delimiters=${y.delimiters} intensity=${y.intensity} examplesIn=${y.examplesIn}
444
+ total ${s.tokens.total} tokens (static ${s.tokens.static}, volatile ${s.tokens.volatile}, reminder ${s.tokens.reminder})
445
+ `);for(let x of s.files)process.stdout.write(` ${x.name.padEnd(14)} ${x.tier.padEnd(9)} ${String(x.tokens).padStart(5)}/${x.budget} tokens, editable=${x.editable}
446
+ `);if(u.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
+ `),t;for(let x of u)process.stdout.write(`
449
+ ${x.code}: ${x.message}
450
+ `),process.stdout.write(` hint: ${x.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
+ ${u.length} finding(s)
453
+ `),n.strict===!0?i:t}catch(r){if(n.json===!0&&r instanceof A)return process.stdout.write(`${JSON.stringify({ok:!1,error:r.toDetail(),details:r.details},null,2)}
454
+ `),i;throw r}}function $a(n){if(n instanceof A)process.stderr.write(`${n.format()}
455
+ `);else if(n instanceof Error){if(process.stderr.write(`${n.message}
456
+ `),Fe().debug&&n.stack!==void 0)process.stderr.write(`${n.stack}
457
+ `)}else process.stderr.write(`${String(n)}
458
+ `);return i}async function va(n){let r=Po(n);switch(r.kind){case"version":return process.stdout.write(`${M}
459
+ `),t;case"help":return process.stdout.write(Zn(r.command)),t;case"usage":return process.stdout.write(Zn()),i;case"command":break}let{command:o,positionals:a,flags:s}=r.parsed,d=a[0],u=()=>Ae(d),f=o.flags.some((m)=>m.name==="store")?s.str("store"):void 0,y=await un({needsServer:o.needsServer,disabled:s.bool("no-bootstrap"),install:()=>dn(),...f===void 0?{}:{store:f}}),x=uA(y);if(x!==void 0)process.stderr.write(x);switch(o.name){case"init":{let m=s.str("dir"),w=s.str("user"),E=s.str("name"),j=s.str("purpose"),W=s.str("preset"),I=s.str("model"),T=s.str("base-url"),de=s.str("api-key-env"),K=s.str("system"),re=s.str("web"),G=s.str("web-backend"),ee=s.str("composio"),te=s.str("telegram"),se=s.str("telegram-allow"),be=s.str("whatsapp"),ce=s.str("whatsapp-number"),Ce=s.str("server"),ze=s.str("schedules"),Qe=s.str("skills"),D=s.str("daemon");return await Mt({...m===void 0?{}:{dir:m},...w===void 0?{}:{user:w},...E===void 0?{}:{name:E},...j===void 0?{}:{purpose:j},...W===void 0?{}:{preset:W},...I===void 0?{}:{model:I},...T===void 0?{}:{baseUrl:T},...de===void 0?{}:{apiKeyEnv:de},...K===void 0?{}:{system:K},...re===void 0?{}:{web:re},...G===void 0?{}:{webBackend:G},...ee===void 0?{}:{composio:ee},...te===void 0?{}:{telegram:te},...ze===void 0?{}:{schedules:ze},...se===void 0?{}:{telegramAllow:se},...be===void 0?{}:{whatsapp:be},...ce===void 0?{}:{whatsappNumber:ce},...Ce===void 0?{}:{server:Ce},...Qe===void 0?{}:{skills:Qe},...D===void 0?{}:{daemon:D},yes:s.bool("yes"),plain:s.bool("plain"),installServer:dn})}case"run":{let m=s.str("session"),w=s.str("input"),E=s.str("store");return await wt({...a[0]===void 0?{}:{manifestPath:u()},...m===void 0?{}:{sessionKey:m},continueSession:s.bool("continue"),...w===void 0?{}:{once:w},...E===void 0?{}:{store:E},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 m=s.str("store"),w=s.str("id"),E=s.str("enable"),j=s.str("disable");return await tr({manifestPath:u(),...m===void 0?{}:{store:m},...w===void 0?{}:{id:w},...E===void 0?{}:{enable:E},...j===void 0?{}:{disable:j},recipients:s.bool("recipients"),json:s.bool("json")})}case"sessions":{let m=s.str("session"),w=s.str("store"),E=s.num("limit");return await rr({manifestPath:u(),...m===void 0?{}:{sessionKey:m},...w===void 0?{}:{store:w},...E===void 0?{}:{limit:E},json:s.bool("json"),clear:s.bool("clear"),turns:s.bool("turns")})}case"memory":{let m=s.num("limit"),w=s.str("store");return await ss({action:d,manifestPath:Ae(a[1]??""),...a[2]===void 0?{}:{query:a[2]},...m===void 0?{}:{limit:m},...w===void 0?{}:{store:w},all:s.bool("all"),json:s.bool("json")})}case"config":{let{configCommand:m,readAction:w}=await import("./config-64q4mgxc.js"),E=w(d,a[1]);return await m({action:E.action,...E.ref===void 0?{}:{ref:E.ref},...a[2]===void 0?{}:{name:a[2]},...a[3]===void 0?{}:{value:a[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 mr({manifestPath:u(),json:s.bool("json")});case"workspace":return pr({manifestPath:u(),json:s.bool("json"),strict:s.bool("strict")});case"soul":{let m=s.str("out");return or({action:d,file:a[1],...m===void 0?{}:{out:m}})}case"skills":{if(a.length===0)return await jo({plain:s.bool("plain"),json:s.bool("json")});let m=a[2];return Re({action:d,manifestPath:Ae(a[1]??""),...m===void 0?{}:{name:m},json:s.bool("json"),strict:s.bool("strict")})}case"sources":{let m=s.str("path"),w=s.str("ref");return await ir({action:d,rest:a.slice(1),...m===void 0?{}:{path:m},...w===void 0?{}:{ref:w},json:s.bool("json")})}case"channels":{let m=Ko("channels",d),w=m.ref??a[1]??"",{channelsCommand:E}=await import("./channels-q4fwqq87.js");return await E({...m.action===void 0?{}:{action:m.action},manifestPath:Ae(w),...a[2]===void 0?{}:{channelId:a[2]},json:s.bool("json"),installServer:dn})}case"plugins":{let m=s.str("ref"),w=s.str("name");return await Es({action:d,manifestPath:Ae(a[1]??""),rest:a.slice(2),...m===void 0?{}:{ref:m},...w===void 0?{}:{name:w},json:s.bool("json")})}case"agents":{let m=s.str("store");return await $t({manifestPaths:a.map((w)=>Ae(w)),...m===void 0?{}:{store:m},json:s.bool("json")})}case"restart":{let m=s.str("store");return await Ds({...d===void 0?{}:{manifestPath:u()},...m===void 0?{}:{store:m},json:s.bool("json")})}case"status":{let m=s.str("store");return await dr({...m===void 0?{}:{store:m},json:s.bool("json")})}case"logs":{let m=s.num("lines"),w=s.str("store");return await ke({action:"logs",...d===void 0?{}:{manifestPath:u()},...m===void 0?{}:{lines:m},follow:s.bool("follow"),truncate:s.bool("truncate"),...w===void 0?{}:{store:w},json:s.bool("json")})}case"serve":{let m=s.num("port"),w=s.str("host"),E=s.str("store");return await sr({manifestPaths:a.map((j)=>Ae(j)),...m===void 0?{}:{port:m},...w===void 0?{}:{host:w},...E===void 0?{}:{store:E},claim:s.bool("claim"),json:s.bool("json")})}case"keys":return await Jt({noEnhancedKeys:s.bool("no-enhanced-keys")});case"terminal-setup":return await cr({dryRun:s.bool("dry-run"),yes:s.bool("yes"),json:s.bool("json"),confirm:CA});case"remove":return await Fs({...d===void 0?{}:{ref:d},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:vo});case"stop":{let m=s.str("reason");return await Rn({...d===void 0?{}:{manifestPath:u()},dryRun:s.bool("dry-run"),...m===void 0?{}:{reason:m},...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"start":return await ar({manifestPath:u(),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")});case"web":{let{webCommand:m}=await import("./web-923c7f5e.js");return await m({action:d,...a[1]===void 0?{}:{manifestPath:Ae(a[1])},noOpen:s.bool("no-open"),...s.str("store")===void 0?{}:{store:s.str("store")},json:s.bool("json")})}case"credential":{let{credentialCommand:m}=await import("./credential-2sj7vsmw.js");return await m({action:d??"",...a[1]===void 0?{}:{keyId:a[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 m=s.num("lines");return await ke({action:d,...a[1]===void 0?{}:{manifestPath:Ae(a[1])},...m===void 0?{}:{lines:m},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 m=s.num("price");return await gs({manifestPath:Ae(a[1]),window:s.bool("window"),...m===void 0?{}:{price:m},write:s.bool("write"),yes:s.bool("yes"),json:s.bool("json")})}case"tools":return await ur({manifestPath:u(),warm:s.bool("warm"),json:s.bool("json")});default:throw new A({code:"cli_command_unwired",message:`Command "${o.name}" is declared but not wired up.`,hint:"Add a case for it in src/index.ts."})}}es();Vo();await va(process.argv.slice(2)).catch($a).then((n)=>yn(n));
529
460
 
530
- //# debugId=92EA07B9DCA0055664756E2164756E21
461
+ //# debugId=4A418E187444FB4464756E2164756E21
531
462
  //# sourceMappingURL=index.js.map