dispach 0.1.0
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.
- package/README.md +596 -0
- package/dist/App-dxqm39zx.js +11 -0
- package/dist/App-dxqm39zx.js.map +25 -0
- package/dist/ConfigEditor-7v5nebvy.js +6 -0
- package/dist/ConfigEditor-7v5nebvy.js.map +11 -0
- package/dist/KeyProbe-vjhmdpx6.js +5 -0
- package/dist/KeyProbe-vjhmdpx6.js.map +11 -0
- package/dist/Picker-jxaesaxy.js +5 -0
- package/dist/Picker-jxaesaxy.js.map +10 -0
- package/dist/SessionPicker-z2t0p4b5.js +5 -0
- package/dist/SessionPicker-z2t0p4b5.js.map +11 -0
- package/dist/SkillBrowser-yyf2gy0q.js +5 -0
- package/dist/SkillBrowser-yyf2gy0q.js.map +11 -0
- package/dist/WizardApp-12ndxgqv.js +5 -0
- package/dist/WizardApp-12ndxgqv.js.map +13 -0
- package/dist/agents.d.ts +9 -0
- package/dist/agents.d.ts.map +1 -0
- package/dist/browse.d.ts +63 -0
- package/dist/browse.d.ts.map +1 -0
- package/dist/client.d.ts +25 -0
- package/dist/client.d.ts.map +1 -0
- package/dist/client.js +34 -0
- package/dist/client.js.map +11 -0
- package/dist/components/App.d.ts +28 -0
- package/dist/components/App.d.ts.map +1 -0
- package/dist/components/Banner.d.ts +16 -0
- package/dist/components/Banner.d.ts.map +1 -0
- package/dist/components/Brandmark.d.ts +31 -0
- package/dist/components/Brandmark.d.ts.map +1 -0
- package/dist/components/CheckList.d.ts +38 -0
- package/dist/components/CheckList.d.ts.map +1 -0
- package/dist/components/CommandOutput.d.ts +29 -0
- package/dist/components/CommandOutput.d.ts.map +1 -0
- package/dist/components/ConfigEditor.d.ts +64 -0
- package/dist/components/ConfigEditor.d.ts.map +1 -0
- package/dist/components/HistorySearch.d.ts +23 -0
- package/dist/components/HistorySearch.d.ts.map +1 -0
- package/dist/components/KeyProbe.d.ts +36 -0
- package/dist/components/KeyProbe.d.ts.map +1 -0
- package/dist/components/LineCursor.d.ts +55 -0
- package/dist/components/LineCursor.d.ts.map +1 -0
- package/dist/components/Live.d.ts +17 -0
- package/dist/components/Live.d.ts.map +1 -0
- package/dist/components/Palette.d.ts +21 -0
- package/dist/components/Palette.d.ts.map +1 -0
- package/dist/components/Picker.d.ts +23 -0
- package/dist/components/Picker.d.ts.map +1 -0
- package/dist/components/Prompt.d.ts +20 -0
- package/dist/components/Prompt.d.ts.map +1 -0
- package/dist/components/Screen.d.ts +39 -0
- package/dist/components/Screen.d.ts.map +1 -0
- package/dist/components/SelectList.d.ts +34 -0
- package/dist/components/SelectList.d.ts.map +1 -0
- package/dist/components/SessionPicker.d.ts +26 -0
- package/dist/components/SessionPicker.d.ts.map +1 -0
- package/dist/components/SkillBrowser.d.ts +39 -0
- package/dist/components/SkillBrowser.d.ts.map +1 -0
- package/dist/components/Spinner.d.ts +13 -0
- package/dist/components/Spinner.d.ts.map +1 -0
- package/dist/components/StatusBar.d.ts +11 -0
- package/dist/components/StatusBar.d.ts.map +1 -0
- package/dist/components/SummaryCard.d.ts +11 -0
- package/dist/components/SummaryCard.d.ts.map +1 -0
- package/dist/components/TextField.d.ts +39 -0
- package/dist/components/TextField.d.ts.map +1 -0
- package/dist/components/Transcript.d.ts +23 -0
- package/dist/components/Transcript.d.ts.map +1 -0
- package/dist/components/WizardApp.d.ts +18 -0
- package/dist/components/WizardApp.d.ts.map +1 -0
- package/dist/components/WizardFrame.d.ts +19 -0
- package/dist/components/WizardFrame.d.ts.map +1 -0
- package/dist/config-yz0nz51b.js +24 -0
- package/dist/config-yz0nz51b.js.map +10 -0
- package/dist/config.d.ts +71 -0
- package/dist/config.d.ts.map +1 -0
- package/dist/credential-wgt4gvcz.js +19 -0
- package/dist/credential-wgt4gvcz.js.map +10 -0
- package/dist/credential.d.ts +68 -0
- package/dist/credential.d.ts.map +1 -0
- package/dist/daemon.d.ts +47 -0
- package/dist/daemon.d.ts.map +1 -0
- package/dist/editor.d.ts +81 -0
- package/dist/editor.d.ts.map +1 -0
- package/dist/hooks/useElapsed.d.ts +10 -0
- package/dist/hooks/useElapsed.d.ts.map +1 -0
- package/dist/hooks/useTerminalSize.d.ts +14 -0
- package/dist/hooks/useTerminalSize.d.ts.map +1 -0
- package/dist/hooks/useTurn.d.ts +41 -0
- package/dist/hooks/useTurn.d.ts.map +1 -0
- package/dist/index-2cvtz0fy.js +903 -0
- package/dist/index-2cvtz0fy.js.map +194 -0
- package/dist/index-3nwfz9jq.js +12 -0
- package/dist/index-3nwfz9jq.js.map +11 -0
- package/dist/index-6b7qvh1x.js +6 -0
- package/dist/index-6b7qvh1x.js.map +10 -0
- package/dist/index-6z0yr17z.js +12 -0
- package/dist/index-6z0yr17z.js.map +11 -0
- package/dist/index-7da4fqcr.js +7 -0
- package/dist/index-7da4fqcr.js.map +11 -0
- package/dist/index-8bmhd2hj.js +6 -0
- package/dist/index-8bmhd2hj.js.map +10 -0
- package/dist/index-9d011p3q.js +6 -0
- package/dist/index-9d011p3q.js.map +10 -0
- package/dist/index-9f9pp2ef.js +6 -0
- package/dist/index-9f9pp2ef.js.map +10 -0
- package/dist/index-9nsfs0vy.js +6 -0
- package/dist/index-9nsfs0vy.js.map +10 -0
- package/dist/index-9pj1ws0p.js +77 -0
- package/dist/index-9pj1ws0p.js.map +12 -0
- package/dist/index-b5wwtxzk.js +66 -0
- package/dist/index-b5wwtxzk.js.map +12 -0
- package/dist/index-b8zwg8a3.js +6 -0
- package/dist/index-b8zwg8a3.js.map +10 -0
- package/dist/index-bry9bzt3.js +427 -0
- package/dist/index-bry9bzt3.js.map +11 -0
- package/dist/index-bwckzbf8.js +6 -0
- package/dist/index-bwckzbf8.js.map +10 -0
- package/dist/index-cx3vz7sf.js +6 -0
- package/dist/index-cx3vz7sf.js.map +11 -0
- package/dist/index-e8n70sgj.js +6 -0
- package/dist/index-e8n70sgj.js.map +11 -0
- package/dist/index-fvhg0xyd.js +167 -0
- package/dist/index-fvhg0xyd.js.map +19 -0
- package/dist/index-gbnc99j8.js +14 -0
- package/dist/index-gbnc99j8.js.map +13 -0
- package/dist/index-h2yds678.js +7 -0
- package/dist/index-h2yds678.js.map +11 -0
- package/dist/index-j97vttdt.js +10 -0
- package/dist/index-j97vttdt.js.map +10 -0
- package/dist/index-jk0def33.js +6 -0
- package/dist/index-jk0def33.js.map +12 -0
- package/dist/index-jym27m75.js +6 -0
- package/dist/index-jym27m75.js.map +10 -0
- package/dist/index-mgdgx22q.js +10 -0
- package/dist/index-mgdgx22q.js.map +10 -0
- package/dist/index-mrtb5y08.js +6 -0
- package/dist/index-mrtb5y08.js.map +11 -0
- package/dist/index-my5cjx00.js +6 -0
- package/dist/index-my5cjx00.js.map +10 -0
- package/dist/index-qc2vrq9z.js +7 -0
- package/dist/index-qc2vrq9z.js.map +11 -0
- package/dist/index-rqbtm761.js +6 -0
- package/dist/index-rqbtm761.js.map +10 -0
- package/dist/index-rqzg861g.js +6 -0
- package/dist/index-rqzg861g.js.map +10 -0
- package/dist/index-t1xvacym.js +6 -0
- package/dist/index-t1xvacym.js.map +11 -0
- package/dist/index-xgqzk5cq.js +9 -0
- package/dist/index-xgqzk5cq.js.map +12 -0
- package/dist/index-xqyms08r.js +6 -0
- package/dist/index-xqyms08r.js.map +10 -0
- package/dist/index-yr25dnf5.js +6 -0
- package/dist/index-yr25dnf5.js.map +10 -0
- package/dist/index.d.ts +23 -0
- package/dist/index.d.ts.map +1 -0
- package/dist/index.js +527 -0
- package/dist/index.js.map +48 -0
- package/dist/init.d.ts +34 -0
- package/dist/init.d.ts.map +1 -0
- package/dist/keymap.d.ts +126 -0
- package/dist/keymap.d.ts.map +1 -0
- package/dist/keys.d.ts +17 -0
- package/dist/keys.d.ts.map +1 -0
- package/dist/lib/ambient.d.ts +69 -0
- package/dist/lib/ambient.d.ts.map +1 -0
- package/dist/lib/args.d.ts +33 -0
- package/dist/lib/args.d.ts.map +1 -0
- package/dist/lib/bootstrap.d.ts +84 -0
- package/dist/lib/bootstrap.d.ts.map +1 -0
- package/dist/lib/browse.d.ts +89 -0
- package/dist/lib/browse.d.ts.map +1 -0
- package/dist/lib/browser.d.ts +55 -0
- package/dist/lib/browser.d.ts.map +1 -0
- package/dist/lib/chat-frame.d.ts +156 -0
- package/dist/lib/chat-frame.d.ts.map +1 -0
- package/dist/lib/clipboard.d.ts +32 -0
- package/dist/lib/clipboard.d.ts.map +1 -0
- package/dist/lib/commands.d.ts +26 -0
- package/dist/lib/commands.d.ts.map +1 -0
- package/dist/lib/composer.d.ts +85 -0
- package/dist/lib/composer.d.ts.map +1 -0
- package/dist/lib/config-apply.d.ts +51 -0
- package/dist/lib/config-apply.d.ts.map +1 -0
- package/dist/lib/config-editor.d.ts +113 -0
- package/dist/lib/config-editor.d.ts.map +1 -0
- package/dist/lib/config-env.d.ts +110 -0
- package/dist/lib/config-env.d.ts.map +1 -0
- package/dist/lib/config-rows.d.ts +37 -0
- package/dist/lib/config-rows.d.ts.map +1 -0
- package/dist/lib/config-view.d.ts +133 -0
- package/dist/lib/config-view.d.ts.map +1 -0
- package/dist/lib/confirm.d.ts +86 -0
- package/dist/lib/confirm.d.ts.map +1 -0
- package/dist/lib/const.d.ts +213 -0
- package/dist/lib/const.d.ts.map +1 -0
- package/dist/lib/csi.d.ts +70 -0
- package/dist/lib/csi.d.ts.map +1 -0
- package/dist/lib/curated.d.ts +44 -0
- package/dist/lib/curated.d.ts.map +1 -0
- package/dist/lib/daemon-plan.d.ts +151 -0
- package/dist/lib/daemon-plan.d.ts.map +1 -0
- package/dist/lib/dotenv-edit.d.ts +30 -0
- package/dist/lib/dotenv-edit.d.ts.map +1 -0
- package/dist/lib/env.d.ts +10 -0
- package/dist/lib/env.d.ts.map +1 -0
- package/dist/lib/exit.d.ts +170 -0
- package/dist/lib/exit.d.ts.map +1 -0
- package/dist/lib/help.d.ts +10 -0
- package/dist/lib/help.d.ts.map +1 -0
- package/dist/lib/init-flow.d.ts +539 -0
- package/dist/lib/init-flow.d.ts.map +1 -0
- package/dist/lib/init-skills.d.ts +46 -0
- package/dist/lib/init-skills.d.ts.map +1 -0
- package/dist/lib/keyboard.d.ts +76 -0
- package/dist/lib/keyboard.d.ts.map +1 -0
- package/dist/lib/keys-view.d.ts +57 -0
- package/dist/lib/keys-view.d.ts.map +1 -0
- package/dist/lib/launchd.d.ts +151 -0
- package/dist/lib/launchd.d.ts.map +1 -0
- package/dist/lib/lifecycle.d.ts +126 -0
- package/dist/lib/lifecycle.d.ts.map +1 -0
- package/dist/lib/log-follow.d.ts +71 -0
- package/dist/lib/log-follow.d.ts.map +1 -0
- package/dist/lib/mouse.d.ts +84 -0
- package/dist/lib/mouse.d.ts.map +1 -0
- package/dist/lib/multiselect.d.ts +37 -0
- package/dist/lib/multiselect.d.ts.map +1 -0
- package/dist/lib/origins.d.ts +40 -0
- package/dist/lib/origins.d.ts.map +1 -0
- package/dist/lib/output.d.ts +29 -0
- package/dist/lib/output.d.ts.map +1 -0
- package/dist/lib/palette.d.ts +69 -0
- package/dist/lib/palette.d.ts.map +1 -0
- package/dist/lib/probe.d.ts +158 -0
- package/dist/lib/probe.d.ts.map +1 -0
- package/dist/lib/providers.d.ts +63 -0
- package/dist/lib/providers.d.ts.map +1 -0
- package/dist/lib/provision.d.ts +163 -0
- package/dist/lib/provision.d.ts.map +1 -0
- package/dist/lib/remove-plan.d.ts +120 -0
- package/dist/lib/remove-plan.d.ts.map +1 -0
- package/dist/lib/render.d.ts +78 -0
- package/dist/lib/render.d.ts.map +1 -0
- package/dist/lib/resume.d.ts +69 -0
- package/dist/lib/resume.d.ts.map +1 -0
- package/dist/lib/rows.d.ts +69 -0
- package/dist/lib/rows.d.ts.map +1 -0
- package/dist/lib/sandbox.d.ts +101 -0
- package/dist/lib/sandbox.d.ts.map +1 -0
- package/dist/lib/schema.d.ts +491 -0
- package/dist/lib/schema.d.ts.map +1 -0
- package/dist/lib/screen.d.ts +102 -0
- package/dist/lib/screen.d.ts.map +1 -0
- package/dist/lib/scroll.d.ts +64 -0
- package/dist/lib/scroll.d.ts.map +1 -0
- package/dist/lib/select.d.ts +23 -0
- package/dist/lib/select.d.ts.map +1 -0
- package/dist/lib/service-env.d.ts +38 -0
- package/dist/lib/service-env.d.ts.map +1 -0
- package/dist/lib/service.d.ts +102 -0
- package/dist/lib/service.d.ts.map +1 -0
- package/dist/lib/session-commands.d.ts +229 -0
- package/dist/lib/session-commands.d.ts.map +1 -0
- package/dist/lib/session-key.d.ts +55 -0
- package/dist/lib/session-key.d.ts.map +1 -0
- package/dist/lib/sessions-view.d.ts +31 -0
- package/dist/lib/sessions-view.d.ts.map +1 -0
- package/dist/lib/source-cache.d.ts +105 -0
- package/dist/lib/source-cache.d.ts.map +1 -0
- package/dist/lib/source.d.ts +281 -0
- package/dist/lib/source.d.ts.map +1 -0
- package/dist/lib/sources.d.ts +107 -0
- package/dist/lib/sources.d.ts.map +1 -0
- package/dist/lib/spawn.d.ts +56 -0
- package/dist/lib/spawn.d.ts.map +1 -0
- package/dist/lib/stdin-tap.d.ts +41 -0
- package/dist/lib/stdin-tap.d.ts.map +1 -0
- package/dist/lib/subcommand.d.ts +57 -0
- package/dist/lib/subcommand.d.ts.map +1 -0
- package/dist/lib/systemd.d.ts +60 -0
- package/dist/lib/systemd.d.ts.map +1 -0
- package/dist/lib/templates.d.ts +35 -0
- package/dist/lib/templates.d.ts.map +1 -0
- package/dist/lib/terminal.d.ts +98 -0
- package/dist/lib/terminal.d.ts.map +1 -0
- package/dist/lib/text-selection.d.ts +75 -0
- package/dist/lib/text-selection.d.ts.map +1 -0
- package/dist/lib/theme.d.ts +90 -0
- package/dist/lib/theme.d.ts.map +1 -0
- package/dist/lib/types.d.ts +467 -0
- package/dist/lib/types.d.ts.map +1 -0
- package/dist/lib/warnings.d.ts +79 -0
- package/dist/lib/warnings.d.ts.map +1 -0
- package/dist/lib/width.d.ts +39 -0
- package/dist/lib/width.d.ts.map +1 -0
- package/dist/lib/wizard.d.ts +95 -0
- package/dist/lib/wizard.d.ts.map +1 -0
- package/dist/lib/wordmark.d.ts +60 -0
- package/dist/lib/wordmark.d.ts.map +1 -0
- package/dist/lib/wrap.d.ts +74 -0
- package/dist/lib/wrap.d.ts.map +1 -0
- package/dist/memory.d.ts +25 -0
- package/dist/memory.d.ts.map +1 -0
- package/dist/model.d.ts +47 -0
- package/dist/model.d.ts.map +1 -0
- package/dist/plugins.d.ts +15 -0
- package/dist/plugins.d.ts.map +1 -0
- package/dist/remove.d.ts +52 -0
- package/dist/remove.d.ts.map +1 -0
- package/dist/run.d.ts +42 -0
- package/dist/run.d.ts.map +1 -0
- package/dist/schedules.d.ts +41 -0
- package/dist/schedules.d.ts.map +1 -0
- package/dist/serve.d.ts +41 -0
- package/dist/serve.d.ts.map +1 -0
- package/dist/sessions.d.ts +13 -0
- package/dist/sessions.d.ts.map +1 -0
- package/dist/skills.d.ts +80 -0
- package/dist/skills.d.ts.map +1 -0
- package/dist/soul.d.ts +19 -0
- package/dist/soul.d.ts.map +1 -0
- package/dist/sources.d.ts +32 -0
- package/dist/sources.d.ts.map +1 -0
- package/dist/start.d.ts +26 -0
- package/dist/start.d.ts.map +1 -0
- package/dist/stop.d.ts +58 -0
- package/dist/stop.d.ts.map +1 -0
- package/dist/terminal-setup.d.ts +31 -0
- package/dist/terminal-setup.d.ts.map +1 -0
- package/dist/tools.d.ts +22 -0
- package/dist/tools.d.ts.map +1 -0
- package/dist/transcript.d.ts +124 -0
- package/dist/transcript.d.ts.map +1 -0
- package/dist/validate.d.ts +36 -0
- package/dist/validate.d.ts.map +1 -0
- package/dist/web-w7r68df1.js +14 -0
- package/dist/web-w7r68df1.js.map +11 -0
- package/dist/web.d.ts +36 -0
- package/dist/web.d.ts.map +1 -0
- package/dist/wire.d.ts +10 -0
- package/dist/wire.d.ts.map +1 -0
- package/dist/wire.js +33 -0
- package/dist/wire.js.map +10 -0
- package/dist/workspace.d.ts +19 -0
- package/dist/workspace.d.ts.map +1 -0
- package/package.json +78 -0
package/dist/index.js
ADDED
|
@@ -0,0 +1,527 @@
|
|
|
1
|
+
#!/usr/bin/env node
|
|
2
|
+
import{Ot,e,E,t,De,on,Ae,ct,Ue,H,sn,gr,yr,me,wr,je,ge,an,ut,T,x,A,dn,Ke,ht,cn,He,_,M,Sr,L,un,Er,Tr,p,Ao}from"./index-2cvtz0fy.js";import{Ce,Cn,Pn,Mn}from"./index-b5wwtxzk.js";import{I,O,W,C,q,P,ar,Je,lr,jt,V,Fr,Ur,jr,In,ce,Qe,be,On,ve,et,zr,Br}from"./index-fvhg0xyd.js";import{Fo}from"./index-jk0def33.js";import{vt}from"./index-t1xvacym.js";import{at,At,nn,Rt,rn,lt,Vn,It,Le,Ee,dt,Yn}from"./index-bry9bzt3.js";import{Tt,le,$t}from"./index-yr25dnf5.js";import{Xt,Jt,xt,Gn,st,po,go,yo}from"./index-3nwfz9jq.js";import"./index-qc2vrq9z.js";import{sr,Or,Nr,Cr,Pr}from"./index-9pj1ws0p.js";import{Ve,Rr}from"./index-j97vttdt.js";import{Mr}from"./index-6b7qvh1x.js";import{Lr,Rn,Dr,Oe,Ne,yt,wt,Ye,Xe,Ut}from"./index-rqzg861g.js";import{zt,he,Kr,b,Hr,J,ue,Nn,Wr,Y,ie}from"./index-xgqzk5cq.js";import{xe,ee,z,w,Ht,Wt,no,B,te}from"./index-7da4fqcr.js";import{jn}from"./index-8bmhd2hj.js";import{ko,So}from"./index-9f9pp2ef.js";import{Eo}from"./index-xqyms08r.js";import{Z}from"./index-9nsfs0vy.js";import{l,m,d,c,pt,Qn,mt,We}from"./index-mgdgx22q.js";import{Mo,Do}from"./index-9d011p3q.js";import{vn,Go,we,U,Sn,$n,n,s,Ft,is}from"./index-my5cjx00.js";async function Nt(r){let o=await L.create({agents:[...r.manifestPaths],toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p(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 ${Qn(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 Oo,existsSync as pr,mkdirSync as _o,openSync as Co,readFileSync as No,readSync as Lo,statSync as hr}from"node:fs";import{homedir as zn}from"node:os";import{dirname as bn,join as br,resolve as jo}from"node:path";function Lt(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 fo(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 Mt(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(...fo(r.binary)),o}function mo(r,o="serving on"){let a=r.lastIndexOf(o);return a===-1?r:r.slice(a)}function Kt(r){let o=mo(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 ho=3;function Dt(r,o){let a=wo(o),u=[];if(o.pid!==void 0)u.push({label:"state",value:`running · pid ${o.pid}`,...o.uptimeMs===void 0?{}:{note:`up ${Qn(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:`(${pt(o.stderrBytes)})`}});return{verdict:a,healthy:a==="running",headline:a==="restart-loop"?`${r} — RESTART LOOP`:`${r} — ${bo(a)}`,rows:u,wantsStderrTail:a==="restart-loop"||a==="failed"||a==="installed-idle"}}function wo(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)>=ho&&(r.lastExitCode??0)!==0)return"restart-loop";if((r.lastExitCode??0)!==0)return"failed";return"installed-idle"}function bo(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 Bt(r){return`${r.headline}
|
|
5
|
+
${l(r.rows)}`}function fn(r){return["HOME","PATH","TMPDIR",`${r}SERVICE`,`${r}HOME`]}class Hn 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 mn(r,o,a){let u=fn(o);for(let i of Object.keys(r))if(!u.includes(i))throw new Hn(i,u,a)}var vo={Crashed:!0},Be=30,Ge=30;function pn(r,o){return`${r}.agent.${o}`}function Fe(r){return`${r}.server`}function Pe(r){return r.replaceAll("&","&").replaceAll("<","<").replaceAll(">",">").replaceAll('"',""").replaceAll("'","'")}function hn(r,o){mn(r.environment,o,"launchd");let a=r.programArguments.map((f)=>` <string>${Pe(f)}</string>`).join(`
|
|
6
|
+
`),u=Object.entries(r.environment).map(([f,h])=>` <key>${Pe(f)}</key>
|
|
7
|
+
<string>${Pe(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)=>` ${Pe(f)}`).join(`
|
|
12
|
+
`)}
|
|
13
|
+
-->
|
|
14
|
+
<plist version="1.0">
|
|
15
|
+
<dict>
|
|
16
|
+
<key>Label</key>
|
|
17
|
+
<string>${Pe(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
|
+
<${vo.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>${Pe(r.workingDirectory)}</string>
|
|
37
|
+
<key>StandardOutPath</key>
|
|
38
|
+
<string>${Pe(r.stdoutPath)}</string>
|
|
39
|
+
<key>StandardErrorPath</key>
|
|
40
|
+
<string>${Pe(r.stderrPath)}</string>
|
|
41
|
+
<key>EnvironmentVariables</key>
|
|
42
|
+
<dict>
|
|
43
|
+
${u}
|
|
44
|
+
</dict>
|
|
45
|
+
</dict>
|
|
46
|
+
</plist>
|
|
47
|
+
`}function Gt(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 qt(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 Vt(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 $o(r,o){if(o<r)return{from:0,to:o,truncated:!0};return{from:r,to:o,truncated:!1}}async function Yt(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=$o(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 Po,mkdirSync as Wn,readdirSync as tr,rmSync as rr,writeFileSync as or}from"node:fs";import{basename as Ro,dirname as yn,join as nr}from"node:path";import{join as Qt}from"node:path";function Zt(r,o,a=process.env){let u=a.XDG_CONFIG_HOME,i=u===void 0||u===""?Qt(o,".config"):u;return Qt(i,"systemd","user",`${r}.service`)}function Bn(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 xo(r){if(!/[\s"\\]/.test(r))return r;return`"${r.replaceAll("\\","\\\\").replaceAll('"',"\\\"")}"`}function gn(r,o){mn(r.environment,o,"systemd");for(let f of r.programArguments)Bn(f,"ExecStart");Bn(r.workingDirectory,"WorkingDirectory");for(let[f,h]of Object.entries(r.environment))Bn(h,`Environment=${f}`);let a=r.programArguments.map(xo).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 er(r,o){return["systemctl --user daemon-reload",`systemctl --user enable --now ${r}`,`loginctl enable-linger ${o}`]}var Io=6000,To=200,ir=(r,o)=>{let a=Eo({command:r,args:o});return{code:a.code,stdout:a.stdout,stderr:a.stderr}};function Me(r,o){if(r==="darwin")return new ur(o);if(r==="linux")return new cr(o);throw qn(r)}function dr(r){return r==="darwin"}function qn(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 cr{id="systemd";#r;#e;#s;#t;constructor(r){this.#r=r.home,this.#e=r.envPrefix,this.#s=r.exec??ir,this.#t=r.env??process.env}unitPath(r){return Zt(r,this.#r,this.#t)}install(r){let o=this.unitPath(r.label),a=gn(r,this.#e);Wn(yn(o),{recursive:!0}),or(o,a,{encoding:"utf8",mode:384})}uninstall(r){rr(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:Po(this.unitPath(r)),disabled:!1,liveness:!1}}labels(r){try{return tr(yn(this.unitPath(r))).filter((o)=>o.startsWith(r)&&o.endsWith(".service")).map((o)=>o.slice(0,-8)).sort()}catch{return[]}}followUp(r){return er(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??Ro(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 ur{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??ir}unitPath(r){return nr(this.#r,"Library","LaunchAgents",`${r}.plist`)}install(r){let o=this.unitPath(r.label),a=hn(r,this.#s);if(Wn(yn(o),{recursive:!0}),Wn(yn(r.stdoutPath),{recursive:!0}),this.#n(["bootout",`${this.#e}/${r.label}`],{tolerate:!0}),this.#o(r.label),or(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()+Io;while(Date.now()<o){if(this.#t("launchctl",["print",`${this.#e}/${r}`]).code!==0)return;Atomics.wait(new Int32Array(new SharedArrayBuffer(4)),0,0,To)}}uninstall(r){this.#n(["bootout",`${this.#e}/${r}`],{tolerate:!0}),this.#n(["enable",`${this.#e}/${r}`],{tolerate:!0}),rr(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=Vt(this.#t("launchctl",["print-disabled",this.#e]).stdout).includes(r);if(o.code!==0)return{installed:!1,disabled:a,liveness:!0};let u=qt(o.stdout);return{installed:!0,disabled:a,liveness:!0,print:u,...u.pid===void 0?{}:{pid:u.pid}}}labels(r){let o=Gt(this.#t("launchctl",["list"]).stdout).map((u)=>u.label).filter((u)=>u.startsWith(r)),a=[];try{a=tr(nr(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 fr=["install","uninstall","start","stop","restart","status","logs"];async function ze(r){if(!fr.includes(r.action))throw new t({code:"cli_daemon_unknown_action",message:`daemon takes one of ${fr.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=Uo();if(a!=="darwin"&&a!=="linux"&&o!=="status")throw qn(a,Bo(u,r.manifestPath??"<manifest>"));let i=a==="darwin"||a==="linux"?Me(a,{home:zn(),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 Jo(r,i);case"install":return await Ko(r,u,i);case"uninstall":return Vo(r,i);case"start":case"stop":case"restart":return Xo(o,i);case"logs":return await Qo(r)}}async function Ko(r,o,a){let u=Fe(e.slug),i=Ht(r.env),f=(a?.labels(`${e.slug}.agent.`)??[]).filter((y)=>y!==u),h=[...Mt({binary:o,retiring:f,servedElsewhere:(await yt(r.store)).map((y)=>({agentId:y.agentId,pid:y.pid,mode:y.mode}))}),...B(r.env).flatMap((y)=>{let S=qo(y.dir);return Lt({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:Wo(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"?gn(g,e.envPrefix):hn(g,e.envPrefix)),h.length>0)process.stderr.write(mr(h));return n}for(let y of f)a?.uninstall(y);if(h.length>0)process.stdout.write(mr(h));_o(bn(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:`${qe(o.execPath)} … serve`},{label:"hosts",value:"every agent in the sandbox that is not stopped"},{label:"logs",value:qe(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 Uo(){let r=Xn(process.execPath),o=Xn(process.argv[1]??""),a=Ho(bn(o));return{execPath:r,scriptPath:o,...a===void 0?{}:{gitRoot:a}}}function Xn(r){try{return Ot("node:fs").realpathSync(r)}catch{return r}}function Ho(r){let o=r;for(let a=0;a<40;a+=1){if(pr(br(o,".git")))return o;let u=bn(o);if(u===o)return;o=u}return}function Bo(r,o){return`ExecStart=${r.execPath} ${r.scriptPath} serve ${o} --store ${w()}`}function Wo(r){let o=zn(),u=[bn(Xn(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 qo(r){try{return hr(br(r,".env")).mode}catch{return}}function mr(r){return`${r.map((o)=>`${o.severity==="block"?"refused":"warning"}: ${o.message}
|
|
96
|
+
hint: ${o.hint}`).join(`
|
|
97
|
+
|
|
98
|
+
`)}
|
|
99
|
+
`}function Vo(r,o){let a=Fe(e.slug),u=Ht(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:qe(u.err)},{label:"agents",value:"unchanged — nothing was switched off"}])}
|
|
102
|
+
`),n}function Xo(r,o){let a=Fe(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 Jo(r,o){let a=Fe(e.slug),u=await yt(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]:[vr(r.manifestPath)],f=await Promise.all(i.map((v)=>Yo(v,o,{...v===a?{label:a}:{},logs:v===a?Ht(r.env):Wt(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 zo()).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(`${Bt(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 zo(){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 Yo(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 K=await M.open({path:a.store??w()});g=await K.leases.get(a.leaseOf??r),await K.close()}catch{g=void 0}if(g!==void 0&&!_(g.pid))g=void 0;let v=f?.print?.stderrPath??h.err,k=wn(v),y={installed:i!==void 0&&pr(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:qe(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=Dt(r,y),R=Kt(Jn(h.out,200));return{agentId:r,report:S,tail:S.wantsStderrTail?Jn(v,20):"",attention:R}}async function Qo(r){let o=r.manifestPath===void 0?void 0:vr(r.manifestPath),a=o??Fe(e.slug),u=o===void 0?Ht(r.env):Wt(o);if(r.truncate===!0){for(let f of[u.out,u.err])try{Ot("node:fs").writeFileSync(f,"")}catch{}return process.stdout.write(`${a} — logs truncated
|
|
122
|
+
`),n}let i=Jn(u.err,r.lines??40);if(process.stdout.write(i===""?`${qe(u.err)} is empty
|
|
123
|
+
`:`${i}
|
|
124
|
+
`),r.follow!==!0)return n;return await Yt([{path:u.err,label:"stderr"},{path:u.out,label:"stdout"}],Zo(),{offsets:{[u.err]:wn(u.err)??0,[u.out]:wn(u.out)??0},intervalMs:is}),n}function Zo(){let r=!1,o,a=()=>{r=!0,o?.()};return process.on("SIGINT",a),b(()=>{process.off("SIGINT",a)}),{sizeOf:(u)=>wn(u),read:(u,i,f)=>{try{let h=Co(u,"r");try{let g=Buffer.alloc(f-i),v=Lo(h,g,0,g.length,i);return g.subarray(0,v).toString("utf8")}finally{Oo(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 vr(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 qe(r){return mt(jo(r),zn())}function wn(r){try{return hr(r).size}catch{return}}function Jn(r,o){try{let a=No(r,"utf8").trimEnd();if(a==="")return"";return a.split(`
|
|
125
|
+
`).slice(-o).join(`
|
|
126
|
+
`)}catch{return""}}var Zd=fn(e.envPrefix);import{basename as mi,dirname as pi,join as Se,resolve as hi}from"node:path";import{rmSync as ei}from"node:fs";import{isAbsolute as $r,join as ni,resolve as kr}from"node:path";var ti=3;async function xr(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=V(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 Qe(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(...be(y,r.env))}for(let y of i)process.stdout.write(c(`could not fetch ${y}
|
|
129
|
+
`));if(u.length===0){process.stdout.write(`${c("no source could be read, so no skill was installed — the directory is there and empty")}
|
|
130
|
+
${c("`sources update` reports why; `sources search <words>` when it works",4)}
|
|
131
|
+
`);return}let f=ri(o,u);if(f.length===0){process.stdout.write(`${c(`nothing in ${u.length} skills matches those words, so none was installed`)}
|
|
132
|
+
${c("the ranking is lexical: try the words a skill's own description would use, with `sources search`",4)}
|
|
133
|
+
`);return}let h=f[0],g=`${h.source}/${h.skill}`;if(process.stdout.write(`${c(`best of ${u.length}: ${g}`)}
|
|
134
|
+
`),f.length>1)process.stdout.write(`${c(`also matched: ${f.slice(1,1+ti).map((y)=>`${y.source}/${y.skill}`).join(", ")}`,4)}
|
|
135
|
+
`);if(process.stdout.write(`
|
|
136
|
+
`),ve({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=si(r.manifestPath,r.envOverlay);if(k!==void 0)oi(r.manifestPath,h.skill,r.envOverlay),process.stdout.write(`
|
|
137
|
+
${d(`${g} was removed again: it does not load on this machine`)}
|
|
138
|
+
${c(k,4)}
|
|
139
|
+
${c("everything else is fine; `sources search` for one that needs no extra runtime",4)}
|
|
140
|
+
`)}function ri(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 ht(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}function si(r,o){try{let a=x(r,{knownProviders:W,knownChannels:q,...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);Ke({dir:$r(u.dir)?u.dir:kr(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 oi(r,o,a){try{let u=x(r,{knownProviders:W,knownChannels:q,...a===void 0?{}:{env:{...process.env,...a}}}),i=u.manifest.skills;if(i===void 0)return;let f=$r(i.dir)?i.dir:kr(u.dir,i.dir);ei(ni(f,o),{recursive:!0,force:!0}),On(f,o)}catch{}}import{existsSync as ii,mkdirSync as ai,writeFileSync as di}from"node:fs";import{dirname as li,join as kn,resolve as ci}from"node:path";var xn={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 Zn(r,o,a){let u=[];for(;;){let i=Le(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=Ee(i.step,i.fallback);if(f.ok)r[i.step]=f.value}if(u.length>0){let i=u.map((f)=>xn[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 nt(r,o){let a=r,u=at(a.preset),i=a.apiKeyEnv??u?.apiKeyEnv,f=a.dir??At(a.dirChoice,a.name,o);if(f===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:a.server,skills:a.skills,...a.skillsSearch===void 0||a.skillsSearch===""?{}:{skillsSearch:a.skillsSearch},...a.skillsPick===void 0||a.skillsPick===""?{}:{skillsPick:a.skillsPick},daemon:a.daemon,...a.server==="local"?{serverToken:ui()}:{},...i===void 0?{}:{apiKeyEnv:i},...a.apiKey===void 0||a.apiKey===""?{}:{apiKey:a.apiKey},...a.dirChoice===void 0?{}:{dirChoice:a.dirChoice},dir:f}}function ui(){let r=new Uint8Array(32);return crypto.getRandomValues(r),[...r].map((o)=>o.toString(16).padStart(2,"0")).join("")}function tt(r,o){let a=o.map((u)=>kn(r,u.relPath)).filter((u)=>ii(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=kn(r,u.relPath);ai(li(i),{recursive:!0}),di(i,u.contents,{encoding:"utf8",...u.relPath===".env"?{mode:384}:{}})}}var Ar=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."}]]),rt=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 _r(r){let o=Ee(r.step,r.fallback);return o.ok?o.value:r.fallback}function fi(r,o){let a=rt.get(r.step);return{step:r.step,prompt:r.prompt,fallback:_r(r),optional:r.optional===!0,secret:It.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 Ir=64;function Gr(r){let o=new Map,a=new Set,u=(f,h)=>{let g={...f},v=[];for(let k=0;k<Ir;k+=1){let y=Le(g,r);if(y===void 0)break;let S=_r(y);if(!Ar.has(y.step)&&!o.has(y.step))o.set(y.step,fi(y,h));for(let R of y.options??[]){if(R.value===S)continue;if(rt.get(y.step)?.has(R.value)===!0)continue;v.push({seed:{...g,[y.step]:R.value},opened:{step:y.step,value:R.value}})}g[y.step]=S}return v},i=[...u({})];for(let f=0;f<Ir&&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)=>Vn.indexOf(f.step)-Vn.indexOf(h.step))}function qr(r){let o={};for(let[f,h]of Object.entries(r.answers)){let g=f;if(!(g in xn))throw new t({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 v=Ar.get(g);if(v!==void 0)throw new t({code:v.code,message:`"${f}" cannot be set over the API.`,hint:v.hint,field:f});let k=rt.get(g)?.get(h.trim().toLowerCase());if(k!==void 0)throw new t({code:k.code,message:`${f} is ${JSON.stringify(h)}, which this runtime cannot do over the API.`,hint:k.hint,field:f});let y=Ee(g,h);if(!y.ok)throw new t({code:"provision_answer_invalid",message:`${f} is ${JSON.stringify(h)}, which ${y.reason}`,hint:"GET /v1/provision lists every step with its prompt, its default and its choices, generated from the same walk the terminal wizard uses.",field:f});o[g]=y.value}Zn(o,"this is the provisioning API",r.defaults);let a=nt(o,r.defaults),u=ci(kn(r.defaults.agentDirBase,a.name)),i=Yn({...a,dir:u});return tt(u,i),{agentId:a.name,dir:u,manifestPath:kn(u,"agent.yaml"),files:i.map((f)=>f.relPath)}}function gi(r){if(r.web!=="search")return;return nn(r.webBackend??"tavily")?.apiKeyEnv}async function Vr(r){let o=await Xr(r);if(o.kind==="aborted")return process.stdout.write(`nothing written
|
|
141
|
+
`),n;return o.kind==="failed"?o.code:n}async function ot(r){return Xr(r)}async function Xr(r){let o=wi(r),a=ie({json:!1,plain:r.plain===!0,oneShot:!1}),u=a.mode==="rich"&&r.yes!==!0,i={agentDirBase:z()};if(u){let j=await bi(o,i);if(j===void 0)return{kind:"aborted"};Object.assign(o,j)}else Zn(o,r.yes===!0?"--yes was passed":a.because,i);let f=nt(o,i),h=hi(process.cwd(),f.dir),g=no(h);if(g!==void 0)process.stderr.write(`${g}
|
|
142
|
+
`);let v=Se(h,"agent.yaml"),k=Yn(f);tt(h,k);let y=f.apiKeyEnv,S=y!==void 0&&f.apiKey===void 0&&(process.env[y]===void 0||process.env[y]===""),R=S&&y!==void 0?{[y]:"(pending)"}:void 0,K=!1;try{let j=x(Se(h,"agent.yaml"),{knownProviders:W,knownChannels:q,...S?{env:{...process.env,[y]:"(pending)"}}:{}}),N=H(j.manifest.model.main.id,j.manifest.model.main.capabilities),{workspace:oe,warnings:fe}=He(j,N.promptStyle),ae=Ae(oe,j.manifest.context.rules);if(ae!==void 0&&j.manifest.context.rules.onExceed==="fail")throw ae;K=fe.some((D)=>D.code==="soul_distilled")}catch(j){if(j instanceof t)return process.stderr.write(`init wrote ${k.length} files to ${h}, but the result does not load:
|
|
143
|
+
${j.format()}
|
|
144
|
+
`),{kind:"failed",code:s};throw j}if(process.stdout.write(`wrote ${k.length} files to ${h} — validated ok
|
|
145
|
+
`),f.skills==="find"){let j=(f.skillsPick??"").split(",").map((N)=>N.trim()).filter((N)=>N!=="");if(j.length>0)zr(j,v,{...R===void 0?{}:{envOverlay:R}});else if(!u)await xr({answers:f,manifestPath:v,...R===void 0?{}:{envOverlay:R}})}let X=!1;if(f.daemon==="service"){process.stdout.write(`
|
|
146
|
+
`);try{X=await ze({action:"install",manifestPath:v})===n}catch(j){process.stderr.write(`the background service was not installed: ${j instanceof t?j.message:String(j)}
|
|
147
|
+
`)}}return process.stdout.write(vi(f,h,K,X)),{kind:"ok",manifestPath:Se(h,"agent.yaml")}}function yi(r){if(r===void 0)return[];if(lt.some((o)=>o.value===r))return[["skills",r]];return[["skills","find"],["skillsSearch",r]]}function wi(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],...yi(r.skills),["daemon",r.daemon],["dir",r.dir]];for(let[u,i]of a){if(i===void 0)continue;let f=Ee(u,i);if(!f.ok)throw new t({code:"cli_init_flag_invalid",message:`${xn[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 bi(r,o){let[{render:a},{createElement:u},{WizardApp:i}]=await Promise.all([import("ink"),import("react"),import("./WizardApp-12ndxgqv.js")]),f;zt();let h=a(u(i,{title:`${e.name} ${A}`,given:r,defaults:o,onDone:(g)=>{f=g}}),{exitOnCtrlC:!1,...Y()});return b(()=>h.unmount()),await h.waitUntilExit(),h.unmount(),f}function vi(r,o,a,u=!1){let f=pi(o)===z()?mi(o):Se(o,"agent.yaml"),h=Se(o,"agent.yaml"),g=[];if(r.apiKeyEnv!==void 0&&r.apiKey===void 0)g.push(`Add your key: edit ${Se(o,".env")} and set ${r.apiKeyEnv}=`);let v=gi(r);if(v!==void 0&&r.webKey===void 0)g.push(`Add your search key: edit ${Se(o,".env")} and set ${v}= — web_fetch works without it, web_search does not`);if(dt(r)&&r.composioKey===void 0)g.push(`Add your Composio key: edit ${Se(o,".env")} and set ${Rt}=`);if(r.telegram==="connected"&&r.telegramToken===void 0)g.push(`Add your bot token: message @BotFather with /newbot, then edit ${Se(o,".env")} and set ${rn}=`);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(dt(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?`
|
|
151
|
+
this model ships SOUL.compact.md — the full SOUL.md needs a 200k+ window on a
|
|
152
|
+
frontier-class model, and activates automatically if you upgrade.
|
|
153
|
+
`:""}${S}
|
|
154
|
+
`+g.map((K,X)=>` ${X+1}. ${K}
|
|
155
|
+
`).join("")}var En=16;function Tn(r=process.stdin){let o=[],a=[],u=(i)=>{let f=typeof i==="string"?i:i.toString("utf8");if(a.push(f),a.length>En)a.splice(0,a.length-En);if(o.push(...Mo(f)),o.length>En)o.splice(0,o.length-En)};return r.on("data",u),{correct:(i,f)=>Do(i,f,o),takeRaw:()=>a.shift(),close:()=>{r.off("data",u)}}}var Jr=[{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 An(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 _n(r){return Jr.find((o)=>o.id===r)}function Yr(){return Jr}function Qr(r,o){return o.marker!==void 0&&r.includes(o.marker)}function Zr(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}
|
|
160
|
+
]
|
|
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 es(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=Y(r.noEnhancedKeys),u=a.kittyKeyboard!==void 0,i=An(process.env),f=_n(i)?.name??i,[{render:h},{createElement:g},{KeyProbe:v}]=await Promise.all([import("ink"),import("react"),import("./KeyProbe-vjhmdpx6.js")]),k=()=>{},y=new Promise((K)=>{k=K}),S=Tn();b(()=>{S.close()}),he(),process.stdout.write(we);let R=h(g(v,{columns:Z(process.stdout.columns,U),asked:u,terminal:f,takeRaw:S.takeRaw,correctKeys:S.correct,onDone:k}),{exitOnCtrlC:!1,...a});return b(()=>R.unmount()),await y,R.unmount(),S.close(),J(),await ue(),n}import{existsSync as $i}from"node:fs";function ki(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($i("/.dockerenv")||o.container!==void 0)return"in-container";if(o.CI!==void 0)return"in-ci";return}async function ns(r){let o=ki(r);if(o!==void 0)return{kind:"skipped",reason:o};if((await yt(r.store)).length>0)return{kind:"already"};let u=r.platform??process.platform;if(!dr(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 ts(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 Si=24,it=22;function ft(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 rs(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(Si)}${r.help}${u}`}var ss=`Session keys are {channel}:{peerId}[:{thread}] | A bare word is refused, because outbound
|
|
168
|
+
delivery reads the channel back out of the key.`;function xi(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 gt(r){if(r!==void 0){let a=[r.summary,"","usage:",` ${ft(r)} [flags]`,...xi(r),"","flags:",...$t(r).map(rs)];if(r.flags.some((u)=>u.name==="session"))a.push("",ss);return`${a.join(`
|
|
169
|
+
`)}
|
|
170
|
+
`}let o=Math.max(...le.map((a)=>ft(a).length))+2;return`${[`${e.name} — a lightweight, model-agnostic agent runtime`,"","usage:",...le.map((a)=>` ${ft(a).padEnd(o)}${a.summary}`),` ${e.slug} --version`,` ${e.slug} --help`,"",`Per-command flags: ${e.slug} <command> --help`,"","global flags:",...Tt.map(rs),"",ss,"","environment:",` ${`${e.envPrefix}BRAND`.padEnd(it)}rebrand every derived path, env prefix, and apiVersion`,` ${"NO_COLOR".padEnd(it)}set to anything to force plain output`,` ${"DEBUG".padEnd(it)}print stack traces on failure`].join(`
|
|
171
|
+
`)}
|
|
172
|
+
`}var Ei=[{name:"ExperimentalWarning",contains:"SQLite is an experimental feature",because:"node:sqlite is a declared soft-compat target with an adapter and a dual-runtime test suite; the experimental status is the reason the adapter exists, not news about this run."}];function Pi(r,o){return Ei.some((a)=>a.name===r&&o.includes(a.contains))}function Ri(r){return r.execArgv.includes("--trace-warnings")||(r.nodeOptions??"").includes("--trace-warnings")}var os;function as(r={execArgv:process.execArgv,nodeOptions:process.env.NODE_OPTIONS}){if(os)return;if(Ri(r))return;let o=process.emitWarning;os=o,process.emitWarning=(a,...u)=>{let i=typeof a==="string"?Ii(u):a.name,f=typeof a==="string"?a:a.message;if(Pi(i,f))return;Reflect.apply(o,process,[a,...u])}}function Ii(r){let o=r[0];return typeof o==="string"?o:"Warning"}var ds=96;async function cs(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([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)=>ls(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(ls(v,i.carried),g)} ${$e(v.passage.at.slice(0,10),10)} ${k}${Ti(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 Ti(r){let o=r.replace(/\s+/g," ").trim();return o.length<=ds?o:`${o.slice(0,ds-1)}…`}function $e(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function ls(r,o){return r.passage.source===o?`${r.passage.source} *`:r.passage.source}var Ai=["context_length","context_window","max_context_length","max_model_len"],Oi=[["prompt_cache_hit_tokens",(r)=>r.prompt_cache_hit_tokens],["prompt_tokens_details.cached_tokens",(r)=>{let o=r.prompt_tokens_details;return Fn(o)?o.cached_tokens:void 0}],["cache_read_input_tokens",(r)=>r.cache_read_input_tokens]];function Fn(r){return typeof r==="object"&&r!==null&&!Array.isArray(r)}function bt(r){if(typeof r!=="number"||!Number.isFinite(r))return;if(!Number.isInteger(r)||r<=0)return;return r}function us(r,o){let a=Fn(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(!Fn(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 Ai){let k=bt(f[v]);if(k!==void 0)return{technique:"metadata",tokens:k,bound:"ceiling",detail:`GET /models published ${v}: ${k}`}}return}return}function kt(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=bt(Number(i[1].replaceAll(/[,_]/g,"")));if(f!==void 0)a.push(f)}if(a.length===0)return;return Math.max(...a)}function fs(r){if(!Fn(r))return;let o=bt(r.prompt_tokens)??0;for(let[a,u]of Oi){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 ms(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 Ze(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 ps(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 hs(r,o,a){return`measured ${o} against ${r} — ${a}`}function gs(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 _i=2000000000,ys=1024,bs=8192,vs=2097152;function $s(r){return"context ".repeat(Math.max(1,r))}async function en(r){let o=await r.text();try{return{text:o,json:JSON.parse(o)}}catch{return{text:o,json:void 0}}}function ks(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 Ci(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 en(u),f=us(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 Ni(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:_i})}),{text:i,json:f}=await en(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=ks(f,i.slice(0,400)),g=kt(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 ws(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 en(u),f=typeof i==="object"&&i!==null?i.usage:void 0;return fs(f)}async function Fi(r,o,a){let u=`${$s(ys)}
|
|
188
|
+
Reply with the single character x.`;try{let i=await ws(r,o,u),f=await ws(r,o,u);return ms(i,f,ys)}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 Li(r,o,a){let u=bs,i=0;while(u<=vs){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:$s(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 en(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 en(f),v=kt(ks(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 ji(r,o){let a=Ze(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[m(` ${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:",ps(r.modelId,a.tokens,r.outputCeiling).split(`
|
|
189
|
+
`).map((h)=>` ${h}`).join(`
|
|
190
|
+
`)]].join(`
|
|
191
|
+
`)}async function Ss(r){let o=r.fetch??globalThis.fetch;try{let a=x(r.manifestPath,{knownProviders:W,knownChannels:q,env:p([r.manifestPath])}),{manifest:u}=a,i=me(u).filter((v)=>v.role===v.configuredAs),f=!1;if(r.window){let v=gs(bs,vs),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}.
|
|
192
|
+
That is an upper bound: the search stops at the first refusal, and the refused request generates nothing.
|
|
193
|
+
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 Ve("spend it?"),process.stdout.write(f?`
|
|
195
|
+
`:`
|
|
196
|
+
Skipping the search. The free techniques below still run — re-run with --window --yes to search without asking.
|
|
197
|
+
|
|
198
|
+
`)}let h=[];for(let v of i){let k=u.model[v.role]??u.model.main,y={chat:sn(k.baseUrl),models:gr(k.baseUrl),headers:yr(k.apiKeyEnv,a.env,`model.${v.role}`),modelId:k.id},S=[],R=[],K=await Ci(y,o,S);if(K!==void 0)R.push(K);let X=await Ni(y,o,S);if(X.window!==void 0)R.push(X.window);let j=await Fi(y,o,S);if(f){let N=await Li(y,o,S);if(N!==void 0)R.push(N)}h.push({role:v.role,modelId:k.id,baseUrl:k.baseUrl,declared:v.window.contextWindow,declaredSource:v.window.source,findings:R,cache:j,outputCeiling:X.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 Mi(a.path,h):{written:[],refused:[]};return process.stdout.write([`probed ${u.id} · ${h.length} role${h.length===1?"":"s"}`,...h.map((v)=>ji(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."]:[Ki(h)],""].join(`
|
|
200
|
+
`)),n}catch(a){if(a instanceof t)return process.stderr.write(`${a.format()}
|
|
201
|
+
`),s;throw a}}async function Mi(r,o){let a=[],u=[];for(let i of o){let f=Ze(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 ut({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 Ki(r){let o=r.filter((f)=>Ze(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:Ze(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}`,` # ${hs(i,new Date().toISOString().slice(0,10),u.detail)}`].join(`
|
|
202
|
+
`)}async function xs(r){let o=await L.create({agents:[r.manifestPath],toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([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:ar},null,2)}
|
|
203
|
+
`),n;if(a.length===0)return process.stdout.write(`No plugins. This binary can resolve these by name:
|
|
204
|
+
|
|
205
|
+
${ar.map((f)=>` - "${f}"`).join(`
|
|
206
|
+
`)}
|
|
207
|
+
|
|
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(`
|
|
211
|
+
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 Xi,readdirSync as As,rmSync as St,statSync as Os}from"node:fs";import{homedir as Ji}from"node:os";import{join as _s}from"node:path";function Es(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 Ps(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 ${se(a.sessions,"conversation")}, ${se(a.messages,"message")}, ${se(a.passages,"memory passage")}`}),r.logs.length>0)o.push({kind:"logs",detail:`delete ${se(r.logs.length,"log file")}`})}return o.push({kind:"directory",detail:`delete ${r.dir}`}),o}function Rs(r){let o=r.footprint,a=[{label:"directory",value:`${r.dir}`,note:`${se(r.files.count,"file")}, ${pt(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:`${se(o.sessions,"conversation")}, ${se(o.passages,"memory passage")}, and the logs`,note:"--files-only"});else a.push({label:"sessions",value:`${se(o.sessions,"conversation")}, ${se(o.messages,"message")}, ${se(o.turns,"turn")}`},{label:"memory",value:`${se(o.passages,"passage")} from ${se(o.memorySources,"source")}`},{label:"outbox",value:o.outbox===0?"nothing queued":`${se(o.outbox,"delivery")}${o.outboxPending===0?"":`, ${o.outboxPending} not yet sent`}`,...o.outboxPending===0?{}:{note:"abandoned"}},{label:"schedules",value:o.schedules===0?"none":se(o.schedules,"schedule"),...o.schedules===0?{}:{note:"stops firing"}},{label:"logs",value:r.logs.length===0?"none":`${se(r.logs.length,"file")}, ${pt(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 Is(r){if(r.length===0)return"";return r.map((o)=>{let a=o.footprint,u=[];if(a.sessions>0)u.push(`${se(a.sessions,"conversation")}, ${se(a.messages,"message")}`);if(a.passages>0)u.push(`${se(a.passages,"memory passage")}`);if(a.outbox>0)u.push(`${se(a.outbox,"queued delivery")}`);if(a.schedules>0)u.push(`${se(a.schedules,"schedule")}`);if(a.lease)u.push("a stale lease");if(o.logs.length>0)u.push(`${se(o.logs.length,"log file")}, ${pt(o.logs.reduce((i,f)=>i+f.bytes,0))}`);return` ${o.agentId} ${u.length===0?"rows with no detail":u.join(" · ")}`}).join(`
|
|
214
|
+
`)}function se(r,o){return`${r} ${o}${r===1?"":"s"}`}import{homedir as Ui}from"node:os";var Ts=12000,Di=250;async function Kn(r){if(r.manifestPath!==void 0)return await Hi(r,r.manifestPath);return await Bi(r)}async function Hi(r,o){let a=Vi(o),u=[];if(r.dryRun===!0){let g=await Oe(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 Rn(a,!1,r.reason,r.store),u.push("switched off for the next start");let i=await Oe(a,r.store),f=!0;if(i===void 0)u.push("nothing was running");else if(i.baseUrl===void 0){let g=await Ln(i.pid,"SIGTERM");f=g||await Ln(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 Xe(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}])}
|
|
218
|
+
`),process.stdout.write(`
|
|
219
|
+
Stays off across restarts. \`${e.slug} start ${a}\` switches it back on.
|
|
220
|
+
`);return f?n:s}async function Bi(r){let o=r.platform??process.platform,a=o==="darwin"?Me(o,{home:Ui(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}}):void 0,u=await Wi(a,r.store);if(u.length===0)return process.stdout.write(r.json===!0?`${JSON.stringify({stopped:[]})}
|
|
221
|
+
`:`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(qi(f))).join(`
|
|
224
|
+
`)}
|
|
225
|
+
`),n;let i=[];for(let f of u)i.push(await Gi(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(`
|
|
228
|
+
Services are disabled as well as unloaded, so they stay stopped across a reboot.
|
|
229
|
+
Start one again with \`${e.slug} daemon start <agent>\`.
|
|
230
|
+
`);if(i.some((h)=>h.forced===!0))process.stdout.write(`
|
|
231
|
+
Something had to be killed rather than asked. A forced stop skips the runtime's own
|
|
232
|
+
cleanup, so a command the agent had left running in the background may still be alive —
|
|
233
|
+
\`ps\` will show it if so.
|
|
234
|
+
`)}return i.every((f)=>f.stopped)?n:s}async function Wi(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 Gi(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 Ln(r.pid,"SIGTERM"))return a.push(`pid ${r.pid} stopped cleanly`),{...r,stopped:!0,note:a.join(" · ")};let i=await Ln(r.pid,"SIGKILL",!0);return a.push(i?`pid ${r.pid} did not stop in ${Math.round(Ts/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 Ln(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:Ts);while(Date.now()<u){if(!_(r))return!0;await new Promise((i)=>setTimeout(i,Di))}return!_(r)}function qi(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 Vi(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 Cs(r){let o=await M.open({path:r.store??w()});try{if(r.prune===!0)return await Qi(r,o);if(r.all===!0)return await Yi(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 zi(r.ref,r,o)}finally{await o.close()}}async function zi(r,o,a){let u=await Fs(r,o,a),i=Es(u);if(i.length>0){let g=i[0];throw new t({code:g.code,message:g.message,hint:g.hint})}let f=Ps(u),h=`${m(`removing ${r} will:`,!0)}
|
|
235
|
+
${Rs(u)}
|
|
236
|
+
|
|
237
|
+
${f.map((g)=>d(g.detail)).join(`
|
|
238
|
+
`)}
|
|
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}
|
|
241
|
+
Nothing was deleted — this was --dry-run.
|
|
242
|
+
`),n;if(process.stdout.write(h),!await Et(o,r,"type the agent's name to confirm:"))return process.stdout.write(`
|
|
243
|
+
Nothing was deleted.
|
|
244
|
+
`),n;return await Ns(u,o,a)}async function Ns(r,o,a){let u=[];if(r.running!==void 0||!r.filesOnly&&r.service!==void 0){if(await Kn({manifestPath:r.manifestPath,...o.exec===void 0?{}:{exec:o.exec},...o.platform===void 0?{}:{platform:o.platform}})!==n)return process.stderr.write(`
|
|
245
|
+
Stopping ${r.ref} did not succeed, so nothing was deleted. Its directory and data are untouched.
|
|
246
|
+
hint: check what is still running with \`${e.slug} stop --dry-run\`, then run remove again.
|
|
247
|
+
`),s;u.push({label:"stopped",value:r.ref})}if(!r.filesOnly&&r.service!==void 0){let i=Ls(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)St(f.path,{force:!0});if(r.logs.length>0)u.push({label:"logs",value:`${r.logs.length} file(s)`})}if(St(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 Yi(r,o){let a=B();if(a.length===0)return process.stdout.write(`The sandbox is empty — there is nothing to remove.
|
|
254
|
+
`),n;if(process.stdout.write(`${m(`removing every agent in ${z()}:`,!0)}
|
|
255
|
+
${a.map((i)=>d(`${i.ref}${i.id===void 0||i.id===i.ref?"":` (id ${i.id})`}`)).join(`
|
|
256
|
+
`)}
|
|
257
|
+
`),r.dryRun===!0)return process.stdout.write(`
|
|
258
|
+
Nothing was deleted — this was --dry-run.
|
|
259
|
+
`),n;if(!await Et(r,"all",`type \`all\` to remove all ${a.length}:`))return process.stdout.write(`
|
|
260
|
+
Nothing was deleted.
|
|
261
|
+
`),n;let u=n;for(let i of a){let f=await Fs(i.ref,r,o),h=await Ns({...f,sharesIdWith:[]},r,o);if(h!==n)u=h}return u}async function Qi(r,o){let a=new Set(B().map((h)=>h.id??h.ref).filter((h)=>h!=="")),u=new Set((await o.agentIds()).filter((h)=>!a.has(h)));for(let h of ea())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:js(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 ${z()}.
|
|
263
|
+
`),n;if(process.stdout.write(`${m("no sandbox directory claims these:",!0)}
|
|
264
|
+
${Is(i)}
|
|
265
|
+
`),r.dryRun===!0)return process.stdout.write(`
|
|
266
|
+
Nothing was deleted — this was --dry-run.
|
|
267
|
+
`),n;if(!await Et(r,"prune","type `prune` to delete them:"))return process.stdout.write(`
|
|
268
|
+
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)St(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)}
|
|
270
|
+
`:`
|
|
271
|
+
pruned ${i.length} agent id(s).
|
|
272
|
+
${l(f)}
|
|
273
|
+
`),n}async function Fs(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 ${z()} 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=B(),i=u.find((R)=>R.ref===r);if(i===void 0){let R=u.map((K)=>K.ref);throw new t({code:"cli_agent_unknown",message:`No agent named "${r}" in the sandbox${R.length===0?", which is empty":""}.`,hint:R.length===0?`Nothing to remove. \`${e.slug} init\` creates one.`:`Known agents: ${R.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=Ls(o),S=pn(e.slug,g);return{ref:r,agentId:g,manifestPath:i.manifestPath,dir:i.dir,files:Zi(i.dir),footprint:v,logs:js(g),sharesIdWith:u.filter((R)=>R.ref!==r&&(R.id??"")===g).map((R)=>R.ref),...k!==void 0&&_(k.pid)?{running:{pid:k.pid,mode:k.mode}}:{},...y?.state(S).installed===!0?{service:S}:{},filesOnly:h}}function Ls(r){let o=r.platform??process.platform;if(o!=="darwin")return;return Me(o,{home:Ji(),uid:process.getuid?.()??0,envPrefix:e.envPrefix,...r.exec===void 0?{}:{exec:r.exec}})}function Zi(r){let o=0,a=0,u=(i)=>{let f;try{f=As(i)}catch{return}for(let h of f){let g=_s(i,h);try{let v=Os(g);if(v.isDirectory()){u(g);continue}o+=1,a+=v.size}catch{}}};return u(r),{count:o,bytes:a}}function js(r){let o=Wt(r),a=[];for(let u of[o.out,o.err])try{if(!Xi(u))continue;a.push({path:u,bytes:Os(u).size})}catch{}return a}function ea(){let r;try{r=As(_s(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 Et(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 _t}from"node:crypto";import{existsSync as da}from"node:fs";import{createInterface as Gs}from"node:readline";class Ie 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 na(r,o){let a=r instanceof Error?r.message:String(r);return new Ie({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 ta(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 Ie(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 Ms=new Set(Ce);async function*Ks(r){for await(let o of Cn(ra(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*ra(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*sa(r){for await(let{name:o,data:a}of Ks(r)){if(Ms.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*oa(r){for await(let{name:o,data:a}of Ks(r)){if(Ms.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*ia(r,o={}){for await(let a of r){if(a.kind==="replay"&&a.report.truncated&&o.allowTruncated!==!0)throw new Ie({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 Ie({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 Us(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 R;try{R=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(K){throw na(K,{method:k,path:y,baseUrl:o})}if(!R.ok)throw await ta(R,{method:k,path:y});return R}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 Ie({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,R={}){let K=(j)=>j?.chunks===!0?"?chunks=true":"",X={turnId:y,sessionKey:S,replayed:R.replayed===!0,async*stream(j){let N=await h(`/v1/agents/${encodeURIComponent(k)}/turns/${encodeURIComponent(y)}/stream${K(j)}`,j?.signal);yield*sa(N)},async*tokens(j){yield*ia(X.stream({chunks:!0,...j}),{...j?.allowTruncated===void 0?{}:{allowTruncated:j.allowTruncated}})},async text(){for await(let j of X.stream()){if(j.kind==="ended")break;if(j.kind==="unavailable")break;if(j.kind==="event"&&j.event.type==="turn.end")break}return(await X.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 X}function v(k){let y=(S)=>`/v1/agents/${encodeURIComponent(k)}${S}`;return{id:k,async send(S,R){let K=await f("POST",y("/messages"),{body:{text:S,...R?.sessionKey===void 0?{}:{sessionKey:R.sessionKey},...R?.deliver===void 0?{}:{deliver:R.deliver},...R?.from===void 0?{}:{from:R.from}},...R?.idempotencyKey===void 0?{}:{headers:{"idempotency-key":R.idempotencyKey}},...R?.signal===void 0?{}:{signal:R.signal}});return g(k,K.turnId,K.sessionKey,{replayed:K.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,R)=>{let K=new URLSearchParams;if(R?.before!==void 0)K.set("before",String(R.before));if(R?.limit!==void 0)K.set("limit",String(R.limit));let X=K.size===0?"":`?${K.toString()}`;return f("GET",y(`/sessions/${encodeURIComponent(S)}/messages${X}`))},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,R)=>f("PATCH",y(`/schedules/${encodeURIComponent(S)}`),{body:R}),deleteSchedule:async(S)=>{await f("DELETE",y(`/schedules/${encodeURIComponent(S)}`))},runSchedule:(S)=>f("POST",y(`/schedules/${encodeURIComponent(S)}/run`),{body:{}}),session:(S)=>f("GET",y(`/sessions/${encodeURIComponent(S)}`)),setPhase:(S,R)=>f("POST",y(`/sessions/${encodeURIComponent(S)}/phase`),{body:{phase:R}}),approve:async(S,R)=>{await f("POST",y(`/approvals/${encodeURIComponent(S)}`),{body:{granted:R}})},stop:(S)=>f("POST",y("/stop"),{body:S===void 0?{}:{reason:S}}),start:()=>f("POST",y("/start"),{body:{}}),context:(S)=>{let R=new URLSearchParams;if(S?.sessionKey!==void 0)R.set("sessionKey",S.sessionKey);if(S?.input!==void 0)R.set("input",S.input);let K=R.size===0?"":`?${R.toString()}`;return f("GET",y(`/context${K}`))}}}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 Ie&&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()}`,R=await h(`/v1/events${S}`,k?.signal);yield*oa(R)}}}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=Er(u,o);if(i==="")continue;a.push({role:u.role,text:i})}return a}function Ds(r){let o=r.ref??"<your agent>",a=`${e.slug} run ${o} --session ${r.sessionKey}`;return`
|
|
275
|
+
${Go}Resume this session with:
|
|
276
|
+
${a}${vn}
|
|
277
|
+
`}function Pt(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 aa(r){return r==="nlt"?Mn():Pn()}function Hs(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()=>Gn(r.agent),context:r.context,close:async()=>{}}}function Bs(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,R=new Promise((K)=>{let X=(j)=>{if(k!==void 0&&j.turnId!==void 0&&j.turnId!==k)return;if(j.type==="error"){S=j.data;return}if(j.type!=="turn.end")return;a.delete(X),K({text:"",reason:j.data.reason,steps:j.data.steps,durationMs:j.data.durationMs,tokens:j.data.tokens,...S===void 0?{}:{error:S}})};a.add(X),f()});try{if(k=(await o.send(h,{sessionKey:g.sessionKey})).turnId,v)o.turn(k).stop().catch(()=>{});return await R}finally{g.signal.removeEventListener("abort",y)}},streamFilter:()=>aa(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 Ws(r){if(r?.baseUrl===void 0||r.baseUrl==="")return;return{baseUrl:r.baseUrl,pid:r.pid}}async function la(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} ${A} · ${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=Pt(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 R of[...r.warnings,...r.tools.warnings])y.push(`note: ${R.message}
|
|
278
|
+
${R.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 Ct(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 j=await ua(u,a.because,r);if(typeof j==="number")return j;return Ct({...r,manifestPath:j})}let i=Sr();if(r.store===void 0&&r.ephemeral!==!0&&da(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,R="first",K={current:void 0},X=r.ephemeral===!0?void 0:Ws(await Oe(wt(r.manifestPath),r.store));if(X!==void 0)return await ha({...r,host:X,mode:u==="rich"?"rich":"plain",quiet:S,oneShot:o,reader:h,draft:g,session:v,random:_t});for(;;){let j=await L.create({agents:[r.manifestPath],toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([r.manifestPath]),store:r.ephemeral===!0?":memory:":r.store??w()});f=j;let N=j.list()[0];if(N===void 0)throw Error("The manifest produced no agent.");if(v.current===void 0||v.current===""){let F=await qs({list:()=>Q.sessions(),mode:u,asked:v.current,wantsContinue:r.continueSession===!0,random:_t});if(typeof F==="number")return await j.stop("cli-exit"),F;v.current=F.sessionKey,k.current=F.fresh}let oe=v.current,fe=N.roles.main.capabilities.thinking!=="none",ae=r.noReasoning===!0?!1:fe,D=S||o?[]:await la(N,oe,j.store.location,R==="first"?j.boot.processMs:j.boot.bootMs,R,Ao([r.manifestPath]),y.current),G=u==="rich"&&!S&&!o?tn(await N.history(oe),N.describe().dialect):[],Q=Hs({agent:N,bus:j.bus,send:(F,ne)=>N.send(F,ne),history:async(F)=>tn(await N.history(F),N.describe().dialect),sessions:async()=>await N.store.sessions.list(N.id),clearSession:async(F)=>{await N.clearSession(F)},context:async(F)=>ga(N,F),streamFilter:()=>N.streamFilter(),description:{agentId:N.id,name:N.describe().name,model:N.describe().model,dialect:N.describe().dialect,window:N.describe().window,catalogueTokens:N.describe().catalogueTokens,thinking:N.roles.main.capabilities.thinking,warnings:[...N.warnings,...N.tools.warnings]}}),re={...r,source:Q,embedded:{agent:N,runtime:j},sessionKey:oe,banner:D,prior:G,quiet:S,reader:h,draft:g,showReasoning:ae,freshSession:k.current,switchTo:K,random:_t},pe=u==="rich"?await Vs(re):await Xs(re);if(await j.stop(pe===Te?"restart":"cli-exit"),pe!==Te)return pe;if(K.current===void 0)R="restart";else R=K.current.reason,y.current=oe,v.current=K.current.key,K.current=void 0;k.current=!1}}function ca(r,o){let a=[];for(let u of r)ve({action:"install",manifestPath:o,name:`${u.source}/${u.skill}`,quiet:!0,collect:a});return a}var Te=Symbol("restart");async function ua(r,o,a){let u=B();if(u.length===0){if(r==="rich"){let y=await ot({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-jxaesaxy.js")]),g={kind:"quit"};zt();let v=i(f(h,{title:`${e.name} ${A}`,agents:u,onDone:(y)=>{g=y}}),{exitOnCtrlC:!1,...Y(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 ot({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 qs(r){let o=()=>({sessionKey:jn(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=fa(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(Un))process.stdout.write(`${i.sessionKey} ${i.messages} ${i.turns} ${i.lastActivityAt}
|
|
289
|
+
`);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 ma([...a].sort(Un));return u===void 0?o():{sessionKey:u,fresh:!1}}return r.asked===void 0?o():{sessionKey:r.asked,fresh:!1}}function Un(r,o){return Date.parse(o.lastActivityAt)-Date.parse(r.lastActivityAt)}function fa(r){return[...r].sort(Un)[0]}async function ma(r){let[{render:o},{createElement:a},{SessionPicker:u}]=await Promise.all([import("ink"),import("react"),import("./SessionPicker-z2t0p4b5.js")]),i;zt();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:Z(process.stdout.columns,U),maxRows:Ft,onDone:(h)=>{i=h,f.unmount()}}),{exitOnCtrlC:!1,...Y()});return b(()=>f.unmount()),await f.waitUntilExit(),i}function pa(r,o,a,u,i){let f=r.describe(),h=[`${e.name} ${A} · ${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=Pt(u,i);if(g!==void 0)h.push(g);for(let v of f.warnings)h.push(`warning: ${v.message}`);return h}async function ha(r){let o=r.manifestPath??"",a=wt(o),u=Ye(o),i=Us({baseUrl:r.host.baseUrl,...u===void 0?{}:{token:u}}),f=await i.agent(a).describe(),h=Bs({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 N=await qs({list:()=>h.sessions(),mode:r.mode,asked:r.session.current,wantsContinue:r.continueSession===!0,random:r.random});if(typeof N==="number")return N;r.session.current=N.sessionKey,y.current=N.fresh}let S=r.session.current??"",R=r.quiet||r.oneShot?[]:pa(h,S,r.host,v,k.current),K=r.mode==="rich"&&!r.quiet&&!r.oneShot?await h.history(S):[],X={...r,source:h,sessionKey:S,banner:R,prior:K,quiet:r.quiet,reader:r.reader,draft:r.draft,showReasoning:r.noReasoning!==!0,freshSession:y.current,switchTo:g,random:r.random},j=r.mode==="rich"?await Vs(X):await Xs(X);if(j!==Te)return await h.close(),j;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 Vs(r){let[{render:o},{createElement:a},{App:u}]=await Promise.all([import("ink"),import("react"),import("./App-dxqm39zx.js")]),i=Tn();b(()=>{i.close()}),he(),Kr(),process.stdout.write(`${we}${Fo}`);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:jn(r.random),reason:"new"},r.draft.current=g},sessions:async()=>[...await r.source.sessions()].sort(Un).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:yo(go(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)=>et({onStatus:g}),install:async(g,v)=>vt(ca(g,v))},status:()=>r.embedded===void 0?zs(r.source):Js(r.embedded),contextView:()=>Ys(r,r.sessionKey),...r.draft.current===""?{}:{initialDraft:r.draft.current}}),{exitOnCtrlC:!1,...Y(r.noEnhancedKeys)});if(b(()=>h.unmount()),await h.waitUntilExit(),J(),!f)process.stdout.write(Ds({ref:r.source.describe().agentId,sessionKey:r.sessionKey}));return f?Te:n}async function Xs(r){let{source:o,sessionKey:a,quiet:u}=r,i=!0,f=(D)=>{if(D==="")return;process.stdout.write(D),i=D.endsWith(`
|
|
291
|
+
`)},h=(D)=>{if(!i)f(`
|
|
292
|
+
`);f(`${D}
|
|
293
|
+
`)};if(r.banner.length>0)f(`${r.banner.join(`
|
|
294
|
+
`)}
|
|
295
|
+
|
|
296
|
+
`);let g=!u&&r.once===void 0,v=!1,k,y=o.streamFilter(),S=(D)=>{if(D==="")return;f(D),v=!0},R=r.source.subscribe((D)=>{switch(D.type){case"model.result":S(y.endStep());return;case"model.chunk":{let{delta:G,kind:Q}=D.data;if(Q==="reasoning"&&r.showReasoning!==!0)return;if(Q!==k){if(k!==void 0)f(`
|
|
297
|
+
|
|
298
|
+
`);if(r.showReasoning===!0)f(Q==="reasoning"?`· reasoning ·
|
|
299
|
+
`:`· reply ·
|
|
300
|
+
`);k=Q}if(Q==="reasoning"){f(G),v=!0;return}S(y.push(G));return}case"tool.result":{if(!g)return;let{slug:G,ok:Q,latencyMs:re,truncated:pe}=D.data;h(` · ${G} — ${Q?"ok":"failed"} · ${re} ms${pe?" · observation trimmed":""}`);return}case"agent.warning":h(` · ${D.data.message}
|
|
301
|
+
${D.data.hint}`);return;case"tool.repair":if(g)h(` · ${D.data.slugs.join(", ")} — could not be used, asking again`);return;case"tool.gated":h(` · ${D.data.slug} — blocked: ${D.data.reason}`);return;case"context.dropped":h(` · context: ${D.data.messages} older message(s) did not fit the ${D.data.budget}-token budget and were left out`);return;default:return}}),K=async(D)=>{let G=Xt(D);if(G===void 0)return"prompt";switch(G.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:jn(r.random),reason:"new"},"restart";case"help":return h(Jt()),"handled";case"tools":return h(st(await o.tools())),"handled";case"status":return h(r.embedded===void 0?await zs(o):await Js(r.embedded)),"handled";case"context":return h(await Ys(r,a)),"handled";case"reset":return await o.clearSession(a),h("session cleared — memory files on disk are untouched"),"handled";case"unknown":return h(xt(G)),"handled";case"command":return h(`${G.name} is a command, not a prompt — run it at a terminal, or in another shell as \`${e.slug} ${G.name}${G.rest===""?"":` ${G.rest}`}\``),"handled"}},X,j=0,N=n,oe=(D=r.reader.current)=>{if(X!==void 0&&!X.signal.aborted){j=performance.now(),X.abort();return}D?.close(),f(`
|
|
302
|
+
`)},fe=async(D)=>{X=new AbortController,v=!1,k=void 0,y=o.streamFilter();let G=await o.send(D,{sessionKey:a,signal:X.signal});if(X=void 0,S(y.end()),v&&!i)f(`
|
|
303
|
+
`);else if(!v&&G.text!=="")f(`${G.text}
|
|
304
|
+
`);let Q=je(G.reason,{steps:G.steps,durationMs:G.durationMs,...j===0?{}:{cancelledAfterMs:performance.now()-j}});if(Q!==void 0)f(`
|
|
305
|
+
(${Q})
|
|
306
|
+
`);if(G.reason==="error"&&G.error!==void 0)process.stderr.write(`
|
|
307
|
+
${G.error.code}: ${G.error.message}
|
|
308
|
+
hint: ${G.error.hint}
|
|
309
|
+
`);if(wr(G.reason))N=s;if(!u&&G.reason==="final")f(` ${G.tokens.prompt} prompt · ${G.tokens.output} output · ${G.durationMs} ms
|
|
310
|
+
|
|
311
|
+
`);await ue()},ae=()=>oe();process.on("SIGINT",ae);try{if(r.once!==void 0)return await fe(r.once),N;if(process.stdin.isTTY!==!0){let G=r.reader.current??Gs({input:process.stdin});r.reader.current=G;for await(let Q of G){let re=Q.trim();if(re==="")continue;let pe=await K(re);if(pe==="exit")break;if(pe==="restart"){N=Te;break}if(pe==="handled")continue;await fe(re)}return N}let D=r.reader.current??Gs({input:process.stdin,output:process.stdout,prompt:Sn,terminal:!1});r.reader.current=D,D.prompt();for await(let G of D){let Q=G.trim();if(Q===""){D.prompt();continue}let re=await K(Q);if(re==="exit")break;if(re==="restart"){N=Te;break}if(re==="handled"){D.prompt();continue}await fe(Q),D.prompt()}if(N!==Te)D.close(),r.reader.current=void 0;return N}finally{process.off("SIGINT",ae),R()}}async function Js(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=me(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 (${Ue(v[0]?.window)})`},...k.map((y)=>({label:y.role,value:`${y.modelId} · ${y.window.contextWindow} token window (${Ue(y.window)})`})),{label:"channels",value:h},{label:"http api",value:g},{label:"store",value:a.store.location},{label:"background",value:await ya(a,u.id)}])}async function zs(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 ga(r,o){let a=await r.previewContext({sessionKey:o}),[u]=me(r.manifest);return{slots:a.slots,history:a.history,cache:a.cache,total:a.total,window:a.window,windowSource:Ue(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 Ys(r,o){return po(await r.source.context(o))}async function ya(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 ye(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function wa(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 ba(r,o){if(r.lastFiredAt===void 0)return"never run";let a=We(r.lastFiredAt,o);if(r.lastStatus==="error")return`FAILED ${a}`;return`ok ${a}`}function va(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(`${ye("SCHEDULE",a)} ${ye("WHEN",u)} ${ye("NEXT",7)} LAST
|
|
312
|
+
`);for(let f of r)process.stdout.write(`${ye(f.id,a)} ${ye(`${f.kind} ${f.expr}`,u)} ${ye(wa(f,o),7)} ${ba(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 $a(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(` ${ye(u,a)} ${i}
|
|
317
|
+
`)}function ka(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 Sa(r,o){if(r.length===0){process.stdout.write(`no addresses yet — this agent has had no conversation on a declared channel.
|
|
318
|
+
`+` 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(`${ye("CHANNEL",a)} ${ye("ADDRESS",u)} LAST SEEN
|
|
320
|
+
`);for(let i of r)process.stdout.write(`${ye(i.channelId,a)} ${ye(i.address,u)} ${We(i.lastSeen,o)}
|
|
321
|
+
`);process.stdout.write(`
|
|
322
|
+
Use an ADDRESS in deliver.to. On Telegram an @name addresses a channel and
|
|
323
|
+
`+`never a person — a private chat is reached by the numeric id above.
|
|
324
|
+
`)}async function Qs(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([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}
|
|
325
|
+
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.
|
|
327
|
+
`+` Writing it here would last until the next start — reconciliation restores every
|
|
328
|
+
`+` field from the file, enabled included.
|
|
329
|
+
|
|
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=ka(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 Sa(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 $a(f),n}if(r.enable===void 0&&r.disable===void 0)va(i,u);return n}function xa(){return ct.shape.server.parse({})}async function Zs(r){let o=p(r.manifestPaths),a=r.store??w(),u=await Lr(r.manifestPaths,o,a),i=u.filter((F)=>!F.enabled),h=u.filter((F)=>F.enabled).map((F)=>({path:F.manifestPath,loaded:x(F.manifestPath,{knownProviders:W,knownChannels:q,env:o})})),g=h[0],v=g?.loaded,k=v?.manifest.server??xa();for(let F of h.slice(1)){let ne=F.loaded.manifest.server;for(let[ke,Re,ln,_e]of[["server.port",k.port,ne.port,r.port!==void 0],["server.host",k.host,ne.host,r.host!==void 0],["server.tokenEnv",k.tokenEnv,ne.tokenEnv,!1]]){if(_e||Re===ln)continue;throw new t({code:"serve_bind_conflict",message:`${g?.path??"the first manifest"} sets ${ke} to ${String(Re)} and ${F.path} sets it to ${String(ln)}.`,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:ke})}}let y=r.port??k.port,S=r.host??k.host,R=v===void 0?o[k.tokenEnv]:v.env[k.tokenEnv],K=o[`${e.envPrefix}SERVICE`]!==void 0,X=new De({runtimeId:`rt_${Date.now().toString(36)}`});if(r.json!==!0)X.on("agent.channel.status",(F)=>{let ne=F.data,ke=ne.input===void 0?"":` (${ne.input.kind}${ne.input.expiresAt===void 0?"":`, expires ${ne.input.expiresAt}`} — GET /v1/agents/${F.agentId??""} carries it)`;process.stdout.write(` ${ne.channelId}: ${ne.status}${ne.detail===void 0?"":` — ${ne.detail}`}${ke}
|
|
338
|
+
`)}),X.on("agent.channel.error",(F)=>{let ne=F.data;process.stderr.write(` ${ne.channelId}: ${ne.message}
|
|
339
|
+
hint: ${ne.hint}
|
|
340
|
+
`)}),X.on("agent.channel.rejected",(F)=>{let ne=F.data;process.stdout.write(` ${ne.channelId}: ${ne.reason} — ${ne.detail}
|
|
341
|
+
`)});let j=sr(),N=await L.create({agents:h.map((F)=>F.path),approve:j.approver,env:o,bus:X,toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,startChannels:!0,startSchedules:!0,store:a,mode:K?"daemon":"terminal"});Hr();let oe=Ea(),fe=await N.store.operatorKeys.liveCount(),ae=fe===0||r.claim===!0?Or():void 0,D;try{D=await Pr({runtime:N,host:S,port:y,approvals:j,allowedOrigins:k.allowedOrigins,allowedHosts:k.allowedHosts,resolveAgent:(F)=>Ut(F,o),provision:{steps:()=>Gr({agentDirBase:z(o)}),create:(F)=>qr({answers:F,defaults:{agentDirBase:z(o)}})},...ae===void 0?{}:{claim:ae},...R===void 0||R===""?{}:{token:R}})}catch(F){if(await N.stop("server failed to bind"),F instanceof t)throw F;throw new t({code:"server_bind_failed",message:`Could not bind ${S}:${y}: ${F instanceof Error?F.message:String(F)}`,hint:"Another process is probably on that port. Pass --port, or set server.port in the manifest.",cause:F})}await N.publishAddress(D.url);let G=N.list(),Q=G[0];if(Q!==void 0)process.title=G.length===1?`${e.slug} ${Q.id}`:`${e.slug} ${G.length} agents`;for(let F of G)F.reportRuntimeState({serverListening:!0});if(r.json===!0)process.stdout.write(`${JSON.stringify({url:D.url,websocket:D.websocket,authenticated:R!==void 0&&R!=="",keys:fe,...ae===void 0?{}:{claim:ae.token},agents:G.map((F)=>({id:F.id,channels:N.channels.statusOf(F.id)})),declined:N.declined.map((F)=>({agentId:F.agentId,pid:F.pid,mode:F.mode,since:F.startedAt})),disabled:i.map((F)=>({agentId:F.agentId,...F.reason===void 0?{}:{reason:F.reason}}))})}
|
|
342
|
+
`);else{process.stdout.write(`${e.name} serving on ${D.url}
|
|
343
|
+
`);for(let F of G){let ne=N.channels.statusOf(F.id),ke=ne.length===0?"no channels":ne.map((_e)=>`${_e.id} (${_e.type})`).join(", "),Re=F.manifest.schedules.filter((_e)=>_e.enabled),ln=F.manifest.schedules.length===0?"":`, ${Re.length} schedule${Re.length===1?"":"s"}${F.manifest.schedules.length>Re.length?` (+${F.manifest.schedules.length-Re.length} disabled)`:""}`;process.stdout.write(` ${F.id} — ${ke}${ln}
|
|
344
|
+
`)}for(let F of i)process.stdout.write(` ${F.agentId} — stopped${F.reason===void 0?"":` (${F.reason})`}, \`${e.slug} start ${F.agentId}\`
|
|
345
|
+
`);for(let F of N.declined)process.stdout.write(` ${F.agentId} — NOT served here: pid ${F.pid} (${F.mode}) already has it
|
|
346
|
+
`);if(N.declined.length>0)process.stdout.write(` \`${e.slug} stop <agent>\` ends the other one, or leave it — nothing here is broken.
|
|
347
|
+
`);if(ae!==void 0){if(process.stdout.write(` open once to claim this server:
|
|
348
|
+
${Nr(S,D.port,ae.token)}
|
|
349
|
+
without a browser: ${Cr(S,D.port,ae.token)}
|
|
350
|
+
`),R===void 0||R==="")process.stdout.write(` the first key closes this server — every route then needs a credential.
|
|
351
|
+
`)}if(R===void 0||R==="")process.stdout.write(` unauthenticated — loopback only. Set ${k.tokenEnv} to bind a public host.
|
|
352
|
+
`);if(!D.websocket)process.stdout.write(` /v1/ws unavailable under Node — SSE and HTTP are unaffected.
|
|
353
|
+
`);if(K)process.stdout.write(` running as a background service · ${e.slug} daemon status ${G[0]?.id??""}
|
|
354
|
+
`);else process.stdout.write(` ctrl-c to stop — this ends when the terminal does. \`${e.slug} daemon install ${G[0]?.id??"<agent>"}\` keeps it running.
|
|
355
|
+
`)}let re=!1,pe=async()=>{if(re)return;re=!0,await D.stop(),await N.stop("interrupted")};return b(pe),await oe,process.stdout.write(`stopping
|
|
356
|
+
`),await pe(),n}function Ea(){return new Promise((r)=>{let o=()=>{process.off("SIGINT",o),process.off("SIGTERM",o),r()};process.once("SIGINT",o),process.once("SIGTERM",o)})}function de(r,o){return r.length>=o?r:r+" ".repeat(o-r.length)}function Pa(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 Ra(r){if(r.length===0){process.stdout.write(`no sessions yet
|
|
357
|
+
`);return}let o=Pa(r),a=Math.max(7,...o.map((u)=>u.sessionKey.length));process.stdout.write(`${de("SESSION",a)} ${de("MSGS",5)} ${de("TURNS",5)} ${de("PHASE",8)} LAST
|
|
358
|
+
`);for(let u of o){let i=u.runs===void 0?"":` (${u.runs} run${u.runs===1?"":"s"})`;process.stdout.write(`${de(u.sessionKey,a)} ${de(String(u.messages),5)} ${de(String(u.turns),5)} ${de(u.phase??"-",8)} ${We(u.lastActivityAt,Date.now())}${i}
|
|
359
|
+
`)}}async function Ia(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}
|
|
360
|
+
`);return}for(let i of[...u.messages].reverse())process.stdout.write(`${i.role}: ${i.content}
|
|
361
|
+
`);if(u.nextBefore!==void 0)process.stdout.write(`
|
|
362
|
+
… older messages exist; raise --limit
|
|
363
|
+
`)}async function Ta(r,o,a){let u=await r.turns(o,a);if(u.length===0){process.stdout.write(`no turns in ${o}
|
|
364
|
+
`);return}process.stdout.write(`${de("TURN",22)} ${de("STATUS",9)} ${de("STEPS",5)} ${de("TOKENS",13)} ${de("MS",6)} SOURCE
|
|
365
|
+
`);for(let i of u)if(process.stdout.write(`${de(i.turnId,22)} ${de(i.status,9)} ${de(String(i.steps),5)} ${de(`${i.promptTokens}/${i.outputTokens}`,13)} ${de(String(i.durationMs??"-"),6)} ${i.source}
|
|
366
|
+
`),i.errorCode!==void 0){if(process.stdout.write(` ${i.errorCode}: ${i.errorMessage}
|
|
367
|
+
`),i.errorHint!==void 0)process.stdout.write(` hint: ${i.errorHint}
|
|
368
|
+
`)}}async function eo(r){let o=await L.create({agents:[r.manifestPath],store:r.store??w(),toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([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??$n;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
|
|
369
|
+
`),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)}
|
|
370
|
+
`),n}if(process.stdout.write(`store: ${o.store.location}
|
|
371
|
+
|
|
372
|
+
`),r.sessionKey===void 0)return Ra(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}
|
|
373
|
+
hint: run \`sessions ${r.manifestPath}\` to list the keys that exist
|
|
374
|
+
`),s;if(r.turns===!0)await Ta(a,r.sessionKey,u);else await Ia(a,r.sessionKey,u);return n}import{existsSync as Aa,readFileSync as Oa,writeFileSync as _a}from"node:fs";import{basename as Ca,dirname as Na,join as Fa}from"node:path";var La=/^(#{1,6})\s+(.*)$/,ja=/^[ \t]*<rules(?:\s[^>]*)?>[ \t]*$/,Ma=/^[ \t]*<\/rules>[ \t]*$/,Ka=/^\s*(?:```|~~~)/;function to(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=Oa(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=Ca(r.file),u=r.out??Fa(Na(r.file),`${a.replace(/\.md$/i,"")}.compact.md`);if(Aa(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}=on(a,o),f=Ua(a,i);return _a(u,f,"utf8"),process.stdout.write(`wrote ${u}
|
|
375
|
+
|
|
376
|
+
The scaffold copies ${a}'s headings and its <rules> blocks verbatim, and leaves a
|
|
377
|
+
{{PLACEHOLDER}} under each heading. Now:
|
|
378
|
+
`+` 1. Fill every placeholder by hand — two or three sentences that must survive, in the
|
|
379
|
+
`+` document's own voice. The workspace command warns until none are left.
|
|
380
|
+
2. Name the file in context.soul.distilled.
|
|
381
|
+
`),n}function Ua(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(`
|
|
382
|
+
`)){if(Ka.test(g)){if(u=!u,i)a.push(g);continue}if(u){if(i)a.push(g);continue}if(ja.test(g)){i=!0,a.push(g);continue}if(i){if(a.push(g),Ma.test(g))i=!1,a.push("");continue}if(La.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(`
|
|
383
|
+
`).replace(/\n{3,}/g,`
|
|
384
|
+
|
|
385
|
+
`).trimEnd()}
|
|
386
|
+
`}var Da=["list","add","remove","update","search"],Ha=12;async function ro(r){try{switch(r.action){case"list":return Ba(r);case"add":return Wa(r);case"remove":return qa(r);case"update":return await Va(r);case"search":return await Xa(r);default:throw new t({code:"sources_action_unknown",message:`${r.action} is not a sources action`,hint:`One of: ${Da.join(", ")}.`})}}catch(o){if(o instanceof t)return process.stdout.write(`${o.message}
|
|
387
|
+
|
|
388
|
+
${o.hint}
|
|
389
|
+
`),s;throw o}}function Ba(r){let a=V(r.env).map((u)=>{let i=In(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:jt(r.env),sources:a},null,2)}
|
|
390
|
+
`),n;if(a.length===0)return process.stdout.write(`every built-in source has been removed, and none has been added
|
|
391
|
+
|
|
392
|
+
\`sources add <name> <url>\` to add one, or \`sources add ${Je[0]?.name??"anthropic"} ${Je[0]?.url??""}\` to put a built-in back.
|
|
393
|
+
`),n;process.stdout.write(m("sources",!0));for(let u of a)process.stdout.write(`
|
|
394
|
+
${d(`${u.name}${u.builtin===!0?" (built-in)":""}`)}
|
|
395
|
+
`),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(`
|
|
396
|
+
${m("registry")}
|
|
397
|
+
${c(jt(r.env))}
|
|
398
|
+
`),n}function Wa(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=jr(i),h=u?o:Ga(f.url);if(!lr(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=V(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(Fr(y,r.env),r.json===!0)return process.stdout.write(`${JSON.stringify({added:y},null,2)}
|
|
399
|
+
`),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}]])}
|
|
400
|
+
`),process.stdout.write(`${m("next")}
|
|
401
|
+
${d(`sources update ${h}`)}
|
|
402
|
+
${d("sources search <what you need>")}
|
|
403
|
+
`),n}function Ga(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 qa(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=V(r.env).map((i)=>i.name);if(!Ur(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=Je.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":""}
|
|
404
|
+
`),process.stdout.write(`
|
|
405
|
+
The cached copy is left on disk; nothing already installed into an agent is touched.
|
|
406
|
+
`),n}async function Va(r){let o=V(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
|
|
407
|
+
|
|
408
|
+
\`sources add <url>\` to add one.
|
|
409
|
+
`),n;let u=[],i=[];for(let f of a){if(r.json!==!0)process.stdout.write(`fetching ${f.name} … `);try{let h=await Qe(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)":""}
|
|
410
|
+
`)}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
|
|
411
|
+
`);if(r.json!==!0&&h instanceof t)process.stdout.write(`${c(h.message)}
|
|
412
|
+
${c(h.hint,4)}
|
|
413
|
+
`)}}if(r.json===!0)process.stdout.write(`${JSON.stringify({updated:u,failed:i},null,2)}
|
|
414
|
+
`);return u.length===0?s:n}async function Xa(r){let o=r.rest.join(" ").trim(),a=V(r.env);if(a.length===0)return process.stdout.write(`no sources configured
|
|
415
|
+
|
|
416
|
+
\`sources add <url>\` to add one.
|
|
417
|
+
`),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 Qe(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
|
|
418
|
+
`)}catch(v){if(r.json!==!0){if(process.stdout.write(`failed
|
|
419
|
+
`),v instanceof t)process.stdout.write(`${c(v.message)}
|
|
420
|
+
`)}}}let i=a.flatMap((g)=>be(g,r.env));if(i.length===0)return process.stdout.write(`
|
|
421
|
+
nothing to search — no source has been fetched successfully
|
|
422
|
+
|
|
423
|
+
\`sources update\` reports why.
|
|
424
|
+
`),s;let f=o.length===0?i:Ja(o,i);if(f.length===0)return process.stdout.write(`
|
|
425
|
+
nothing in ${i.length} skills across ${a.length} sources matches ${JSON.stringify(o)}
|
|
426
|
+
|
|
427
|
+
Try the words a skill's own description would use — the ranking is lexical, not semantic. \`sources search\` with no query lists everything.
|
|
428
|
+
`),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)}
|
|
429
|
+
`),n;let h=f.slice(0,Ha);process.stdout.write(`
|
|
430
|
+
${m(o.length===0?`${i.length} skills`:`${f.length} of ${i.length} skills match ${JSON.stringify(o)}`,!0)}
|
|
431
|
+
`);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"}
|
|
432
|
+
`);let v=g.problem??g.description;process.stdout.write(`${c(v.length>160?`${v.slice(0,157)}…`:v,4)}
|
|
433
|
+
`)}if(f.length>h.length)process.stdout.write(`
|
|
434
|
+
${c(`… and ${f.length-h.length} more; narrow the query or use --json`)}
|
|
435
|
+
`);return process.stdout.write(`
|
|
436
|
+
${m("install")}
|
|
437
|
+
${c(`skills install <agent> ${h[0]?.source}/${h[0]?.skill}`)}
|
|
438
|
+
`),n}function Ja(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 ht(r,u).filter((i)=>i.score>0).map((i)=>a.get(i.skill.name)).filter((i)=>i!==void 0)}async function so(r){let o=za(r.manifestPath),a=await Dr(o,r.store),u=[];if(a?.enabled===!0)u.push("was already switched on");await Rn(o,!0,void 0,r.store);let i=await Ne(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 Xe(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)}
|
|
439
|
+
`);else if(process.stdout.write(`${l([{label:o,value:f?"running":"switched on",note:u.join(" · ")}])}
|
|
440
|
+
`),!f&&i!==void 0&&i.baseUrl!==void 0)process.stdout.write(`
|
|
441
|
+
Switched on but not yet running. \`${e.slug} daemon restart\` picks it up.
|
|
442
|
+
`);return i!==void 0&&i.baseUrl!==void 0&&!f?s:n}function za(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 Ya,existsSync as Qa,mkdirSync as Za,readFileSync as ed,writeFileSync as nd}from"node:fs";import{dirname as td,join as oo}from"node:path";async function io(r){let o=r.env??p([]),a=r.home??o.HOME??"",u=An(o),i=_n(u);if(r.json===!0)return process.stdout.write(`${JSON.stringify({terminal:u,how:i?.how??"unknown",configPath:i?.configPath===void 0?void 0:oo(a,i.configPath),line:i?.line,steps:i?.steps},null,2)}
|
|
443
|
+
`),i===void 0?s:n;if(process.stdout.write(`${m("shift+enter",!0)}
|
|
444
|
+
${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.")}
|
|
445
|
+
`),i===void 0)return process.stdout.write(`
|
|
446
|
+
${m("this terminal was not recognised")}
|
|
447
|
+
${c(`TERM_PROGRAM=${o.TERM_PROGRAM??"(unset)"} TERM=${o.TERM??"(unset)"}`)}
|
|
448
|
+
${c(`known: ${Yr().map((f)=>f.name).join(", ")}`)}
|
|
449
|
+
${d("⌥⏎ works here regardless — nothing needs configuring for it")}
|
|
450
|
+
`),s;if(process.stdout.write(`
|
|
451
|
+
${m(i.name)}
|
|
452
|
+
`),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"}`)}
|
|
453
|
+
|
|
454
|
+
`);for(let[f,h]of(i.steps??[]).entries())process.stdout.write(`${c(`${f+1}. ${h}`)}
|
|
455
|
+
`);return process.stdout.write(i.how==="unverified"?`
|
|
456
|
+
${d("⌥⏎ works here today — nothing has to be configured for it")}
|
|
457
|
+
`:`
|
|
458
|
+
${d("then restart the terminal and press shift+⏎ in a session to check it")}
|
|
459
|
+
`),n}return await rd(i,{...r,env:o,home:a})}async function rd(r,o){let a=oo(o.home,r.configPath??""),u=Qa(a)?ed(a,"utf8"):"";if(Qr(u,r))return process.stdout.write(`${c("already configured — a binding for shift+enter is present")}
|
|
460
|
+
${c(mt(a,o.home),4)}
|
|
461
|
+
`),n;let i=Zr(u,r);if(i===void 0)return process.stdout.write(`${c("this file is not in a shape this command can edit safely:")}
|
|
462
|
+
${c(mt(a,o.home),4)}
|
|
463
|
+
${d("add the line below by hand:")}
|
|
464
|
+
${c(r.line??"",4)}
|
|
465
|
+
`),s;if(process.stdout.write(`${l([{label:"file",value:mt(a,o.home)},{label:"exists",value:u===""?"no — it will be created":"yes"},{label:"add",value:r.line??""}])}
|
|
466
|
+
`),o.dryRun===!0)return process.stdout.write(`
|
|
467
|
+
${d("--dry-run: nothing was written")}
|
|
468
|
+
`),n;if(o.yes!==!0){if(!(o.confirm===void 0?!1:await o.confirm("write this change?")))return process.stdout.write(`
|
|
469
|
+
${d("nothing was written")}
|
|
470
|
+
`),n}try{if(Za(td(a),{recursive:!0}),u!=="")Ya(a,`${a}.${e.slug}-backup`);nd(a,i,"utf8")}catch(f){return process.stderr.write(`could not write ${a}: ${f instanceof Error?f.message:String(f)}
|
|
471
|
+
`),s}return process.stdout.write(`
|
|
472
|
+
${m("done")}
|
|
473
|
+
${u===""?"":`${c(`a copy of the old file is at ${mt(`${a}.${e.slug}-backup`,o.home)}`)}
|
|
474
|
+
`}${d("restart the terminal, then press shift+⏎ in a session to check it")}
|
|
475
|
+
`),n}async function ao(r){return r.warm===!0?await sd(r):await od(r)}async function sd(r){let o=x(r.manifestPath,{knownProviders:W,knownChannels:q,env:p([r.manifestPath])}),a=ge(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.
|
|
476
|
+
`),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.
|
|
477
|
+
`),n;let i=[],f=new Set;for(let g of a){let v=I[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.
|
|
478
|
+
`);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)}
|
|
479
|
+
`);else for(let g of i){if(process.stdout.write(`${g.fetched} of ${u.length} pinned tools fetched from ${g.provider}
|
|
480
|
+
`),g.changed.length>0)process.stdout.write(` changed: ${g.changed.join(", ")}
|
|
481
|
+
`);if(g.cachePath!=="")process.stdout.write(` cache: ${g.cachePath}
|
|
482
|
+
`)}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
|
|
483
|
+
`);return h.length>0?s:n}async function od(r){let o=await L.create({agents:[r.manifestPath],toolProviders:I,builtInPlugins:P,scriptRunner:O(),channels:C,env:p([r.manifestPath])});try{let a=o.list()[0];if(a===void 0)throw Error("The manifest produced no agent.");let u=Gn(a);return process.stdout.write(r.json===!0?`${JSON.stringify(u,null,2)}
|
|
484
|
+
`:`${st(u)}
|
|
485
|
+
`),n}finally{await o.stop("cli-exit")}}import{dirname as lo,isAbsolute as id,resolve as Dn}from"node:path";async function co(r){try{let o=T(r.manifestPath),a=await dn({refs:o.plugins??[],agentId:o.id??r.manifestPath,paths:{workspace:lo(Dn(r.manifestPath)),state:lo(Dn(r.manifestPath)),manifest:Dn(r.manifestPath)},env:p([r.manifestPath]),bus:new De({runtimeId:"validate"}),builtIn:P,base:{toolProviders:I,channels:C}}),u=x(r.manifestPath,{knownProviders:Object.keys(a.toolProviders),knownChannels:Object.keys(a.channels),env:p([r.manifestPath])}),{manifest:i}=u,f=H(i.model.main.id,i.model.main.capabilities),{workspace:h,warnings:g}=He(u,f.promptStyle);un(u,{channels:a.channels});let v=Ae(h,i.context.rules);if(v!==void 0&&i.context.rules.onExceed==="fail")throw v;let k=[...g,...an(i),...v===void 0?[]:[v.toDetail()]],y=i.knowledge===void 0?void 0:cn({dir:id(i.knowledge.dir)?i.knowledge.dir:Dn(u.dir,i.knowledge.dir),maxActive:i.knowledge.maxActive,budget:i.knowledge.budget,style:f.promptStyle}),S=["static","volatile","reminder"].map((N)=>{let oe=h.files.filter((fe)=>fe.tier===N).map((fe)=>fe.name);if(oe.length===0)return;return`${N}=${oe.join(",")} (${h.tokens[N]}/${i.context.budgets[N]})`}).filter((N)=>N!==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((N)=>({name:N.name,tier:N.tier,editable:N.editable,tokens:N.tokens,budget:N.budget})),tokens:h.tokens},knowledge:y===void 0?[]:y.entries.map((N)=>({name:N.name,keywords:N.keywords,tokens:N.tokens})),warnings:k},null,2)}
|
|
486
|
+
`),n;let R=me(i),K=R.map((N)=>N.role===N.configuredAs?`${N.role}=${N.modelId}`:`${N.role}=→main`).join(" "),X=R.filter((N)=>N.role===N.configuredAs),j=So({manifestPath:r.manifestPath,rawModelId:o.modelId,apiKeyEnv:i.model.main.apiKeyEnv}).flatMap((N)=>{let oe=ko(N.origin);return oe===void 0?[]:[` env ${N.variable} — ${oe}
|
|
487
|
+
`]}).join("");return process.stdout.write(`ok ${u.path}
|
|
488
|
+
id ${i.id}${i.name===void 0?"":` (${i.name})`}
|
|
489
|
+
models ${K}
|
|
490
|
+
`+j+` window ${u.window} ${Ue(R[0]?.window)} (reserveOutput ${i.context.reserveOutput}, maxOutput ${f.maxOutput})
|
|
491
|
+
`+(X.length<2?"":`${X.slice(1).map((N)=>` ${N.role.padEnd(12)} ${N.modelId} · window ${N.window.contextWindow} ${Ue(N.window)}
|
|
492
|
+
`).join("")}`)+` capabilities thinking=${f.thinking} promptCache=${f.promptCache} nativeTools=${f.nativeTools} strictSchema=${f.strictSchema}
|
|
493
|
+
`+ad(f.promptCache,i.model.main.id)+` dialect ${i.tools.dialect}
|
|
494
|
+
workspace ${S===""?"(none)":S}
|
|
495
|
+
`+(y===void 0?"":` knowledge ${y.entries.length} entries, maxActive=${y.maxActive}, budget=${y.budget}
|
|
496
|
+
`)+` 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}`}
|
|
497
|
+
schedules ${i.schedules.length===0?"none":i.schedules.map((N)=>`${N.id} (${N.kind} ${N.expr}${N.timezone===void 0?"":` ${N.timezone}`}${N.role===void 0?"":` role=${N.role}`}${N.enabled?"":", disabled"})`).join(" ")}
|
|
498
|
+
team ${i.team===void 0?"none — no delegation; `handoff` is not registered":`${i.team.members.map((N)=>`${N.id} (${N.manifest})`).join(" ")} — run one at a time`}
|
|
499
|
+
limits maxSteps=${i.limits.maxSteps} turnTimeoutMs=${i.limits.turnTimeoutMs}
|
|
500
|
+
`+k.map((N)=>` warning ${N.message}
|
|
501
|
+
`).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)}
|
|
502
|
+
`),s;throw o}}function ad(r,o){if(r!=="none")return"";return/(^|\/)claude-/i.test(o)?` promptCache none — Anthropic's OpenAI-compatible endpoint does not support
|
|
503
|
+
`+` caching at all, so no request field reaches it. Caching lives on the native
|
|
504
|
+
Messages API, which this runtime does not speak.
|
|
505
|
+
`:` promptCache none — this runtime sends no cache directives. Many endpoints cache
|
|
506
|
+
`+" a stable prefix anyway; `/context` reports what was actually charged.\n"}function uo(r){try{let o=x(r.manifestPath,{knownProviders:W,knownChannels:q,env:p([r.manifestPath])}),{manifest:a}=o,u=H(a.model.main.id,a.model.main.capabilities),{workspace:i,warnings:f}=He(o,u.promptStyle),h=[...f,...Tr(i.files.map((k)=>({name:k.name,authored:k.authored,tier:k.tier,field:k.field})))],g=Ae(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)}
|
|
507
|
+
`),r.strict===!0&&h.length>0?s:n;let v=u.promptStyle;process.stdout.write(`${o.path}
|
|
508
|
+
rendering delimiters=${v.delimiters} intensity=${v.intensity} examplesIn=${v.examplesIn}
|
|
509
|
+
total ${i.tokens.total} tokens (static ${i.tokens.static}, volatile ${i.tokens.volatile}, reminder ${i.tokens.reminder})
|
|
510
|
+
`);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}
|
|
511
|
+
`);if(h.length===0)return process.stdout.write(`
|
|
512
|
+
no findings
|
|
513
|
+
`),n;for(let k of h)process.stdout.write(`
|
|
514
|
+
${k.code}: ${k.message}
|
|
515
|
+
`),process.stdout.write(` hint: ${k.hint}
|
|
516
|
+
`);return process.stdout.write(`
|
|
517
|
+
${h.length} finding(s)
|
|
518
|
+
`),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)}
|
|
519
|
+
`),s;throw o}}function dd(r){if(r instanceof t)process.stderr.write(`${r.format()}
|
|
520
|
+
`);else if(r instanceof Error){if(process.stderr.write(`${r.message}
|
|
521
|
+
`),xe().debug&&r.stack!==void 0)process.stderr.write(`${r.stack}
|
|
522
|
+
`)}else process.stderr.write(`${String(r)}
|
|
523
|
+
`);return s}async function ld(){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 cd(r){let o=Mr(r);switch(o.kind){case"version":return process.stdout.write(`${A}
|
|
524
|
+
`),n;case"help":return process.stdout.write(gt(o.command)),n;case"usage":return process.stdout.write(gt()),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 ns({needsServer:a.needsServer,disabled:i.bool("no-bootstrap"),install:()=>ld(),...g===void 0?{}:{store:g}}),k=ts(v);if(k!==void 0)process.stderr.write(k);switch(a.name){case"init":{let y=i.str("dir"),S=i.str("user"),R=i.str("name"),K=i.str("purpose"),X=i.str("preset"),j=i.str("model"),N=i.str("base-url"),oe=i.str("api-key-env"),fe=i.str("system"),ae=i.str("web"),D=i.str("web-backend"),G=i.str("composio"),Q=i.str("telegram"),re=i.str("telegram-allow"),pe=i.str("server"),F=i.str("schedules"),ne=i.str("skills"),ke=i.str("daemon");return await Vr({...y===void 0?{}:{dir:y},...S===void 0?{}:{user:S},...R===void 0?{}:{name:R},...K===void 0?{}:{purpose:K},...X===void 0?{}:{preset:X},...j===void 0?{}:{model:j},...N===void 0?{}:{baseUrl:N},...oe===void 0?{}:{apiKeyEnv:oe},...fe===void 0?{}:{system:fe},...ae===void 0?{}:{web:ae},...D===void 0?{}:{webBackend:D},...G===void 0?{}:{composio:G},...Q===void 0?{}:{telegram:Q},...F===void 0?{}:{schedules:F},...re===void 0?{}:{telegramAllow:re},...pe===void 0?{}:{server:pe},...ne===void 0?{}:{skills:ne},...ke===void 0?{}:{daemon:ke},yes:i.bool("yes"),plain:i.bool("plain")})}case"run":{let y=i.str("session"),S=i.str("input"),R=i.str("store");return await Ct({...u[0]===void 0?{}:{manifestPath:h()},...y===void 0?{}:{sessionKey:y},continueSession:i.bool("continue"),...S===void 0?{}:{once:S},...R===void 0?{}:{store:R},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"),R=i.str("enable"),K=i.str("disable");return await Qs({manifestPath:h(),...y===void 0?{}:{store:y},...S===void 0?{}:{id:S},...R===void 0?{}:{enable:R},...K===void 0?{}:{disable:K},recipients:i.bool("recipients"),json:i.bool("json")})}case"sessions":{let y=i.str("session"),S=i.str("store"),R=i.num("limit");return await eo({manifestPath:h(),...y===void 0?{}:{sessionKey:y},...S===void 0?{}:{store:S},...R===void 0?{}:{limit:R},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 cs({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-yz0nz51b.js"),R=S(f,u[1]);return await y({action:R.action,...R.ref===void 0?{}:{ref:R.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 co({manifestPath:h(),json:i.bool("json")});case"workspace":return uo({manifestPath:h(),json:i.bool("json"),strict:i.bool("strict")});case"soul":{let y=i.str("out");return to({action:f,file:u[1],...y===void 0?{}:{out:y}})}case"skills":{if(u.length===0)return await Br({plain:i.bool("plain"),json:i.bool("json")});let y=u[2];return ve({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 ro({action:f,rest:u.slice(1),...y===void 0?{}:{path:y},...S===void 0?{}:{ref:S},json:i.bool("json")})}case"plugins":return await xs({manifestPath:te(u[0]??""),json:i.bool("json")});case"agents":return await Nt({manifestPaths:u.map((y)=>te(y)),json:i.bool("json")});case"serve":{let y=i.num("port"),S=i.str("host"),R=i.str("store");return await Zs({manifestPaths:u.map((K)=>te(K)),...y===void 0?{}:{port:y},...S===void 0?{}:{host:S},...R===void 0?{}:{store:R},claim:i.bool("claim"),json:i.bool("json")})}case"keys":return await es({noEnhancedKeys:i.bool("no-enhanced-keys")});case"terminal-setup":return await io({dryRun:i.bool("dry-run"),yes:i.bool("yes"),json:i.bool("json"),confirm:Ve});case"remove":return await Cs({...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:Rr});case"stop":{let y=i.str("reason");return await Kn({...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 so({manifestPath:h(),...i.str("store")===void 0?{}:{store:i.str("store")},json:i.bool("json")});case"web":{let{webCommand:y}=await import("./web-w7r68df1.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-wgt4gvcz.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 Ss({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 ao({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."})}}as();Wr();await cd(process.argv.slice(2)).catch(dd).then((r)=>Nn(r));
|
|
525
|
+
|
|
526
|
+
//# debugId=69CF8E8E2CACC51664756E2164756E21
|
|
527
|
+
//# sourceMappingURL=index.js.map
|